OSDN Git Service

8b92e700f27389fb490b55d35e5e14ee60f11935
[android-x86/external-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/IR/CallSite.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalAlias.h"
41 #include "llvm/IR/GlobalVariable.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/MC/MCAsmInfo.h"
45 #include "llvm/MC/MCContext.h"
46 #include "llvm/MC/MCExpr.h"
47 #include "llvm/MC/MCSymbol.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "X86IntrinsicsInfo.h"
54 #include <bitset>
55 #include <numeric>
56 #include <cctype>
57 using namespace llvm;
58
59 #define DEBUG_TYPE "x86-isel"
60
61 STATISTIC(NumTailCalls, "Number of tail calls");
62
63 static cl::opt<bool> ExperimentalVectorWideningLegalization(
64     "x86-experimental-vector-widening-legalization", cl::init(false),
65     cl::desc("Enable an experimental vector type legalization through widening "
66              "rather than promotion."),
67     cl::Hidden);
68
69 static cl::opt<int> ReciprocalEstimateRefinementSteps(
70     "x86-recip-refinement-steps", cl::init(1),
71     cl::desc("Specify the number of Newton-Raphson iterations applied to the "
72              "result of the hardware reciprocal estimate instruction."),
73     cl::NotHidden);
74
75 // Forward declarations.
76 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
77                        SDValue V2);
78
79 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
80                                      const X86Subtarget &STI)
81     : TargetLowering(TM), Subtarget(&STI) {
82   X86ScalarSSEf64 = Subtarget->hasSSE2();
83   X86ScalarSSEf32 = Subtarget->hasSSE1();
84   TD = getDataLayout();
85
86   // Set up the TargetLowering object.
87   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
88
89   // X86 is weird. It always uses i8 for shift amounts and setcc results.
90   setBooleanContents(ZeroOrOneBooleanContent);
91   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
92   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
93
94   // For 64-bit, since we have so many registers, use the ILP scheduler.
95   // For 32-bit, use the register pressure specific scheduling.
96   // For Atom, always use ILP scheduling.
97   if (Subtarget->isAtom())
98     setSchedulingPreference(Sched::ILP);
99   else if (Subtarget->is64Bit())
100     setSchedulingPreference(Sched::ILP);
101   else
102     setSchedulingPreference(Sched::RegPressure);
103   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
104   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
105
106   // Bypass expensive divides on Atom when compiling with O2.
107   if (TM.getOptLevel() >= CodeGenOpt::Default) {
108     if (Subtarget->hasSlowDivide32())
109       addBypassSlowDiv(32, 8);
110     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
111       addBypassSlowDiv(64, 16);
112   }
113
114   if (Subtarget->isTargetKnownWindowsMSVC()) {
115     // Setup Windows compiler runtime calls.
116     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
117     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
118     setLibcallName(RTLIB::SREM_I64, "_allrem");
119     setLibcallName(RTLIB::UREM_I64, "_aullrem");
120     setLibcallName(RTLIB::MUL_I64, "_allmul");
121     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
122     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
123     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
124     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
125     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
126
127     // The _ftol2 runtime function has an unusual calling conv, which
128     // is modeled by a special pseudo-instruction.
129     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
130     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
131     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
132     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
133   }
134
135   if (Subtarget->isTargetDarwin()) {
136     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
137     setUseUnderscoreSetJmp(false);
138     setUseUnderscoreLongJmp(false);
139   } else if (Subtarget->isTargetWindowsGNU()) {
140     // MS runtime is weird: it exports _setjmp, but longjmp!
141     setUseUnderscoreSetJmp(true);
142     setUseUnderscoreLongJmp(false);
143   } else {
144     setUseUnderscoreSetJmp(true);
145     setUseUnderscoreLongJmp(true);
146   }
147
148   // Set up the register classes.
149   addRegisterClass(MVT::i8, &X86::GR8RegClass);
150   addRegisterClass(MVT::i16, &X86::GR16RegClass);
151   addRegisterClass(MVT::i32, &X86::GR32RegClass);
152   if (Subtarget->is64Bit())
153     addRegisterClass(MVT::i64, &X86::GR64RegClass);
154
155   for (MVT VT : MVT::integer_valuetypes())
156     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
157
158   // We don't accept any truncstore of integer registers.
159   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
160   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
161   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
162   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
163   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
164   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
165
166   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
167
168   // SETOEQ and SETUNE require checking two conditions.
169   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
170   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
171   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
172   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
173   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
174   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
175
176   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
177   // operation.
178   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
179   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
180   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
181
182   if (Subtarget->is64Bit()) {
183     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
184     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
185   } else if (!TM.Options.UseSoftFloat) {
186     // We have an algorithm for SSE2->double, and we turn this into a
187     // 64-bit FILD followed by conditional FADD for other targets.
188     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
189     // We have an algorithm for SSE2, and we turn this into a 64-bit
190     // FILD for other targets.
191     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
192   }
193
194   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
195   // this operation.
196   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
197   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
198
199   if (!TM.Options.UseSoftFloat) {
200     // SSE has no i16 to fp conversion, only i32
201     if (X86ScalarSSEf32) {
202       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
203       // f32 and f64 cases are Legal, f80 case is not
204       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
205     } else {
206       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
207       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
208     }
209   } else {
210     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
211     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
212   }
213
214   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
215   // are Legal, f80 is custom lowered.
216   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
217   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
218
219   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
220   // this operation.
221   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
222   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
223
224   if (X86ScalarSSEf32) {
225     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
226     // f32 and f64 cases are Legal, f80 case is not
227     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
228   } else {
229     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
230     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
231   }
232
233   // Handle FP_TO_UINT by promoting the destination to a larger signed
234   // conversion.
235   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
236   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
237   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
238
239   if (Subtarget->is64Bit()) {
240     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
241     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
242   } else if (!TM.Options.UseSoftFloat) {
243     // Since AVX is a superset of SSE3, only check for SSE here.
244     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
245       // Expand FP_TO_UINT into a select.
246       // FIXME: We would like to use a Custom expander here eventually to do
247       // the optimal thing for SSE vs. the default expansion in the legalizer.
248       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
249     else
250       // With SSE3 we can use fisttpll to convert to a signed i64; without
251       // SSE, we're stuck with a fistpll.
252       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
253   }
254
255   if (isTargetFTOL()) {
256     // Use the _ftol2 runtime function, which has a pseudo-instruction
257     // to handle its weird calling convention.
258     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
259   }
260
261   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
262   if (!X86ScalarSSEf64) {
263     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
264     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
265     if (Subtarget->is64Bit()) {
266       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
267       // Without SSE, i64->f64 goes through memory.
268       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
269     }
270   }
271
272   // Scalar integer divide and remainder are lowered to use operations that
273   // produce two results, to match the available instructions. This exposes
274   // the two-result form to trivial CSE, which is able to combine x/y and x%y
275   // into a single instruction.
276   //
277   // Scalar integer multiply-high is also lowered to use two-result
278   // operations, to match the available instructions. However, plain multiply
279   // (low) operations are left as Legal, as there are single-result
280   // instructions for this in x86. Using the two-result multiply instructions
281   // when both high and low results are needed must be arranged by dagcombine.
282   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
283     MVT VT = IntVTs[i];
284     setOperationAction(ISD::MULHS, VT, Expand);
285     setOperationAction(ISD::MULHU, VT, Expand);
286     setOperationAction(ISD::SDIV, VT, Expand);
287     setOperationAction(ISD::UDIV, VT, Expand);
288     setOperationAction(ISD::SREM, VT, Expand);
289     setOperationAction(ISD::UREM, VT, Expand);
290
291     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
292     setOperationAction(ISD::ADDC, VT, Custom);
293     setOperationAction(ISD::ADDE, VT, Custom);
294     setOperationAction(ISD::SUBC, VT, Custom);
295     setOperationAction(ISD::SUBE, VT, Custom);
296   }
297
298   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
299   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
300   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
301   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
302   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
303   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
304   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
305   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
306   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
309   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
310   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
311   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
312   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
313   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
314   if (Subtarget->is64Bit())
315     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
316   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
317   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
318   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
319   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
320   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
321   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
322   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
323   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
324
325   // Promote the i8 variants and force them on up to i32 which has a shorter
326   // encoding.
327   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
328   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
329   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
330   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
331   if (Subtarget->hasBMI()) {
332     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
333     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
334     if (Subtarget->is64Bit())
335       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
336   } else {
337     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
338     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
339     if (Subtarget->is64Bit())
340       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
341   }
342
343   if (Subtarget->hasLZCNT()) {
344     // When promoting the i8 variants, force them to i32 for a shorter
345     // encoding.
346     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
347     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
348     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
349     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
350     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
351     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
352     if (Subtarget->is64Bit())
353       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
354   } else {
355     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
356     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
357     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
358     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
359     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
360     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
361     if (Subtarget->is64Bit()) {
362       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
363       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
364     }
365   }
366
367   // Special handling for half-precision floating point conversions.
368   // If we don't have F16C support, then lower half float conversions
369   // into library calls.
370   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
371     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
372     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
373   }
374
375   // There's never any support for operations beyond MVT::f32.
376   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
377   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
378   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
379   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
380
381   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
382   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
383   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
384   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
385   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
386   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
387
388   if (Subtarget->hasPOPCNT()) {
389     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
390   } else {
391     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
392     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
393     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
394     if (Subtarget->is64Bit())
395       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
396   }
397
398   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
399
400   if (!Subtarget->hasMOVBE())
401     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
402
403   // These should be promoted to a larger select which is supported.
404   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
405   // X86 wants to expand cmov itself.
406   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
407   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
408   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
409   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
410   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
411   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
412   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
413   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
414   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
415   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
416   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
417   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
418   if (Subtarget->is64Bit()) {
419     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
420     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
421   }
422   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
423   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
424   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
425   // support continuation, user-level threading, and etc.. As a result, no
426   // other SjLj exception interfaces are implemented and please don't build
427   // your own exception handling based on them.
428   // LLVM/Clang supports zero-cost DWARF exception handling.
429   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
430   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
431
432   // Darwin ABI issue.
433   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
434   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
435   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
436   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
437   if (Subtarget->is64Bit())
438     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
439   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
440   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
441   if (Subtarget->is64Bit()) {
442     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
443     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
444     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
445     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
446     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
447   }
448   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
449   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
450   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
451   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
452   if (Subtarget->is64Bit()) {
453     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
454     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
455     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
456   }
457
458   if (Subtarget->hasSSE1())
459     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
460
461   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
462
463   // Expand certain atomics
464   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
465     MVT VT = IntVTs[i];
466     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
467     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
468     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
469   }
470
471   if (Subtarget->hasCmpxchg16b()) {
472     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
473   }
474
475   // FIXME - use subtarget debug flags
476   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
477       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
478     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
479   }
480
481   if (Subtarget->is64Bit()) {
482     setExceptionPointerRegister(X86::RAX);
483     setExceptionSelectorRegister(X86::RDX);
484   } else {
485     setExceptionPointerRegister(X86::EAX);
486     setExceptionSelectorRegister(X86::EDX);
487   }
488   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
489   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
490
491   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
492   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
493
494   setOperationAction(ISD::TRAP, MVT::Other, Legal);
495   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
496
497   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
498   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
499   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
500   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
501     // TargetInfo::X86_64ABIBuiltinVaList
502     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
503     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
504   } else {
505     // TargetInfo::CharPtrBuiltinVaList
506     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
507     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
508   }
509
510   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
511   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
512
513   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
514
515   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
516     // f32 and f64 use SSE.
517     // Set up the FP register classes.
518     addRegisterClass(MVT::f32, &X86::FR32RegClass);
519     addRegisterClass(MVT::f64, &X86::FR64RegClass);
520
521     // Use ANDPD to simulate FABS.
522     setOperationAction(ISD::FABS , MVT::f64, Custom);
523     setOperationAction(ISD::FABS , MVT::f32, Custom);
524
525     // Use XORP to simulate FNEG.
526     setOperationAction(ISD::FNEG , MVT::f64, Custom);
527     setOperationAction(ISD::FNEG , MVT::f32, Custom);
528
529     // Use ANDPD and ORPD to simulate FCOPYSIGN.
530     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
531     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
532
533     // Lower this to FGETSIGNx86 plus an AND.
534     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
535     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
536
537     // We don't support sin/cos/fmod
538     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
539     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
540     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
541     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
542     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
543     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
544
545     // Expand FP immediates into loads from the stack, except for the special
546     // cases we handle.
547     addLegalFPImmediate(APFloat(+0.0)); // xorpd
548     addLegalFPImmediate(APFloat(+0.0f)); // xorps
549   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
550     // Use SSE for f32, x87 for f64.
551     // Set up the FP register classes.
552     addRegisterClass(MVT::f32, &X86::FR32RegClass);
553     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
554
555     // Use ANDPS to simulate FABS.
556     setOperationAction(ISD::FABS , MVT::f32, Custom);
557
558     // Use XORP to simulate FNEG.
559     setOperationAction(ISD::FNEG , MVT::f32, Custom);
560
561     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
562
563     // Use ANDPS and ORPS to simulate FCOPYSIGN.
564     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
565     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
566
567     // We don't support sin/cos/fmod
568     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
569     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
570     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
571
572     // Special cases we handle for FP constants.
573     addLegalFPImmediate(APFloat(+0.0f)); // xorps
574     addLegalFPImmediate(APFloat(+0.0)); // FLD0
575     addLegalFPImmediate(APFloat(+1.0)); // FLD1
576     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
577     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
578
579     if (!TM.Options.UnsafeFPMath) {
580       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
581       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
582       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
583     }
584   } else if (!TM.Options.UseSoftFloat) {
585     // f32 and f64 in x87.
586     // Set up the FP register classes.
587     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
588     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
589
590     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
591     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
592     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
593     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
594
595     if (!TM.Options.UnsafeFPMath) {
596       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
597       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
598       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
599       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
600       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
601       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
602     }
603     addLegalFPImmediate(APFloat(+0.0)); // FLD0
604     addLegalFPImmediate(APFloat(+1.0)); // FLD1
605     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
606     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
607     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
608     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
609     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
610     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
611   }
612
613   // We don't support FMA.
614   setOperationAction(ISD::FMA, MVT::f64, Expand);
615   setOperationAction(ISD::FMA, MVT::f32, Expand);
616
617   // Long double always uses X87.
618   if (!TM.Options.UseSoftFloat) {
619     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
620     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
621     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
622     {
623       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
624       addLegalFPImmediate(TmpFlt);  // FLD0
625       TmpFlt.changeSign();
626       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
627
628       bool ignored;
629       APFloat TmpFlt2(+1.0);
630       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
631                       &ignored);
632       addLegalFPImmediate(TmpFlt2);  // FLD1
633       TmpFlt2.changeSign();
634       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
635     }
636
637     if (!TM.Options.UnsafeFPMath) {
638       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
639       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
640       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
641     }
642
643     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
644     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
645     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
646     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
647     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
648     setOperationAction(ISD::FMA, MVT::f80, Expand);
649   }
650
651   // Always use a library call for pow.
652   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
653   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
654   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
655
656   setOperationAction(ISD::FLOG, MVT::f80, Expand);
657   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
658   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
659   setOperationAction(ISD::FEXP, MVT::f80, Expand);
660   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
661   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
662   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
663
664   // First set operation action for all vector types to either promote
665   // (for widening) or expand (for scalarization). Then we will selectively
666   // turn on ones that can be effectively codegen'd.
667   for (MVT VT : MVT::vector_valuetypes()) {
668     setOperationAction(ISD::ADD , VT, Expand);
669     setOperationAction(ISD::SUB , VT, Expand);
670     setOperationAction(ISD::FADD, VT, Expand);
671     setOperationAction(ISD::FNEG, VT, Expand);
672     setOperationAction(ISD::FSUB, VT, Expand);
673     setOperationAction(ISD::MUL , VT, Expand);
674     setOperationAction(ISD::FMUL, VT, Expand);
675     setOperationAction(ISD::SDIV, VT, Expand);
676     setOperationAction(ISD::UDIV, VT, Expand);
677     setOperationAction(ISD::FDIV, VT, Expand);
678     setOperationAction(ISD::SREM, VT, Expand);
679     setOperationAction(ISD::UREM, VT, Expand);
680     setOperationAction(ISD::LOAD, VT, Expand);
681     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
682     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
683     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
684     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
685     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
686     setOperationAction(ISD::FABS, VT, Expand);
687     setOperationAction(ISD::FSIN, VT, Expand);
688     setOperationAction(ISD::FSINCOS, VT, Expand);
689     setOperationAction(ISD::FCOS, VT, Expand);
690     setOperationAction(ISD::FSINCOS, VT, Expand);
691     setOperationAction(ISD::FREM, VT, Expand);
692     setOperationAction(ISD::FMA,  VT, Expand);
693     setOperationAction(ISD::FPOWI, VT, Expand);
694     setOperationAction(ISD::FSQRT, VT, Expand);
695     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
696     setOperationAction(ISD::FFLOOR, VT, Expand);
697     setOperationAction(ISD::FCEIL, VT, Expand);
698     setOperationAction(ISD::FTRUNC, VT, Expand);
699     setOperationAction(ISD::FRINT, VT, Expand);
700     setOperationAction(ISD::FNEARBYINT, VT, Expand);
701     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
702     setOperationAction(ISD::MULHS, VT, Expand);
703     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
704     setOperationAction(ISD::MULHU, VT, Expand);
705     setOperationAction(ISD::SDIVREM, VT, Expand);
706     setOperationAction(ISD::UDIVREM, VT, Expand);
707     setOperationAction(ISD::FPOW, VT, Expand);
708     setOperationAction(ISD::CTPOP, VT, Expand);
709     setOperationAction(ISD::CTTZ, VT, Expand);
710     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
711     setOperationAction(ISD::CTLZ, VT, Expand);
712     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
713     setOperationAction(ISD::SHL, VT, Expand);
714     setOperationAction(ISD::SRA, VT, Expand);
715     setOperationAction(ISD::SRL, VT, Expand);
716     setOperationAction(ISD::ROTL, VT, Expand);
717     setOperationAction(ISD::ROTR, VT, Expand);
718     setOperationAction(ISD::BSWAP, VT, Expand);
719     setOperationAction(ISD::SETCC, VT, Expand);
720     setOperationAction(ISD::FLOG, VT, Expand);
721     setOperationAction(ISD::FLOG2, VT, Expand);
722     setOperationAction(ISD::FLOG10, VT, Expand);
723     setOperationAction(ISD::FEXP, VT, Expand);
724     setOperationAction(ISD::FEXP2, VT, Expand);
725     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
726     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
727     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
728     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
729     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
730     setOperationAction(ISD::TRUNCATE, VT, Expand);
731     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
732     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
733     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
734     setOperationAction(ISD::VSELECT, VT, Expand);
735     setOperationAction(ISD::SELECT_CC, VT, Expand);
736     for (MVT InnerVT : MVT::vector_valuetypes()) {
737       setTruncStoreAction(InnerVT, VT, Expand);
738
739       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
740       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
741
742       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
743       // types, we have to deal with them whether we ask for Expansion or not.
744       // Setting Expand causes its own optimisation problems though, so leave
745       // them legal.
746       if (VT.getVectorElementType() == MVT::i1)
747         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
748     }
749   }
750
751   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
752   // with -msoft-float, disable use of MMX as well.
753   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
754     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
755     // No operations on x86mmx supported, everything uses intrinsics.
756   }
757
758   // MMX-sized vectors (other than x86mmx) are expected to be expanded
759   // into smaller operations.
760   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
761     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
762     setOperationAction(ISD::AND,                MMXTy,      Expand);
763     setOperationAction(ISD::OR,                 MMXTy,      Expand);
764     setOperationAction(ISD::XOR,                MMXTy,      Expand);
765     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
766     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
767     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
768   }
769   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
770
771   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
772     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
773
774     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
775     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
776     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
777     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
778     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
779     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
780     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
781     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
782     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
783     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
784     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
785     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
786     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
787     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
788   }
789
790   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
791     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
792
793     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
794     // registers cannot be used even for integer operations.
795     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
796     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
797     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
798     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
799
800     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
801     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
802     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
803     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
804     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
805     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
806     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
807     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
808     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
809     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
810     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
811     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
812     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
813     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
814     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
815     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
816     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
817     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
818     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
819     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
820     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
821     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
822
823     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
824     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
825     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
826     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
827
828     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
829     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
830     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
831     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
832     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
833
834     // Only provide customized ctpop vector bit twiddling for vector types we
835     // know to perform better than using the popcnt instructions on each vector
836     // element. If popcnt isn't supported, always provide the custom version.
837     if (!Subtarget->hasPOPCNT()) {
838       setOperationAction(ISD::CTPOP,            MVT::v4i32, Custom);
839       setOperationAction(ISD::CTPOP,            MVT::v2i64, Custom);
840     }
841
842     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
843     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
844       MVT VT = (MVT::SimpleValueType)i;
845       // Do not attempt to custom lower non-power-of-2 vectors
846       if (!isPowerOf2_32(VT.getVectorNumElements()))
847         continue;
848       // Do not attempt to custom lower non-128-bit vectors
849       if (!VT.is128BitVector())
850         continue;
851       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
852       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
853       setOperationAction(ISD::VSELECT,            VT, Custom);
854       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
855     }
856
857     // We support custom legalizing of sext and anyext loads for specific
858     // memory vector types which we can load as a scalar (or sequence of
859     // scalars) and extend in-register to a legal 128-bit vector type. For sext
860     // loads these must work with a single scalar load.
861     for (MVT VT : MVT::integer_vector_valuetypes()) {
862       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
863       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
864       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
865       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
866       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
867       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
868       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
869       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
870       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
871     }
872
873     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
874     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
875     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
876     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
877     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
878     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
879     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
880     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
881
882     if (Subtarget->is64Bit()) {
883       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
884       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
885     }
886
887     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
888     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
889       MVT VT = (MVT::SimpleValueType)i;
890
891       // Do not attempt to promote non-128-bit vectors
892       if (!VT.is128BitVector())
893         continue;
894
895       setOperationAction(ISD::AND,    VT, Promote);
896       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
897       setOperationAction(ISD::OR,     VT, Promote);
898       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
899       setOperationAction(ISD::XOR,    VT, Promote);
900       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
901       setOperationAction(ISD::LOAD,   VT, Promote);
902       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
903       setOperationAction(ISD::SELECT, VT, Promote);
904       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
905     }
906
907     // Custom lower v2i64 and v2f64 selects.
908     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
909     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
910     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
911     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
912
913     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
914     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
915
916     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
917     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
918     // As there is no 64-bit GPR available, we need build a special custom
919     // sequence to convert from v2i32 to v2f32.
920     if (!Subtarget->is64Bit())
921       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
922
923     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
924     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
925
926     for (MVT VT : MVT::fp_vector_valuetypes())
927       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
928
929     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
930     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
931     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
932   }
933
934   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
935     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
936       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
937       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
938       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
939       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
940       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
941     }
942
943     // FIXME: Do we need to handle scalar-to-vector here?
944     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
945
946     // We directly match byte blends in the backend as they match the VSELECT
947     // condition form.
948     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
949
950     // SSE41 brings specific instructions for doing vector sign extend even in
951     // cases where we don't have SRA.
952     for (MVT VT : MVT::integer_vector_valuetypes()) {
953       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
954       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
955       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
956     }
957
958     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
959     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
960     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
961     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
962     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
963     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
964     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
965
966     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
967     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
968     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
969     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
970     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
971     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
972
973     // i8 and i16 vectors are custom because the source register and source
974     // source memory operand types are not the same width.  f32 vectors are
975     // custom since the immediate controlling the insert encodes additional
976     // information.
977     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
978     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
979     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
980     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
981
982     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
983     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
984     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
985     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
986
987     // FIXME: these should be Legal, but that's only for the case where
988     // the index is constant.  For now custom expand to deal with that.
989     if (Subtarget->is64Bit()) {
990       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
991       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
992     }
993   }
994
995   if (Subtarget->hasSSE2()) {
996     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
997     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
998
999     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1000     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1001
1002     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1003     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1004
1005     // In the customized shift lowering, the legal cases in AVX2 will be
1006     // recognized.
1007     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1008     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1009
1010     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1011     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1012
1013     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1014   }
1015
1016   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1017     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1018     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1019     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1020     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1021     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1022     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1023
1024     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1025     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1026     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1027
1028     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1029     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1030     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1031     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1032     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1033     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1034     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1035     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1036     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1037     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1038     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1039     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1040
1041     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1042     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1043     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1044     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1045     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1046     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1047     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1048     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1049     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1050     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1051     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1052     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1053
1054     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1055     // even though v8i16 is a legal type.
1056     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1057     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1058     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1059
1060     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1061     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1062     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1063
1064     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1065     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1066
1067     for (MVT VT : MVT::fp_vector_valuetypes())
1068       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1069
1070     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1071     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1072
1073     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1074     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1075
1076     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1077     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1078
1079     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1080     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1081     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1082     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1083
1084     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1085     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1086     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1087
1088     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1089     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1090     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1091     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1092     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1093     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1094     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1095     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1096     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1097     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1098     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1099     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1100
1101     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1102       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1103       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1104       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1105       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1106       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1107       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1108     }
1109
1110     if (Subtarget->hasInt256()) {
1111       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1112       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1113       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1114       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1115
1116       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1117       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1118       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1119       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1120
1121       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1122       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1123       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1124       // Don't lower v32i8 because there is no 128-bit byte mul
1125
1126       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1127       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1128       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1129       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1130
1131       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1132       // when we have a 256bit-wide blend with immediate.
1133       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1134
1135       // Only provide customized ctpop vector bit twiddling for vector types we
1136       // know to perform better than using the popcnt instructions on each
1137       // vector element. If popcnt isn't supported, always provide the custom
1138       // version.
1139       if (!Subtarget->hasPOPCNT())
1140         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1141
1142       // Custom CTPOP always performs better on natively supported v8i32
1143       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1144
1145       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1146       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1147       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1148       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1149       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1150       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1151       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1152
1153       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1154       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1155       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1156       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1157       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1158       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1159     } else {
1160       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1161       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1162       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1163       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1164
1165       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1166       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1167       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1168       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1169
1170       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1171       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1172       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1173       // Don't lower v32i8 because there is no 128-bit byte mul
1174     }
1175
1176     // In the customized shift lowering, the legal cases in AVX2 will be
1177     // recognized.
1178     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1179     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1180
1181     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1182     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1183
1184     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1185
1186     // Custom lower several nodes for 256-bit types.
1187     for (MVT VT : MVT::vector_valuetypes()) {
1188       if (VT.getScalarSizeInBits() >= 32) {
1189         setOperationAction(ISD::MLOAD,  VT, Legal);
1190         setOperationAction(ISD::MSTORE, VT, Legal);
1191       }
1192       // Extract subvector is special because the value type
1193       // (result) is 128-bit but the source is 256-bit wide.
1194       if (VT.is128BitVector()) {
1195         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1196       }
1197       // Do not attempt to custom lower other non-256-bit vectors
1198       if (!VT.is256BitVector())
1199         continue;
1200
1201       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1202       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1203       setOperationAction(ISD::VSELECT,            VT, Custom);
1204       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1205       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1206       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1207       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1208       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1209     }
1210
1211     if (Subtarget->hasInt256())
1212       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1213
1214
1215     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1216     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1217       MVT VT = (MVT::SimpleValueType)i;
1218
1219       // Do not attempt to promote non-256-bit vectors
1220       if (!VT.is256BitVector())
1221         continue;
1222
1223       setOperationAction(ISD::AND,    VT, Promote);
1224       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1225       setOperationAction(ISD::OR,     VT, Promote);
1226       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1227       setOperationAction(ISD::XOR,    VT, Promote);
1228       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1229       setOperationAction(ISD::LOAD,   VT, Promote);
1230       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1231       setOperationAction(ISD::SELECT, VT, Promote);
1232       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1233     }
1234   }
1235
1236   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1237     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1238     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1239     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1240     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1241
1242     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1243     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1244     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1245
1246     for (MVT VT : MVT::fp_vector_valuetypes())
1247       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1248
1249     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1250     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1251     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1252     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1253     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1254     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1255     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1256     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1257     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1258     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1259
1260     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1261     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1262     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1263     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1264     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1265     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1266
1267     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1268     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1269     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1270     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1271     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1272     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1273     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1274     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1275
1276     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1277     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1278     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1279     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1280     if (Subtarget->is64Bit()) {
1281       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1282       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1283       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1284       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1285     }
1286     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1287     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1288     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1289     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1290     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1291     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1292     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1293     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1294     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1295     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1296     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1297     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1298     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1299     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1300
1301     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1302     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1303     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1304     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1305     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1306     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1307     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1308     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1309     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1310     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1311     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1312     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1313     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1314
1315     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1316     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1317     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1318     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1319     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1320     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1321     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1322     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1323     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1324     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1325
1326     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1327     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1328     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1329     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1330     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1331
1332     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1333     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1334
1335     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1336
1337     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1338     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1339     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1340     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1341     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1342     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1343     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1344     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1345     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1346
1347     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1348     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1349
1350     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1351     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1352
1353     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1354
1355     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1356     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1357
1358     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1359     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1360
1361     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1362     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1363
1364     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1365     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1366     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1367     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1368     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1369     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1370
1371     if (Subtarget->hasCDI()) {
1372       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1373       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1374     }
1375
1376     // Custom lower several nodes.
1377     for (MVT VT : MVT::vector_valuetypes()) {
1378       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1379       // Extract subvector is special because the value type
1380       // (result) is 256/128-bit but the source is 512-bit wide.
1381       if (VT.is128BitVector() || VT.is256BitVector()) {
1382         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1383       }
1384       if (VT.getVectorElementType() == MVT::i1)
1385         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1386
1387       // Do not attempt to custom lower other non-512-bit vectors
1388       if (!VT.is512BitVector())
1389         continue;
1390
1391       if ( EltSize >= 32) {
1392         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1393         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1394         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1395         setOperationAction(ISD::VSELECT,             VT, Legal);
1396         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1397         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1398         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1399         setOperationAction(ISD::MLOAD,               VT, Legal);
1400         setOperationAction(ISD::MSTORE,              VT, Legal);
1401       }
1402     }
1403     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1404       MVT VT = (MVT::SimpleValueType)i;
1405
1406       // Do not attempt to promote non-512-bit vectors.
1407       if (!VT.is512BitVector())
1408         continue;
1409
1410       setOperationAction(ISD::SELECT, VT, Promote);
1411       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1412     }
1413   }// has  AVX-512
1414
1415   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1416     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1417     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1418
1419     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1420     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1421
1422     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1423     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1424     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1425     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1426     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1427     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1428     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1429     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1430     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1431     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1432     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1433     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1434     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1435
1436     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1437       const MVT VT = (MVT::SimpleValueType)i;
1438
1439       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1440
1441       // Do not attempt to promote non-512-bit vectors.
1442       if (!VT.is512BitVector())
1443         continue;
1444
1445       if (EltSize < 32) {
1446         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1447         setOperationAction(ISD::VSELECT,             VT, Legal);
1448       }
1449     }
1450   }
1451
1452   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1453     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1454     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1455
1456     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1457     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1458     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1459     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1460     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1461     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1462
1463     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1464     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1465     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1466     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1467     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1468     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1469   }
1470
1471   // We want to custom lower some of our intrinsics.
1472   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1473   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1474   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1475   if (!Subtarget->is64Bit())
1476     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1477
1478   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1479   // handle type legalization for these operations here.
1480   //
1481   // FIXME: We really should do custom legalization for addition and
1482   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1483   // than generic legalization for 64-bit multiplication-with-overflow, though.
1484   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1485     // Add/Sub/Mul with overflow operations are custom lowered.
1486     MVT VT = IntVTs[i];
1487     setOperationAction(ISD::SADDO, VT, Custom);
1488     setOperationAction(ISD::UADDO, VT, Custom);
1489     setOperationAction(ISD::SSUBO, VT, Custom);
1490     setOperationAction(ISD::USUBO, VT, Custom);
1491     setOperationAction(ISD::SMULO, VT, Custom);
1492     setOperationAction(ISD::UMULO, VT, Custom);
1493   }
1494
1495
1496   if (!Subtarget->is64Bit()) {
1497     // These libcalls are not available in 32-bit.
1498     setLibcallName(RTLIB::SHL_I128, nullptr);
1499     setLibcallName(RTLIB::SRL_I128, nullptr);
1500     setLibcallName(RTLIB::SRA_I128, nullptr);
1501   }
1502
1503   // Combine sin / cos into one node or libcall if possible.
1504   if (Subtarget->hasSinCos()) {
1505     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1506     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1507     if (Subtarget->isTargetDarwin()) {
1508       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1509       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1510       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1511       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1512     }
1513   }
1514
1515   if (Subtarget->isTargetWin64()) {
1516     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1517     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1518     setOperationAction(ISD::SREM, MVT::i128, Custom);
1519     setOperationAction(ISD::UREM, MVT::i128, Custom);
1520     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1521     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1522   }
1523
1524   // We have target-specific dag combine patterns for the following nodes:
1525   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1526   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1527   setTargetDAGCombine(ISD::BITCAST);
1528   setTargetDAGCombine(ISD::VSELECT);
1529   setTargetDAGCombine(ISD::SELECT);
1530   setTargetDAGCombine(ISD::SHL);
1531   setTargetDAGCombine(ISD::SRA);
1532   setTargetDAGCombine(ISD::SRL);
1533   setTargetDAGCombine(ISD::OR);
1534   setTargetDAGCombine(ISD::AND);
1535   setTargetDAGCombine(ISD::ADD);
1536   setTargetDAGCombine(ISD::FADD);
1537   setTargetDAGCombine(ISD::FSUB);
1538   setTargetDAGCombine(ISD::FMA);
1539   setTargetDAGCombine(ISD::SUB);
1540   setTargetDAGCombine(ISD::LOAD);
1541   setTargetDAGCombine(ISD::MLOAD);
1542   setTargetDAGCombine(ISD::STORE);
1543   setTargetDAGCombine(ISD::MSTORE);
1544   setTargetDAGCombine(ISD::ZERO_EXTEND);
1545   setTargetDAGCombine(ISD::ANY_EXTEND);
1546   setTargetDAGCombine(ISD::SIGN_EXTEND);
1547   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1548   setTargetDAGCombine(ISD::TRUNCATE);
1549   setTargetDAGCombine(ISD::SINT_TO_FP);
1550   setTargetDAGCombine(ISD::SETCC);
1551   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1552   setTargetDAGCombine(ISD::BUILD_VECTOR);
1553   setTargetDAGCombine(ISD::MUL);
1554   setTargetDAGCombine(ISD::XOR);
1555
1556   computeRegisterProperties(Subtarget->getRegisterInfo());
1557
1558   // On Darwin, -Os means optimize for size without hurting performance,
1559   // do not reduce the limit.
1560   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1561   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1562   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1563   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1564   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1565   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1566   setPrefLoopAlignment(4); // 2^4 bytes.
1567
1568   // Predictable cmov don't hurt on atom because it's in-order.
1569   PredictableSelectIsExpensive = !Subtarget->isAtom();
1570   EnableExtLdPromotion = true;
1571   setPrefFunctionAlignment(4); // 2^4 bytes.
1572
1573   verifyIntrinsicTables();
1574 }
1575
1576 // This has so far only been implemented for 64-bit MachO.
1577 bool X86TargetLowering::useLoadStackGuardNode() const {
1578   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1579 }
1580
1581 TargetLoweringBase::LegalizeTypeAction
1582 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1583   if (ExperimentalVectorWideningLegalization &&
1584       VT.getVectorNumElements() != 1 &&
1585       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1586     return TypeWidenVector;
1587
1588   return TargetLoweringBase::getPreferredVectorAction(VT);
1589 }
1590
1591 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1592   if (!VT.isVector())
1593     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1594
1595   const unsigned NumElts = VT.getVectorNumElements();
1596   const EVT EltVT = VT.getVectorElementType();
1597   if (VT.is512BitVector()) {
1598     if (Subtarget->hasAVX512())
1599       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1600           EltVT == MVT::f32 || EltVT == MVT::f64)
1601         switch(NumElts) {
1602         case  8: return MVT::v8i1;
1603         case 16: return MVT::v16i1;
1604       }
1605     if (Subtarget->hasBWI())
1606       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1607         switch(NumElts) {
1608         case 32: return MVT::v32i1;
1609         case 64: return MVT::v64i1;
1610       }
1611   }
1612
1613   if (VT.is256BitVector() || VT.is128BitVector()) {
1614     if (Subtarget->hasVLX())
1615       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1616           EltVT == MVT::f32 || EltVT == MVT::f64)
1617         switch(NumElts) {
1618         case 2: return MVT::v2i1;
1619         case 4: return MVT::v4i1;
1620         case 8: return MVT::v8i1;
1621       }
1622     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1623       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1624         switch(NumElts) {
1625         case  8: return MVT::v8i1;
1626         case 16: return MVT::v16i1;
1627         case 32: return MVT::v32i1;
1628       }
1629   }
1630
1631   return VT.changeVectorElementTypeToInteger();
1632 }
1633
1634 /// Helper for getByValTypeAlignment to determine
1635 /// the desired ByVal argument alignment.
1636 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1637   if (MaxAlign == 16)
1638     return;
1639   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1640     if (VTy->getBitWidth() == 128)
1641       MaxAlign = 16;
1642   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1643     unsigned EltAlign = 0;
1644     getMaxByValAlign(ATy->getElementType(), EltAlign);
1645     if (EltAlign > MaxAlign)
1646       MaxAlign = EltAlign;
1647   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1648     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1649       unsigned EltAlign = 0;
1650       getMaxByValAlign(STy->getElementType(i), EltAlign);
1651       if (EltAlign > MaxAlign)
1652         MaxAlign = EltAlign;
1653       if (MaxAlign == 16)
1654         break;
1655     }
1656   }
1657 }
1658
1659 /// Return the desired alignment for ByVal aggregate
1660 /// function arguments in the caller parameter area. For X86, aggregates
1661 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1662 /// are at 4-byte boundaries.
1663 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1664   if (Subtarget->is64Bit()) {
1665     // Max of 8 and alignment of type.
1666     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1667     if (TyAlign > 8)
1668       return TyAlign;
1669     return 8;
1670   }
1671
1672   unsigned Align = 4;
1673   if (Subtarget->hasSSE1())
1674     getMaxByValAlign(Ty, Align);
1675   return Align;
1676 }
1677
1678 /// Returns the target specific optimal type for load
1679 /// and store operations as a result of memset, memcpy, and memmove
1680 /// lowering. If DstAlign is zero that means it's safe to destination
1681 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1682 /// means there isn't a need to check it against alignment requirement,
1683 /// probably because the source does not need to be loaded. If 'IsMemset' is
1684 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1685 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1686 /// source is constant so it does not need to be loaded.
1687 /// It returns EVT::Other if the type should be determined using generic
1688 /// target-independent logic.
1689 EVT
1690 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1691                                        unsigned DstAlign, unsigned SrcAlign,
1692                                        bool IsMemset, bool ZeroMemset,
1693                                        bool MemcpyStrSrc,
1694                                        MachineFunction &MF) const {
1695   const Function *F = MF.getFunction();
1696   if ((!IsMemset || ZeroMemset) &&
1697       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1698     if (Size >= 16 &&
1699         (Subtarget->isUnalignedMemAccessFast() ||
1700          ((DstAlign == 0 || DstAlign >= 16) &&
1701           (SrcAlign == 0 || SrcAlign >= 16)))) {
1702       if (Size >= 32) {
1703         if (Subtarget->hasInt256())
1704           return MVT::v8i32;
1705         if (Subtarget->hasFp256())
1706           return MVT::v8f32;
1707       }
1708       if (Subtarget->hasSSE2())
1709         return MVT::v4i32;
1710       if (Subtarget->hasSSE1())
1711         return MVT::v4f32;
1712     } else if (!MemcpyStrSrc && Size >= 8 &&
1713                !Subtarget->is64Bit() &&
1714                Subtarget->hasSSE2()) {
1715       // Do not use f64 to lower memcpy if source is string constant. It's
1716       // better to use i32 to avoid the loads.
1717       return MVT::f64;
1718     }
1719   }
1720   if (Subtarget->is64Bit() && Size >= 8)
1721     return MVT::i64;
1722   return MVT::i32;
1723 }
1724
1725 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1726   if (VT == MVT::f32)
1727     return X86ScalarSSEf32;
1728   else if (VT == MVT::f64)
1729     return X86ScalarSSEf64;
1730   return true;
1731 }
1732
1733 bool
1734 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1735                                                   unsigned,
1736                                                   unsigned,
1737                                                   bool *Fast) const {
1738   if (Fast)
1739     *Fast = Subtarget->isUnalignedMemAccessFast();
1740   return true;
1741 }
1742
1743 /// Return the entry encoding for a jump table in the
1744 /// current function.  The returned value is a member of the
1745 /// MachineJumpTableInfo::JTEntryKind enum.
1746 unsigned X86TargetLowering::getJumpTableEncoding() const {
1747   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1748   // symbol.
1749   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1750       Subtarget->isPICStyleGOT())
1751     return MachineJumpTableInfo::EK_Custom32;
1752
1753   // Otherwise, use the normal jump table encoding heuristics.
1754   return TargetLowering::getJumpTableEncoding();
1755 }
1756
1757 const MCExpr *
1758 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1759                                              const MachineBasicBlock *MBB,
1760                                              unsigned uid,MCContext &Ctx) const{
1761   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1762          Subtarget->isPICStyleGOT());
1763   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1764   // entries.
1765   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1766                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1767 }
1768
1769 /// Returns relocation base for the given PIC jumptable.
1770 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1771                                                     SelectionDAG &DAG) const {
1772   if (!Subtarget->is64Bit())
1773     // This doesn't have SDLoc associated with it, but is not really the
1774     // same as a Register.
1775     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1776   return Table;
1777 }
1778
1779 /// This returns the relocation base for the given PIC jumptable,
1780 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1781 const MCExpr *X86TargetLowering::
1782 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1783                              MCContext &Ctx) const {
1784   // X86-64 uses RIP relative addressing based on the jump table label.
1785   if (Subtarget->isPICStyleRIPRel())
1786     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1787
1788   // Otherwise, the reference is relative to the PIC base.
1789   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1790 }
1791
1792 std::pair<const TargetRegisterClass *, uint8_t>
1793 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1794                                            MVT VT) const {
1795   const TargetRegisterClass *RRC = nullptr;
1796   uint8_t Cost = 1;
1797   switch (VT.SimpleTy) {
1798   default:
1799     return TargetLowering::findRepresentativeClass(TRI, VT);
1800   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1801     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1802     break;
1803   case MVT::x86mmx:
1804     RRC = &X86::VR64RegClass;
1805     break;
1806   case MVT::f32: case MVT::f64:
1807   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1808   case MVT::v4f32: case MVT::v2f64:
1809   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1810   case MVT::v4f64:
1811     RRC = &X86::VR128RegClass;
1812     break;
1813   }
1814   return std::make_pair(RRC, Cost);
1815 }
1816
1817 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1818                                                unsigned &Offset) const {
1819   if (!Subtarget->isTargetLinux())
1820     return false;
1821
1822   if (Subtarget->is64Bit()) {
1823     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1824     Offset = 0x28;
1825     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1826       AddressSpace = 256;
1827     else
1828       AddressSpace = 257;
1829   } else {
1830     // %gs:0x14 on i386
1831     Offset = 0x14;
1832     AddressSpace = 256;
1833   }
1834   return true;
1835 }
1836
1837 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1838                                             unsigned DestAS) const {
1839   assert(SrcAS != DestAS && "Expected different address spaces!");
1840
1841   return SrcAS < 256 && DestAS < 256;
1842 }
1843
1844 //===----------------------------------------------------------------------===//
1845 //               Return Value Calling Convention Implementation
1846 //===----------------------------------------------------------------------===//
1847
1848 #include "X86GenCallingConv.inc"
1849
1850 bool
1851 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1852                                   MachineFunction &MF, bool isVarArg,
1853                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1854                         LLVMContext &Context) const {
1855   SmallVector<CCValAssign, 16> RVLocs;
1856   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1857   return CCInfo.CheckReturn(Outs, RetCC_X86);
1858 }
1859
1860 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1861   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1862   return ScratchRegs;
1863 }
1864
1865 SDValue
1866 X86TargetLowering::LowerReturn(SDValue Chain,
1867                                CallingConv::ID CallConv, bool isVarArg,
1868                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1869                                const SmallVectorImpl<SDValue> &OutVals,
1870                                SDLoc dl, SelectionDAG &DAG) const {
1871   MachineFunction &MF = DAG.getMachineFunction();
1872   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1873
1874   SmallVector<CCValAssign, 16> RVLocs;
1875   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1876   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1877
1878   SDValue Flag;
1879   SmallVector<SDValue, 6> RetOps;
1880   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1881   // Operand #1 = Bytes To Pop
1882   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1883                    MVT::i16));
1884
1885   // Copy the result values into the output registers.
1886   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1887     CCValAssign &VA = RVLocs[i];
1888     assert(VA.isRegLoc() && "Can only return in registers!");
1889     SDValue ValToCopy = OutVals[i];
1890     EVT ValVT = ValToCopy.getValueType();
1891
1892     // Promote values to the appropriate types.
1893     if (VA.getLocInfo() == CCValAssign::SExt)
1894       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1895     else if (VA.getLocInfo() == CCValAssign::ZExt)
1896       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1897     else if (VA.getLocInfo() == CCValAssign::AExt)
1898       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1899     else if (VA.getLocInfo() == CCValAssign::BCvt)
1900       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1901
1902     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1903            "Unexpected FP-extend for return value.");
1904
1905     // If this is x86-64, and we disabled SSE, we can't return FP values,
1906     // or SSE or MMX vectors.
1907     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1908          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1909           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1910       report_fatal_error("SSE register return with SSE disabled");
1911     }
1912     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1913     // llvm-gcc has never done it right and no one has noticed, so this
1914     // should be OK for now.
1915     if (ValVT == MVT::f64 &&
1916         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1917       report_fatal_error("SSE2 register return with SSE2 disabled");
1918
1919     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1920     // the RET instruction and handled by the FP Stackifier.
1921     if (VA.getLocReg() == X86::FP0 ||
1922         VA.getLocReg() == X86::FP1) {
1923       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1924       // change the value to the FP stack register class.
1925       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1926         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1927       RetOps.push_back(ValToCopy);
1928       // Don't emit a copytoreg.
1929       continue;
1930     }
1931
1932     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1933     // which is returned in RAX / RDX.
1934     if (Subtarget->is64Bit()) {
1935       if (ValVT == MVT::x86mmx) {
1936         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1937           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1938           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1939                                   ValToCopy);
1940           // If we don't have SSE2 available, convert to v4f32 so the generated
1941           // register is legal.
1942           if (!Subtarget->hasSSE2())
1943             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1944         }
1945       }
1946     }
1947
1948     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1949     Flag = Chain.getValue(1);
1950     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1951   }
1952
1953   // The x86-64 ABIs require that for returning structs by value we copy
1954   // the sret argument into %rax/%eax (depending on ABI) for the return.
1955   // Win32 requires us to put the sret argument to %eax as well.
1956   // We saved the argument into a virtual register in the entry block,
1957   // so now we copy the value out and into %rax/%eax.
1958   //
1959   // Checking Function.hasStructRetAttr() here is insufficient because the IR
1960   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
1961   // false, then an sret argument may be implicitly inserted in the SelDAG. In
1962   // either case FuncInfo->setSRetReturnReg() will have been called.
1963   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
1964     assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
1965            "No need for an sret register");
1966     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
1967
1968     unsigned RetValReg
1969         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1970           X86::RAX : X86::EAX;
1971     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1972     Flag = Chain.getValue(1);
1973
1974     // RAX/EAX now acts like a return value.
1975     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1976   }
1977
1978   RetOps[0] = Chain;  // Update chain.
1979
1980   // Add the flag if we have it.
1981   if (Flag.getNode())
1982     RetOps.push_back(Flag);
1983
1984   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1985 }
1986
1987 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1988   if (N->getNumValues() != 1)
1989     return false;
1990   if (!N->hasNUsesOfValue(1, 0))
1991     return false;
1992
1993   SDValue TCChain = Chain;
1994   SDNode *Copy = *N->use_begin();
1995   if (Copy->getOpcode() == ISD::CopyToReg) {
1996     // If the copy has a glue operand, we conservatively assume it isn't safe to
1997     // perform a tail call.
1998     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1999       return false;
2000     TCChain = Copy->getOperand(0);
2001   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2002     return false;
2003
2004   bool HasRet = false;
2005   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2006        UI != UE; ++UI) {
2007     if (UI->getOpcode() != X86ISD::RET_FLAG)
2008       return false;
2009     // If we are returning more than one value, we can definitely
2010     // not make a tail call see PR19530
2011     if (UI->getNumOperands() > 4)
2012       return false;
2013     if (UI->getNumOperands() == 4 &&
2014         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2015       return false;
2016     HasRet = true;
2017   }
2018
2019   if (!HasRet)
2020     return false;
2021
2022   Chain = TCChain;
2023   return true;
2024 }
2025
2026 EVT
2027 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2028                                             ISD::NodeType ExtendKind) const {
2029   MVT ReturnMVT;
2030   // TODO: Is this also valid on 32-bit?
2031   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2032     ReturnMVT = MVT::i8;
2033   else
2034     ReturnMVT = MVT::i32;
2035
2036   EVT MinVT = getRegisterType(Context, ReturnMVT);
2037   return VT.bitsLT(MinVT) ? MinVT : VT;
2038 }
2039
2040 /// Lower the result values of a call into the
2041 /// appropriate copies out of appropriate physical registers.
2042 ///
2043 SDValue
2044 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2045                                    CallingConv::ID CallConv, bool isVarArg,
2046                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2047                                    SDLoc dl, SelectionDAG &DAG,
2048                                    SmallVectorImpl<SDValue> &InVals) const {
2049
2050   // Assign locations to each value returned by this call.
2051   SmallVector<CCValAssign, 16> RVLocs;
2052   bool Is64Bit = Subtarget->is64Bit();
2053   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2054                  *DAG.getContext());
2055   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2056
2057   // Copy all of the result registers out of their specified physreg.
2058   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2059     CCValAssign &VA = RVLocs[i];
2060     EVT CopyVT = VA.getValVT();
2061
2062     // If this is x86-64, and we disabled SSE, we can't return FP values
2063     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2064         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2065       report_fatal_error("SSE register return with SSE disabled");
2066     }
2067
2068     // If we prefer to use the value in xmm registers, copy it out as f80 and
2069     // use a truncate to move it from fp stack reg to xmm reg.
2070     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2071         isScalarFPTypeInSSEReg(VA.getValVT()))
2072       CopyVT = MVT::f80;
2073
2074     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2075                                CopyVT, InFlag).getValue(1);
2076     SDValue Val = Chain.getValue(0);
2077
2078     if (CopyVT != VA.getValVT())
2079       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2080                         // This truncation won't change the value.
2081                         DAG.getIntPtrConstant(1));
2082
2083     InFlag = Chain.getValue(2);
2084     InVals.push_back(Val);
2085   }
2086
2087   return Chain;
2088 }
2089
2090 //===----------------------------------------------------------------------===//
2091 //                C & StdCall & Fast Calling Convention implementation
2092 //===----------------------------------------------------------------------===//
2093 //  StdCall calling convention seems to be standard for many Windows' API
2094 //  routines and around. It differs from C calling convention just a little:
2095 //  callee should clean up the stack, not caller. Symbols should be also
2096 //  decorated in some fancy way :) It doesn't support any vector arguments.
2097 //  For info on fast calling convention see Fast Calling Convention (tail call)
2098 //  implementation LowerX86_32FastCCCallTo.
2099
2100 /// CallIsStructReturn - Determines whether a call uses struct return
2101 /// semantics.
2102 enum StructReturnType {
2103   NotStructReturn,
2104   RegStructReturn,
2105   StackStructReturn
2106 };
2107 static StructReturnType
2108 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2109   if (Outs.empty())
2110     return NotStructReturn;
2111
2112   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2113   if (!Flags.isSRet())
2114     return NotStructReturn;
2115   if (Flags.isInReg())
2116     return RegStructReturn;
2117   return StackStructReturn;
2118 }
2119
2120 /// Determines whether a function uses struct return semantics.
2121 static StructReturnType
2122 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2123   if (Ins.empty())
2124     return NotStructReturn;
2125
2126   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2127   if (!Flags.isSRet())
2128     return NotStructReturn;
2129   if (Flags.isInReg())
2130     return RegStructReturn;
2131   return StackStructReturn;
2132 }
2133
2134 /// Make a copy of an aggregate at address specified by "Src" to address
2135 /// "Dst" with size and alignment information specified by the specific
2136 /// parameter attribute. The copy will be passed as a byval function parameter.
2137 static SDValue
2138 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2139                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2140                           SDLoc dl) {
2141   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2142
2143   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2144                        /*isVolatile*/false, /*AlwaysInline=*/true,
2145                        MachinePointerInfo(), MachinePointerInfo());
2146 }
2147
2148 /// Return true if the calling convention is one that
2149 /// supports tail call optimization.
2150 static bool IsTailCallConvention(CallingConv::ID CC) {
2151   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2152           CC == CallingConv::HiPE);
2153 }
2154
2155 /// \brief Return true if the calling convention is a C calling convention.
2156 static bool IsCCallConvention(CallingConv::ID CC) {
2157   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2158           CC == CallingConv::X86_64_SysV);
2159 }
2160
2161 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2162   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2163     return false;
2164
2165   CallSite CS(CI);
2166   CallingConv::ID CalleeCC = CS.getCallingConv();
2167   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2168     return false;
2169
2170   return true;
2171 }
2172
2173 /// Return true if the function is being made into
2174 /// a tailcall target by changing its ABI.
2175 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2176                                    bool GuaranteedTailCallOpt) {
2177   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2178 }
2179
2180 SDValue
2181 X86TargetLowering::LowerMemArgument(SDValue Chain,
2182                                     CallingConv::ID CallConv,
2183                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2184                                     SDLoc dl, SelectionDAG &DAG,
2185                                     const CCValAssign &VA,
2186                                     MachineFrameInfo *MFI,
2187                                     unsigned i) const {
2188   // Create the nodes corresponding to a load from this parameter slot.
2189   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2190   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2191       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2192   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2193   EVT ValVT;
2194
2195   // If value is passed by pointer we have address passed instead of the value
2196   // itself.
2197   if (VA.getLocInfo() == CCValAssign::Indirect)
2198     ValVT = VA.getLocVT();
2199   else
2200     ValVT = VA.getValVT();
2201
2202   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2203   // changed with more analysis.
2204   // In case of tail call optimization mark all arguments mutable. Since they
2205   // could be overwritten by lowering of arguments in case of a tail call.
2206   if (Flags.isByVal()) {
2207     unsigned Bytes = Flags.getByValSize();
2208     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2209     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2210     return DAG.getFrameIndex(FI, getPointerTy());
2211   } else {
2212     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2213                                     VA.getLocMemOffset(), isImmutable);
2214     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2215     return DAG.getLoad(ValVT, dl, Chain, FIN,
2216                        MachinePointerInfo::getFixedStack(FI),
2217                        false, false, false, 0);
2218   }
2219 }
2220
2221 // FIXME: Get this from tablegen.
2222 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2223                                                 const X86Subtarget *Subtarget) {
2224   assert(Subtarget->is64Bit());
2225
2226   if (Subtarget->isCallingConvWin64(CallConv)) {
2227     static const MCPhysReg GPR64ArgRegsWin64[] = {
2228       X86::RCX, X86::RDX, X86::R8,  X86::R9
2229     };
2230     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2231   }
2232
2233   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2234     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2235   };
2236   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2237 }
2238
2239 // FIXME: Get this from tablegen.
2240 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2241                                                 CallingConv::ID CallConv,
2242                                                 const X86Subtarget *Subtarget) {
2243   assert(Subtarget->is64Bit());
2244   if (Subtarget->isCallingConvWin64(CallConv)) {
2245     // The XMM registers which might contain var arg parameters are shadowed
2246     // in their paired GPR.  So we only need to save the GPR to their home
2247     // slots.
2248     // TODO: __vectorcall will change this.
2249     return None;
2250   }
2251
2252   const Function *Fn = MF.getFunction();
2253   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2254   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2255          "SSE register cannot be used when SSE is disabled!");
2256   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2257       !Subtarget->hasSSE1())
2258     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2259     // registers.
2260     return None;
2261
2262   static const MCPhysReg XMMArgRegs64Bit[] = {
2263     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2264     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2265   };
2266   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2267 }
2268
2269 SDValue
2270 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2271                                         CallingConv::ID CallConv,
2272                                         bool isVarArg,
2273                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2274                                         SDLoc dl,
2275                                         SelectionDAG &DAG,
2276                                         SmallVectorImpl<SDValue> &InVals)
2277                                           const {
2278   MachineFunction &MF = DAG.getMachineFunction();
2279   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2280
2281   const Function* Fn = MF.getFunction();
2282   if (Fn->hasExternalLinkage() &&
2283       Subtarget->isTargetCygMing() &&
2284       Fn->getName() == "main")
2285     FuncInfo->setForceFramePointer(true);
2286
2287   MachineFrameInfo *MFI = MF.getFrameInfo();
2288   bool Is64Bit = Subtarget->is64Bit();
2289   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2290
2291   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2292          "Var args not supported with calling convention fastcc, ghc or hipe");
2293
2294   // Assign locations to all of the incoming arguments.
2295   SmallVector<CCValAssign, 16> ArgLocs;
2296   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2297
2298   // Allocate shadow area for Win64
2299   if (IsWin64)
2300     CCInfo.AllocateStack(32, 8);
2301
2302   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2303
2304   unsigned LastVal = ~0U;
2305   SDValue ArgValue;
2306   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2307     CCValAssign &VA = ArgLocs[i];
2308     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2309     // places.
2310     assert(VA.getValNo() != LastVal &&
2311            "Don't support value assigned to multiple locs yet");
2312     (void)LastVal;
2313     LastVal = VA.getValNo();
2314
2315     if (VA.isRegLoc()) {
2316       EVT RegVT = VA.getLocVT();
2317       const TargetRegisterClass *RC;
2318       if (RegVT == MVT::i32)
2319         RC = &X86::GR32RegClass;
2320       else if (Is64Bit && RegVT == MVT::i64)
2321         RC = &X86::GR64RegClass;
2322       else if (RegVT == MVT::f32)
2323         RC = &X86::FR32RegClass;
2324       else if (RegVT == MVT::f64)
2325         RC = &X86::FR64RegClass;
2326       else if (RegVT.is512BitVector())
2327         RC = &X86::VR512RegClass;
2328       else if (RegVT.is256BitVector())
2329         RC = &X86::VR256RegClass;
2330       else if (RegVT.is128BitVector())
2331         RC = &X86::VR128RegClass;
2332       else if (RegVT == MVT::x86mmx)
2333         RC = &X86::VR64RegClass;
2334       else if (RegVT == MVT::i1)
2335         RC = &X86::VK1RegClass;
2336       else if (RegVT == MVT::v8i1)
2337         RC = &X86::VK8RegClass;
2338       else if (RegVT == MVT::v16i1)
2339         RC = &X86::VK16RegClass;
2340       else if (RegVT == MVT::v32i1)
2341         RC = &X86::VK32RegClass;
2342       else if (RegVT == MVT::v64i1)
2343         RC = &X86::VK64RegClass;
2344       else
2345         llvm_unreachable("Unknown argument type!");
2346
2347       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2348       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2349
2350       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2351       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2352       // right size.
2353       if (VA.getLocInfo() == CCValAssign::SExt)
2354         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2355                                DAG.getValueType(VA.getValVT()));
2356       else if (VA.getLocInfo() == CCValAssign::ZExt)
2357         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2358                                DAG.getValueType(VA.getValVT()));
2359       else if (VA.getLocInfo() == CCValAssign::BCvt)
2360         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2361
2362       if (VA.isExtInLoc()) {
2363         // Handle MMX values passed in XMM regs.
2364         if (RegVT.isVector())
2365           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2366         else
2367           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2368       }
2369     } else {
2370       assert(VA.isMemLoc());
2371       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2372     }
2373
2374     // If value is passed via pointer - do a load.
2375     if (VA.getLocInfo() == CCValAssign::Indirect)
2376       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2377                              MachinePointerInfo(), false, false, false, 0);
2378
2379     InVals.push_back(ArgValue);
2380   }
2381
2382   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2383     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2384       // The x86-64 ABIs require that for returning structs by value we copy
2385       // the sret argument into %rax/%eax (depending on ABI) for the return.
2386       // Win32 requires us to put the sret argument to %eax as well.
2387       // Save the argument into a virtual register so that we can access it
2388       // from the return points.
2389       if (Ins[i].Flags.isSRet()) {
2390         unsigned Reg = FuncInfo->getSRetReturnReg();
2391         if (!Reg) {
2392           MVT PtrTy = getPointerTy();
2393           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2394           FuncInfo->setSRetReturnReg(Reg);
2395         }
2396         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2397         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2398         break;
2399       }
2400     }
2401   }
2402
2403   unsigned StackSize = CCInfo.getNextStackOffset();
2404   // Align stack specially for tail calls.
2405   if (FuncIsMadeTailCallSafe(CallConv,
2406                              MF.getTarget().Options.GuaranteedTailCallOpt))
2407     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2408
2409   // If the function takes variable number of arguments, make a frame index for
2410   // the start of the first vararg value... for expansion of llvm.va_start. We
2411   // can skip this if there are no va_start calls.
2412   if (MFI->hasVAStart() &&
2413       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2414                    CallConv != CallingConv::X86_ThisCall))) {
2415     FuncInfo->setVarArgsFrameIndex(
2416         MFI->CreateFixedObject(1, StackSize, true));
2417   }
2418
2419   // Figure out if XMM registers are in use.
2420   assert(!(MF.getTarget().Options.UseSoftFloat &&
2421            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2422          "SSE register cannot be used when SSE is disabled!");
2423
2424   // 64-bit calling conventions support varargs and register parameters, so we
2425   // have to do extra work to spill them in the prologue.
2426   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2427     // Find the first unallocated argument registers.
2428     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2429     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2430     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2431     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2432     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2433            "SSE register cannot be used when SSE is disabled!");
2434
2435     // Gather all the live in physical registers.
2436     SmallVector<SDValue, 6> LiveGPRs;
2437     SmallVector<SDValue, 8> LiveXMMRegs;
2438     SDValue ALVal;
2439     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2440       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2441       LiveGPRs.push_back(
2442           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2443     }
2444     if (!ArgXMMs.empty()) {
2445       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2446       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2447       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2448         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2449         LiveXMMRegs.push_back(
2450             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2451       }
2452     }
2453
2454     if (IsWin64) {
2455       const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2456       // Get to the caller-allocated home save location.  Add 8 to account
2457       // for the return address.
2458       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2459       FuncInfo->setRegSaveFrameIndex(
2460           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2461       // Fixup to set vararg frame on shadow area (4 x i64).
2462       if (NumIntRegs < 4)
2463         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2464     } else {
2465       // For X86-64, if there are vararg parameters that are passed via
2466       // registers, then we must store them to their spots on the stack so
2467       // they may be loaded by deferencing the result of va_next.
2468       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2469       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2470       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2471           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2472     }
2473
2474     // Store the integer parameter registers.
2475     SmallVector<SDValue, 8> MemOps;
2476     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2477                                       getPointerTy());
2478     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2479     for (SDValue Val : LiveGPRs) {
2480       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2481                                 DAG.getIntPtrConstant(Offset));
2482       SDValue Store =
2483         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2484                      MachinePointerInfo::getFixedStack(
2485                        FuncInfo->getRegSaveFrameIndex(), Offset),
2486                      false, false, 0);
2487       MemOps.push_back(Store);
2488       Offset += 8;
2489     }
2490
2491     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2492       // Now store the XMM (fp + vector) parameter registers.
2493       SmallVector<SDValue, 12> SaveXMMOps;
2494       SaveXMMOps.push_back(Chain);
2495       SaveXMMOps.push_back(ALVal);
2496       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2497                              FuncInfo->getRegSaveFrameIndex()));
2498       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2499                              FuncInfo->getVarArgsFPOffset()));
2500       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2501                         LiveXMMRegs.end());
2502       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2503                                    MVT::Other, SaveXMMOps));
2504     }
2505
2506     if (!MemOps.empty())
2507       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2508   }
2509
2510   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2511     // Find the largest legal vector type.
2512     MVT VecVT = MVT::Other;
2513     // FIXME: Only some x86_32 calling conventions support AVX512.
2514     if (Subtarget->hasAVX512() &&
2515         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2516                      CallConv == CallingConv::Intel_OCL_BI)))
2517       VecVT = MVT::v16f32;
2518     else if (Subtarget->hasAVX())
2519       VecVT = MVT::v8f32;
2520     else if (Subtarget->hasSSE2())
2521       VecVT = MVT::v4f32;
2522
2523     // We forward some GPRs and some vector types.
2524     SmallVector<MVT, 2> RegParmTypes;
2525     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2526     RegParmTypes.push_back(IntVT);
2527     if (VecVT != MVT::Other)
2528       RegParmTypes.push_back(VecVT);
2529
2530     // Compute the set of forwarded registers. The rest are scratch.
2531     SmallVectorImpl<ForwardedRegister> &Forwards =
2532         FuncInfo->getForwardedMustTailRegParms();
2533     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2534
2535     // Conservatively forward AL on x86_64, since it might be used for varargs.
2536     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2537       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2538       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2539     }
2540
2541     // Copy all forwards from physical to virtual registers.
2542     for (ForwardedRegister &F : Forwards) {
2543       // FIXME: Can we use a less constrained schedule?
2544       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2545       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2546       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2547     }
2548   }
2549
2550   // Some CCs need callee pop.
2551   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2552                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2553     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2554   } else {
2555     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2556     // If this is an sret function, the return should pop the hidden pointer.
2557     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2558         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2559         argsAreStructReturn(Ins) == StackStructReturn)
2560       FuncInfo->setBytesToPopOnReturn(4);
2561   }
2562
2563   if (!Is64Bit) {
2564     // RegSaveFrameIndex is X86-64 only.
2565     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2566     if (CallConv == CallingConv::X86_FastCall ||
2567         CallConv == CallingConv::X86_ThisCall)
2568       // fastcc functions can't have varargs.
2569       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2570   }
2571
2572   FuncInfo->setArgumentStackSize(StackSize);
2573
2574   return Chain;
2575 }
2576
2577 SDValue
2578 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2579                                     SDValue StackPtr, SDValue Arg,
2580                                     SDLoc dl, SelectionDAG &DAG,
2581                                     const CCValAssign &VA,
2582                                     ISD::ArgFlagsTy Flags) const {
2583   unsigned LocMemOffset = VA.getLocMemOffset();
2584   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2585   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2586   if (Flags.isByVal())
2587     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2588
2589   return DAG.getStore(Chain, dl, Arg, PtrOff,
2590                       MachinePointerInfo::getStack(LocMemOffset),
2591                       false, false, 0);
2592 }
2593
2594 /// Emit a load of return address if tail call
2595 /// optimization is performed and it is required.
2596 SDValue
2597 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2598                                            SDValue &OutRetAddr, SDValue Chain,
2599                                            bool IsTailCall, bool Is64Bit,
2600                                            int FPDiff, SDLoc dl) const {
2601   // Adjust the Return address stack slot.
2602   EVT VT = getPointerTy();
2603   OutRetAddr = getReturnAddressFrameIndex(DAG);
2604
2605   // Load the "old" Return address.
2606   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2607                            false, false, false, 0);
2608   return SDValue(OutRetAddr.getNode(), 1);
2609 }
2610
2611 /// Emit a store of the return address if tail call
2612 /// optimization is performed and it is required (FPDiff!=0).
2613 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2614                                         SDValue Chain, SDValue RetAddrFrIdx,
2615                                         EVT PtrVT, unsigned SlotSize,
2616                                         int FPDiff, SDLoc dl) {
2617   // Store the return address to the appropriate stack slot.
2618   if (!FPDiff) return Chain;
2619   // Calculate the new stack slot for the return address.
2620   int NewReturnAddrFI =
2621     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2622                                          false);
2623   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2624   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2625                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2626                        false, false, 0);
2627   return Chain;
2628 }
2629
2630 SDValue
2631 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2632                              SmallVectorImpl<SDValue> &InVals) const {
2633   SelectionDAG &DAG                     = CLI.DAG;
2634   SDLoc &dl                             = CLI.DL;
2635   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2636   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2637   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2638   SDValue Chain                         = CLI.Chain;
2639   SDValue Callee                        = CLI.Callee;
2640   CallingConv::ID CallConv              = CLI.CallConv;
2641   bool &isTailCall                      = CLI.IsTailCall;
2642   bool isVarArg                         = CLI.IsVarArg;
2643
2644   MachineFunction &MF = DAG.getMachineFunction();
2645   bool Is64Bit        = Subtarget->is64Bit();
2646   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2647   StructReturnType SR = callIsStructReturn(Outs);
2648   bool IsSibcall      = false;
2649   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2650
2651   if (MF.getTarget().Options.DisableTailCalls)
2652     isTailCall = false;
2653
2654   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2655   if (IsMustTail) {
2656     // Force this to be a tail call.  The verifier rules are enough to ensure
2657     // that we can lower this successfully without moving the return address
2658     // around.
2659     isTailCall = true;
2660   } else if (isTailCall) {
2661     // Check if it's really possible to do a tail call.
2662     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2663                     isVarArg, SR != NotStructReturn,
2664                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2665                     Outs, OutVals, Ins, DAG);
2666
2667     // Sibcalls are automatically detected tailcalls which do not require
2668     // ABI changes.
2669     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2670       IsSibcall = true;
2671
2672     if (isTailCall)
2673       ++NumTailCalls;
2674   }
2675
2676   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2677          "Var args not supported with calling convention fastcc, ghc or hipe");
2678
2679   // Analyze operands of the call, assigning locations to each operand.
2680   SmallVector<CCValAssign, 16> ArgLocs;
2681   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2682
2683   // Allocate shadow area for Win64
2684   if (IsWin64)
2685     CCInfo.AllocateStack(32, 8);
2686
2687   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2688
2689   // Get a count of how many bytes are to be pushed on the stack.
2690   unsigned NumBytes = CCInfo.getNextStackOffset();
2691   if (IsSibcall)
2692     // This is a sibcall. The memory operands are available in caller's
2693     // own caller's stack.
2694     NumBytes = 0;
2695   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2696            IsTailCallConvention(CallConv))
2697     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2698
2699   int FPDiff = 0;
2700   if (isTailCall && !IsSibcall && !IsMustTail) {
2701     // Lower arguments at fp - stackoffset + fpdiff.
2702     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2703
2704     FPDiff = NumBytesCallerPushed - NumBytes;
2705
2706     // Set the delta of movement of the returnaddr stackslot.
2707     // But only set if delta is greater than previous delta.
2708     if (FPDiff < X86Info->getTCReturnAddrDelta())
2709       X86Info->setTCReturnAddrDelta(FPDiff);
2710   }
2711
2712   unsigned NumBytesToPush = NumBytes;
2713   unsigned NumBytesToPop = NumBytes;
2714
2715   // If we have an inalloca argument, all stack space has already been allocated
2716   // for us and be right at the top of the stack.  We don't support multiple
2717   // arguments passed in memory when using inalloca.
2718   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2719     NumBytesToPush = 0;
2720     if (!ArgLocs.back().isMemLoc())
2721       report_fatal_error("cannot use inalloca attribute on a register "
2722                          "parameter");
2723     if (ArgLocs.back().getLocMemOffset() != 0)
2724       report_fatal_error("any parameter with the inalloca attribute must be "
2725                          "the only memory argument");
2726   }
2727
2728   if (!IsSibcall)
2729     Chain = DAG.getCALLSEQ_START(
2730         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2731
2732   SDValue RetAddrFrIdx;
2733   // Load return address for tail calls.
2734   if (isTailCall && FPDiff)
2735     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2736                                     Is64Bit, FPDiff, dl);
2737
2738   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2739   SmallVector<SDValue, 8> MemOpChains;
2740   SDValue StackPtr;
2741
2742   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2743   // of tail call optimization arguments are handle later.
2744   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2745   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2746     // Skip inalloca arguments, they have already been written.
2747     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2748     if (Flags.isInAlloca())
2749       continue;
2750
2751     CCValAssign &VA = ArgLocs[i];
2752     EVT RegVT = VA.getLocVT();
2753     SDValue Arg = OutVals[i];
2754     bool isByVal = Flags.isByVal();
2755
2756     // Promote the value if needed.
2757     switch (VA.getLocInfo()) {
2758     default: llvm_unreachable("Unknown loc info!");
2759     case CCValAssign::Full: break;
2760     case CCValAssign::SExt:
2761       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2762       break;
2763     case CCValAssign::ZExt:
2764       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2765       break;
2766     case CCValAssign::AExt:
2767       if (RegVT.is128BitVector()) {
2768         // Special case: passing MMX values in XMM registers.
2769         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2770         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2771         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2772       } else
2773         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2774       break;
2775     case CCValAssign::BCvt:
2776       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2777       break;
2778     case CCValAssign::Indirect: {
2779       // Store the argument.
2780       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2781       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2782       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2783                            MachinePointerInfo::getFixedStack(FI),
2784                            false, false, 0);
2785       Arg = SpillSlot;
2786       break;
2787     }
2788     }
2789
2790     if (VA.isRegLoc()) {
2791       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2792       if (isVarArg && IsWin64) {
2793         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2794         // shadow reg if callee is a varargs function.
2795         unsigned ShadowReg = 0;
2796         switch (VA.getLocReg()) {
2797         case X86::XMM0: ShadowReg = X86::RCX; break;
2798         case X86::XMM1: ShadowReg = X86::RDX; break;
2799         case X86::XMM2: ShadowReg = X86::R8; break;
2800         case X86::XMM3: ShadowReg = X86::R9; break;
2801         }
2802         if (ShadowReg)
2803           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2804       }
2805     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2806       assert(VA.isMemLoc());
2807       if (!StackPtr.getNode())
2808         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2809                                       getPointerTy());
2810       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2811                                              dl, DAG, VA, Flags));
2812     }
2813   }
2814
2815   if (!MemOpChains.empty())
2816     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2817
2818   if (Subtarget->isPICStyleGOT()) {
2819     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2820     // GOT pointer.
2821     if (!isTailCall) {
2822       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2823                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2824     } else {
2825       // If we are tail calling and generating PIC/GOT style code load the
2826       // address of the callee into ECX. The value in ecx is used as target of
2827       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2828       // for tail calls on PIC/GOT architectures. Normally we would just put the
2829       // address of GOT into ebx and then call target@PLT. But for tail calls
2830       // ebx would be restored (since ebx is callee saved) before jumping to the
2831       // target@PLT.
2832
2833       // Note: The actual moving to ECX is done further down.
2834       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2835       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2836           !G->getGlobal()->hasProtectedVisibility())
2837         Callee = LowerGlobalAddress(Callee, DAG);
2838       else if (isa<ExternalSymbolSDNode>(Callee))
2839         Callee = LowerExternalSymbol(Callee, DAG);
2840     }
2841   }
2842
2843   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2844     // From AMD64 ABI document:
2845     // For calls that may call functions that use varargs or stdargs
2846     // (prototype-less calls or calls to functions containing ellipsis (...) in
2847     // the declaration) %al is used as hidden argument to specify the number
2848     // of SSE registers used. The contents of %al do not need to match exactly
2849     // the number of registers, but must be an ubound on the number of SSE
2850     // registers used and is in the range 0 - 8 inclusive.
2851
2852     // Count the number of XMM registers allocated.
2853     static const MCPhysReg XMMArgRegs[] = {
2854       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2855       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2856     };
2857     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2858     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2859            && "SSE registers cannot be used when SSE is disabled");
2860
2861     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2862                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2863   }
2864
2865   if (isVarArg && IsMustTail) {
2866     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2867     for (const auto &F : Forwards) {
2868       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2869       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2870     }
2871   }
2872
2873   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2874   // don't need this because the eligibility check rejects calls that require
2875   // shuffling arguments passed in memory.
2876   if (!IsSibcall && isTailCall) {
2877     // Force all the incoming stack arguments to be loaded from the stack
2878     // before any new outgoing arguments are stored to the stack, because the
2879     // outgoing stack slots may alias the incoming argument stack slots, and
2880     // the alias isn't otherwise explicit. This is slightly more conservative
2881     // than necessary, because it means that each store effectively depends
2882     // on every argument instead of just those arguments it would clobber.
2883     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2884
2885     SmallVector<SDValue, 8> MemOpChains2;
2886     SDValue FIN;
2887     int FI = 0;
2888     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2889       CCValAssign &VA = ArgLocs[i];
2890       if (VA.isRegLoc())
2891         continue;
2892       assert(VA.isMemLoc());
2893       SDValue Arg = OutVals[i];
2894       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2895       // Skip inalloca arguments.  They don't require any work.
2896       if (Flags.isInAlloca())
2897         continue;
2898       // Create frame index.
2899       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2900       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2901       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2902       FIN = DAG.getFrameIndex(FI, getPointerTy());
2903
2904       if (Flags.isByVal()) {
2905         // Copy relative to framepointer.
2906         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2907         if (!StackPtr.getNode())
2908           StackPtr = DAG.getCopyFromReg(Chain, dl,
2909                                         RegInfo->getStackRegister(),
2910                                         getPointerTy());
2911         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2912
2913         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2914                                                          ArgChain,
2915                                                          Flags, DAG, dl));
2916       } else {
2917         // Store relative to framepointer.
2918         MemOpChains2.push_back(
2919           DAG.getStore(ArgChain, dl, Arg, FIN,
2920                        MachinePointerInfo::getFixedStack(FI),
2921                        false, false, 0));
2922       }
2923     }
2924
2925     if (!MemOpChains2.empty())
2926       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2927
2928     // Store the return address to the appropriate stack slot.
2929     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2930                                      getPointerTy(), RegInfo->getSlotSize(),
2931                                      FPDiff, dl);
2932   }
2933
2934   // Build a sequence of copy-to-reg nodes chained together with token chain
2935   // and flag operands which copy the outgoing args into registers.
2936   SDValue InFlag;
2937   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2938     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2939                              RegsToPass[i].second, InFlag);
2940     InFlag = Chain.getValue(1);
2941   }
2942
2943   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2944     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2945     // In the 64-bit large code model, we have to make all calls
2946     // through a register, since the call instruction's 32-bit
2947     // pc-relative offset may not be large enough to hold the whole
2948     // address.
2949   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
2950     // If the callee is a GlobalAddress node (quite common, every direct call
2951     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2952     // it.
2953     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
2954
2955     // We should use extra load for direct calls to dllimported functions in
2956     // non-JIT mode.
2957     const GlobalValue *GV = G->getGlobal();
2958     if (!GV->hasDLLImportStorageClass()) {
2959       unsigned char OpFlags = 0;
2960       bool ExtraLoad = false;
2961       unsigned WrapperKind = ISD::DELETED_NODE;
2962
2963       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2964       // external symbols most go through the PLT in PIC mode.  If the symbol
2965       // has hidden or protected visibility, or if it is static or local, then
2966       // we don't need to use the PLT - we can directly call it.
2967       if (Subtarget->isTargetELF() &&
2968           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2969           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2970         OpFlags = X86II::MO_PLT;
2971       } else if (Subtarget->isPICStyleStubAny() &&
2972                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2973                  (!Subtarget->getTargetTriple().isMacOSX() ||
2974                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2975         // PC-relative references to external symbols should go through $stub,
2976         // unless we're building with the leopard linker or later, which
2977         // automatically synthesizes these stubs.
2978         OpFlags = X86II::MO_DARWIN_STUB;
2979       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
2980                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
2981         // If the function is marked as non-lazy, generate an indirect call
2982         // which loads from the GOT directly. This avoids runtime overhead
2983         // at the cost of eager binding (and one extra byte of encoding).
2984         OpFlags = X86II::MO_GOTPCREL;
2985         WrapperKind = X86ISD::WrapperRIP;
2986         ExtraLoad = true;
2987       }
2988
2989       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2990                                           G->getOffset(), OpFlags);
2991
2992       // Add a wrapper if needed.
2993       if (WrapperKind != ISD::DELETED_NODE)
2994         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2995       // Add extra indirection if needed.
2996       if (ExtraLoad)
2997         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2998                              MachinePointerInfo::getGOT(),
2999                              false, false, false, 0);
3000     }
3001   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3002     unsigned char OpFlags = 0;
3003
3004     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3005     // external symbols should go through the PLT.
3006     if (Subtarget->isTargetELF() &&
3007         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3008       OpFlags = X86II::MO_PLT;
3009     } else if (Subtarget->isPICStyleStubAny() &&
3010                (!Subtarget->getTargetTriple().isMacOSX() ||
3011                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3012       // PC-relative references to external symbols should go through $stub,
3013       // unless we're building with the leopard linker or later, which
3014       // automatically synthesizes these stubs.
3015       OpFlags = X86II::MO_DARWIN_STUB;
3016     }
3017
3018     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3019                                          OpFlags);
3020   } else if (Subtarget->isTarget64BitILP32() &&
3021              Callee->getValueType(0) == MVT::i32) {
3022     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3023     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3024   }
3025
3026   // Returns a chain & a flag for retval copy to use.
3027   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3028   SmallVector<SDValue, 8> Ops;
3029
3030   if (!IsSibcall && isTailCall) {
3031     Chain = DAG.getCALLSEQ_END(Chain,
3032                                DAG.getIntPtrConstant(NumBytesToPop, true),
3033                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3034     InFlag = Chain.getValue(1);
3035   }
3036
3037   Ops.push_back(Chain);
3038   Ops.push_back(Callee);
3039
3040   if (isTailCall)
3041     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3042
3043   // Add argument registers to the end of the list so that they are known live
3044   // into the call.
3045   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3046     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3047                                   RegsToPass[i].second.getValueType()));
3048
3049   // Add a register mask operand representing the call-preserved registers.
3050   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3051   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3052   assert(Mask && "Missing call preserved mask for calling convention");
3053   Ops.push_back(DAG.getRegisterMask(Mask));
3054
3055   if (InFlag.getNode())
3056     Ops.push_back(InFlag);
3057
3058   if (isTailCall) {
3059     // We used to do:
3060     //// If this is the first return lowered for this function, add the regs
3061     //// to the liveout set for the function.
3062     // This isn't right, although it's probably harmless on x86; liveouts
3063     // should be computed from returns not tail calls.  Consider a void
3064     // function making a tail call to a function returning int.
3065     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3066   }
3067
3068   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3069   InFlag = Chain.getValue(1);
3070
3071   // Create the CALLSEQ_END node.
3072   unsigned NumBytesForCalleeToPop;
3073   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3074                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3075     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3076   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3077            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3078            SR == StackStructReturn)
3079     // If this is a call to a struct-return function, the callee
3080     // pops the hidden struct pointer, so we have to push it back.
3081     // This is common for Darwin/X86, Linux & Mingw32 targets.
3082     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3083     NumBytesForCalleeToPop = 4;
3084   else
3085     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3086
3087   // Returns a flag for retval copy to use.
3088   if (!IsSibcall) {
3089     Chain = DAG.getCALLSEQ_END(Chain,
3090                                DAG.getIntPtrConstant(NumBytesToPop, true),
3091                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3092                                                      true),
3093                                InFlag, dl);
3094     InFlag = Chain.getValue(1);
3095   }
3096
3097   // Handle result values, copying them out of physregs into vregs that we
3098   // return.
3099   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3100                          Ins, dl, DAG, InVals);
3101 }
3102
3103 //===----------------------------------------------------------------------===//
3104 //                Fast Calling Convention (tail call) implementation
3105 //===----------------------------------------------------------------------===//
3106
3107 //  Like std call, callee cleans arguments, convention except that ECX is
3108 //  reserved for storing the tail called function address. Only 2 registers are
3109 //  free for argument passing (inreg). Tail call optimization is performed
3110 //  provided:
3111 //                * tailcallopt is enabled
3112 //                * caller/callee are fastcc
3113 //  On X86_64 architecture with GOT-style position independent code only local
3114 //  (within module) calls are supported at the moment.
3115 //  To keep the stack aligned according to platform abi the function
3116 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3117 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3118 //  If a tail called function callee has more arguments than the caller the
3119 //  caller needs to make sure that there is room to move the RETADDR to. This is
3120 //  achieved by reserving an area the size of the argument delta right after the
3121 //  original RETADDR, but before the saved framepointer or the spilled registers
3122 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3123 //  stack layout:
3124 //    arg1
3125 //    arg2
3126 //    RETADDR
3127 //    [ new RETADDR
3128 //      move area ]
3129 //    (possible EBP)
3130 //    ESI
3131 //    EDI
3132 //    local1 ..
3133
3134 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3135 /// for a 16 byte align requirement.
3136 unsigned
3137 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3138                                                SelectionDAG& DAG) const {
3139   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3140   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3141   unsigned StackAlignment = TFI.getStackAlignment();
3142   uint64_t AlignMask = StackAlignment - 1;
3143   int64_t Offset = StackSize;
3144   unsigned SlotSize = RegInfo->getSlotSize();
3145   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3146     // Number smaller than 12 so just add the difference.
3147     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3148   } else {
3149     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3150     Offset = ((~AlignMask) & Offset) + StackAlignment +
3151       (StackAlignment-SlotSize);
3152   }
3153   return Offset;
3154 }
3155
3156 /// MatchingStackOffset - Return true if the given stack call argument is
3157 /// already available in the same position (relatively) of the caller's
3158 /// incoming argument stack.
3159 static
3160 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3161                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3162                          const X86InstrInfo *TII) {
3163   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3164   int FI = INT_MAX;
3165   if (Arg.getOpcode() == ISD::CopyFromReg) {
3166     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3167     if (!TargetRegisterInfo::isVirtualRegister(VR))
3168       return false;
3169     MachineInstr *Def = MRI->getVRegDef(VR);
3170     if (!Def)
3171       return false;
3172     if (!Flags.isByVal()) {
3173       if (!TII->isLoadFromStackSlot(Def, FI))
3174         return false;
3175     } else {
3176       unsigned Opcode = Def->getOpcode();
3177       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3178            Opcode == X86::LEA64_32r) &&
3179           Def->getOperand(1).isFI()) {
3180         FI = Def->getOperand(1).getIndex();
3181         Bytes = Flags.getByValSize();
3182       } else
3183         return false;
3184     }
3185   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3186     if (Flags.isByVal())
3187       // ByVal argument is passed in as a pointer but it's now being
3188       // dereferenced. e.g.
3189       // define @foo(%struct.X* %A) {
3190       //   tail call @bar(%struct.X* byval %A)
3191       // }
3192       return false;
3193     SDValue Ptr = Ld->getBasePtr();
3194     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3195     if (!FINode)
3196       return false;
3197     FI = FINode->getIndex();
3198   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3199     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3200     FI = FINode->getIndex();
3201     Bytes = Flags.getByValSize();
3202   } else
3203     return false;
3204
3205   assert(FI != INT_MAX);
3206   if (!MFI->isFixedObjectIndex(FI))
3207     return false;
3208   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3209 }
3210
3211 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3212 /// for tail call optimization. Targets which want to do tail call
3213 /// optimization should implement this function.
3214 bool
3215 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3216                                                      CallingConv::ID CalleeCC,
3217                                                      bool isVarArg,
3218                                                      bool isCalleeStructRet,
3219                                                      bool isCallerStructRet,
3220                                                      Type *RetTy,
3221                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3222                                     const SmallVectorImpl<SDValue> &OutVals,
3223                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3224                                                      SelectionDAG &DAG) const {
3225   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3226     return false;
3227
3228   // If -tailcallopt is specified, make fastcc functions tail-callable.
3229   const MachineFunction &MF = DAG.getMachineFunction();
3230   const Function *CallerF = MF.getFunction();
3231
3232   // If the function return type is x86_fp80 and the callee return type is not,
3233   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3234   // perform a tailcall optimization here.
3235   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3236     return false;
3237
3238   CallingConv::ID CallerCC = CallerF->getCallingConv();
3239   bool CCMatch = CallerCC == CalleeCC;
3240   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3241   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3242
3243   // Win64 functions have extra shadow space for argument homing. Don't do the
3244   // sibcall if the caller and callee have mismatched expectations for this
3245   // space.
3246   if (IsCalleeWin64 != IsCallerWin64)
3247     return false;
3248
3249   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3250     if (IsTailCallConvention(CalleeCC) && CCMatch)
3251       return true;
3252     return false;
3253   }
3254
3255   // Look for obvious safe cases to perform tail call optimization that do not
3256   // require ABI changes. This is what gcc calls sibcall.
3257
3258   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3259   // emit a special epilogue.
3260   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3261   if (RegInfo->needsStackRealignment(MF))
3262     return false;
3263
3264   // Also avoid sibcall optimization if either caller or callee uses struct
3265   // return semantics.
3266   if (isCalleeStructRet || isCallerStructRet)
3267     return false;
3268
3269   // An stdcall/thiscall caller is expected to clean up its arguments; the
3270   // callee isn't going to do that.
3271   // FIXME: this is more restrictive than needed. We could produce a tailcall
3272   // when the stack adjustment matches. For example, with a thiscall that takes
3273   // only one argument.
3274   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3275                    CallerCC == CallingConv::X86_ThisCall))
3276     return false;
3277
3278   // Do not sibcall optimize vararg calls unless all arguments are passed via
3279   // registers.
3280   if (isVarArg && !Outs.empty()) {
3281
3282     // Optimizing for varargs on Win64 is unlikely to be safe without
3283     // additional testing.
3284     if (IsCalleeWin64 || IsCallerWin64)
3285       return false;
3286
3287     SmallVector<CCValAssign, 16> ArgLocs;
3288     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3289                    *DAG.getContext());
3290
3291     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3292     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3293       if (!ArgLocs[i].isRegLoc())
3294         return false;
3295   }
3296
3297   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3298   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3299   // this into a sibcall.
3300   bool Unused = false;
3301   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3302     if (!Ins[i].Used) {
3303       Unused = true;
3304       break;
3305     }
3306   }
3307   if (Unused) {
3308     SmallVector<CCValAssign, 16> RVLocs;
3309     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3310                    *DAG.getContext());
3311     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3312     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3313       CCValAssign &VA = RVLocs[i];
3314       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3315         return false;
3316     }
3317   }
3318
3319   // If the calling conventions do not match, then we'd better make sure the
3320   // results are returned in the same way as what the caller expects.
3321   if (!CCMatch) {
3322     SmallVector<CCValAssign, 16> RVLocs1;
3323     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3324                     *DAG.getContext());
3325     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3326
3327     SmallVector<CCValAssign, 16> RVLocs2;
3328     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3329                     *DAG.getContext());
3330     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3331
3332     if (RVLocs1.size() != RVLocs2.size())
3333       return false;
3334     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3335       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3336         return false;
3337       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3338         return false;
3339       if (RVLocs1[i].isRegLoc()) {
3340         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3341           return false;
3342       } else {
3343         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3344           return false;
3345       }
3346     }
3347   }
3348
3349   // If the callee takes no arguments then go on to check the results of the
3350   // call.
3351   if (!Outs.empty()) {
3352     // Check if stack adjustment is needed. For now, do not do this if any
3353     // argument is passed on the stack.
3354     SmallVector<CCValAssign, 16> ArgLocs;
3355     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3356                    *DAG.getContext());
3357
3358     // Allocate shadow area for Win64
3359     if (IsCalleeWin64)
3360       CCInfo.AllocateStack(32, 8);
3361
3362     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3363     if (CCInfo.getNextStackOffset()) {
3364       MachineFunction &MF = DAG.getMachineFunction();
3365       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3366         return false;
3367
3368       // Check if the arguments are already laid out in the right way as
3369       // the caller's fixed stack objects.
3370       MachineFrameInfo *MFI = MF.getFrameInfo();
3371       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3372       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3373       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3374         CCValAssign &VA = ArgLocs[i];
3375         SDValue Arg = OutVals[i];
3376         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3377         if (VA.getLocInfo() == CCValAssign::Indirect)
3378           return false;
3379         if (!VA.isRegLoc()) {
3380           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3381                                    MFI, MRI, TII))
3382             return false;
3383         }
3384       }
3385     }
3386
3387     // If the tailcall address may be in a register, then make sure it's
3388     // possible to register allocate for it. In 32-bit, the call address can
3389     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3390     // callee-saved registers are restored. These happen to be the same
3391     // registers used to pass 'inreg' arguments so watch out for those.
3392     if (!Subtarget->is64Bit() &&
3393         ((!isa<GlobalAddressSDNode>(Callee) &&
3394           !isa<ExternalSymbolSDNode>(Callee)) ||
3395          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3396       unsigned NumInRegs = 0;
3397       // In PIC we need an extra register to formulate the address computation
3398       // for the callee.
3399       unsigned MaxInRegs =
3400         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3401
3402       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3403         CCValAssign &VA = ArgLocs[i];
3404         if (!VA.isRegLoc())
3405           continue;
3406         unsigned Reg = VA.getLocReg();
3407         switch (Reg) {
3408         default: break;
3409         case X86::EAX: case X86::EDX: case X86::ECX:
3410           if (++NumInRegs == MaxInRegs)
3411             return false;
3412           break;
3413         }
3414       }
3415     }
3416   }
3417
3418   return true;
3419 }
3420
3421 FastISel *
3422 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3423                                   const TargetLibraryInfo *libInfo) const {
3424   return X86::createFastISel(funcInfo, libInfo);
3425 }
3426
3427 //===----------------------------------------------------------------------===//
3428 //                           Other Lowering Hooks
3429 //===----------------------------------------------------------------------===//
3430
3431 static bool MayFoldLoad(SDValue Op) {
3432   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3433 }
3434
3435 static bool MayFoldIntoStore(SDValue Op) {
3436   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3437 }
3438
3439 static bool isTargetShuffle(unsigned Opcode) {
3440   switch(Opcode) {
3441   default: return false;
3442   case X86ISD::BLENDI:
3443   case X86ISD::PSHUFB:
3444   case X86ISD::PSHUFD:
3445   case X86ISD::PSHUFHW:
3446   case X86ISD::PSHUFLW:
3447   case X86ISD::SHUFP:
3448   case X86ISD::PALIGNR:
3449   case X86ISD::MOVLHPS:
3450   case X86ISD::MOVLHPD:
3451   case X86ISD::MOVHLPS:
3452   case X86ISD::MOVLPS:
3453   case X86ISD::MOVLPD:
3454   case X86ISD::MOVSHDUP:
3455   case X86ISD::MOVSLDUP:
3456   case X86ISD::MOVDDUP:
3457   case X86ISD::MOVSS:
3458   case X86ISD::MOVSD:
3459   case X86ISD::UNPCKL:
3460   case X86ISD::UNPCKH:
3461   case X86ISD::VPERMILPI:
3462   case X86ISD::VPERM2X128:
3463   case X86ISD::VPERMI:
3464     return true;
3465   }
3466 }
3467
3468 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3469                                     SDValue V1, unsigned TargetMask,
3470                                     SelectionDAG &DAG) {
3471   switch(Opc) {
3472   default: llvm_unreachable("Unknown x86 shuffle node");
3473   case X86ISD::PSHUFD:
3474   case X86ISD::PSHUFHW:
3475   case X86ISD::PSHUFLW:
3476   case X86ISD::VPERMILPI:
3477   case X86ISD::VPERMI:
3478     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3479   }
3480 }
3481
3482 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3483                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3484   switch(Opc) {
3485   default: llvm_unreachable("Unknown x86 shuffle node");
3486   case X86ISD::MOVLHPS:
3487   case X86ISD::MOVLHPD:
3488   case X86ISD::MOVHLPS:
3489   case X86ISD::MOVLPS:
3490   case X86ISD::MOVLPD:
3491   case X86ISD::MOVSS:
3492   case X86ISD::MOVSD:
3493   case X86ISD::UNPCKL:
3494   case X86ISD::UNPCKH:
3495     return DAG.getNode(Opc, dl, VT, V1, V2);
3496   }
3497 }
3498
3499 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3500   MachineFunction &MF = DAG.getMachineFunction();
3501   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3502   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3503   int ReturnAddrIndex = FuncInfo->getRAIndex();
3504
3505   if (ReturnAddrIndex == 0) {
3506     // Set up a frame object for the return address.
3507     unsigned SlotSize = RegInfo->getSlotSize();
3508     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3509                                                            -(int64_t)SlotSize,
3510                                                            false);
3511     FuncInfo->setRAIndex(ReturnAddrIndex);
3512   }
3513
3514   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3515 }
3516
3517 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3518                                        bool hasSymbolicDisplacement) {
3519   // Offset should fit into 32 bit immediate field.
3520   if (!isInt<32>(Offset))
3521     return false;
3522
3523   // If we don't have a symbolic displacement - we don't have any extra
3524   // restrictions.
3525   if (!hasSymbolicDisplacement)
3526     return true;
3527
3528   // FIXME: Some tweaks might be needed for medium code model.
3529   if (M != CodeModel::Small && M != CodeModel::Kernel)
3530     return false;
3531
3532   // For small code model we assume that latest object is 16MB before end of 31
3533   // bits boundary. We may also accept pretty large negative constants knowing
3534   // that all objects are in the positive half of address space.
3535   if (M == CodeModel::Small && Offset < 16*1024*1024)
3536     return true;
3537
3538   // For kernel code model we know that all object resist in the negative half
3539   // of 32bits address space. We may not accept negative offsets, since they may
3540   // be just off and we may accept pretty large positive ones.
3541   if (M == CodeModel::Kernel && Offset >= 0)
3542     return true;
3543
3544   return false;
3545 }
3546
3547 /// isCalleePop - Determines whether the callee is required to pop its
3548 /// own arguments. Callee pop is necessary to support tail calls.
3549 bool X86::isCalleePop(CallingConv::ID CallingConv,
3550                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3551   switch (CallingConv) {
3552   default:
3553     return false;
3554   case CallingConv::X86_StdCall:
3555   case CallingConv::X86_FastCall:
3556   case CallingConv::X86_ThisCall:
3557     return !is64Bit;
3558   case CallingConv::Fast:
3559   case CallingConv::GHC:
3560   case CallingConv::HiPE:
3561     if (IsVarArg)
3562       return false;
3563     return TailCallOpt;
3564   }
3565 }
3566
3567 /// \brief Return true if the condition is an unsigned comparison operation.
3568 static bool isX86CCUnsigned(unsigned X86CC) {
3569   switch (X86CC) {
3570   default: llvm_unreachable("Invalid integer condition!");
3571   case X86::COND_E:     return true;
3572   case X86::COND_G:     return false;
3573   case X86::COND_GE:    return false;
3574   case X86::COND_L:     return false;
3575   case X86::COND_LE:    return false;
3576   case X86::COND_NE:    return true;
3577   case X86::COND_B:     return true;
3578   case X86::COND_A:     return true;
3579   case X86::COND_BE:    return true;
3580   case X86::COND_AE:    return true;
3581   }
3582   llvm_unreachable("covered switch fell through?!");
3583 }
3584
3585 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3586 /// specific condition code, returning the condition code and the LHS/RHS of the
3587 /// comparison to make.
3588 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3589                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3590   if (!isFP) {
3591     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3592       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3593         // X > -1   -> X == 0, jump !sign.
3594         RHS = DAG.getConstant(0, RHS.getValueType());
3595         return X86::COND_NS;
3596       }
3597       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3598         // X < 0   -> X == 0, jump on sign.
3599         return X86::COND_S;
3600       }
3601       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3602         // X < 1   -> X <= 0
3603         RHS = DAG.getConstant(0, RHS.getValueType());
3604         return X86::COND_LE;
3605       }
3606     }
3607
3608     switch (SetCCOpcode) {
3609     default: llvm_unreachable("Invalid integer condition!");
3610     case ISD::SETEQ:  return X86::COND_E;
3611     case ISD::SETGT:  return X86::COND_G;
3612     case ISD::SETGE:  return X86::COND_GE;
3613     case ISD::SETLT:  return X86::COND_L;
3614     case ISD::SETLE:  return X86::COND_LE;
3615     case ISD::SETNE:  return X86::COND_NE;
3616     case ISD::SETULT: return X86::COND_B;
3617     case ISD::SETUGT: return X86::COND_A;
3618     case ISD::SETULE: return X86::COND_BE;
3619     case ISD::SETUGE: return X86::COND_AE;
3620     }
3621   }
3622
3623   // First determine if it is required or is profitable to flip the operands.
3624
3625   // If LHS is a foldable load, but RHS is not, flip the condition.
3626   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3627       !ISD::isNON_EXTLoad(RHS.getNode())) {
3628     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3629     std::swap(LHS, RHS);
3630   }
3631
3632   switch (SetCCOpcode) {
3633   default: break;
3634   case ISD::SETOLT:
3635   case ISD::SETOLE:
3636   case ISD::SETUGT:
3637   case ISD::SETUGE:
3638     std::swap(LHS, RHS);
3639     break;
3640   }
3641
3642   // On a floating point condition, the flags are set as follows:
3643   // ZF  PF  CF   op
3644   //  0 | 0 | 0 | X > Y
3645   //  0 | 0 | 1 | X < Y
3646   //  1 | 0 | 0 | X == Y
3647   //  1 | 1 | 1 | unordered
3648   switch (SetCCOpcode) {
3649   default: llvm_unreachable("Condcode should be pre-legalized away");
3650   case ISD::SETUEQ:
3651   case ISD::SETEQ:   return X86::COND_E;
3652   case ISD::SETOLT:              // flipped
3653   case ISD::SETOGT:
3654   case ISD::SETGT:   return X86::COND_A;
3655   case ISD::SETOLE:              // flipped
3656   case ISD::SETOGE:
3657   case ISD::SETGE:   return X86::COND_AE;
3658   case ISD::SETUGT:              // flipped
3659   case ISD::SETULT:
3660   case ISD::SETLT:   return X86::COND_B;
3661   case ISD::SETUGE:              // flipped
3662   case ISD::SETULE:
3663   case ISD::SETLE:   return X86::COND_BE;
3664   case ISD::SETONE:
3665   case ISD::SETNE:   return X86::COND_NE;
3666   case ISD::SETUO:   return X86::COND_P;
3667   case ISD::SETO:    return X86::COND_NP;
3668   case ISD::SETOEQ:
3669   case ISD::SETUNE:  return X86::COND_INVALID;
3670   }
3671 }
3672
3673 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3674 /// code. Current x86 isa includes the following FP cmov instructions:
3675 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3676 static bool hasFPCMov(unsigned X86CC) {
3677   switch (X86CC) {
3678   default:
3679     return false;
3680   case X86::COND_B:
3681   case X86::COND_BE:
3682   case X86::COND_E:
3683   case X86::COND_P:
3684   case X86::COND_A:
3685   case X86::COND_AE:
3686   case X86::COND_NE:
3687   case X86::COND_NP:
3688     return true;
3689   }
3690 }
3691
3692 /// isFPImmLegal - Returns true if the target can instruction select the
3693 /// specified FP immediate natively. If false, the legalizer will
3694 /// materialize the FP immediate as a load from a constant pool.
3695 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3696   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3697     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3698       return true;
3699   }
3700   return false;
3701 }
3702
3703 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3704                                               ISD::LoadExtType ExtTy,
3705                                               EVT NewVT) const {
3706   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3707   // relocation target a movq or addq instruction: don't let the load shrink.
3708   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3709   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3710     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3711       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3712   return true;
3713 }
3714
3715 /// \brief Returns true if it is beneficial to convert a load of a constant
3716 /// to just the constant itself.
3717 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3718                                                           Type *Ty) const {
3719   assert(Ty->isIntegerTy());
3720
3721   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3722   if (BitSize == 0 || BitSize > 64)
3723     return false;
3724   return true;
3725 }
3726
3727 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3728                                                 unsigned Index) const {
3729   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3730     return false;
3731
3732   return (Index == 0 || Index == ResVT.getVectorNumElements());
3733 }
3734
3735 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3736   // Speculate cttz only if we can directly use TZCNT.
3737   return Subtarget->hasBMI();
3738 }
3739
3740 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3741   // Speculate ctlz only if we can directly use LZCNT.
3742   return Subtarget->hasLZCNT();
3743 }
3744
3745 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3746 /// the specified range (L, H].
3747 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3748   return (Val < 0) || (Val >= Low && Val < Hi);
3749 }
3750
3751 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3752 /// specified value.
3753 static bool isUndefOrEqual(int Val, int CmpVal) {
3754   return (Val < 0 || Val == CmpVal);
3755 }
3756
3757 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3758 /// from position Pos and ending in Pos+Size, falls within the specified
3759 /// sequential range (Low, Low+Size]. or is undef.
3760 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3761                                        unsigned Pos, unsigned Size, int Low) {
3762   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3763     if (!isUndefOrEqual(Mask[i], Low))
3764       return false;
3765   return true;
3766 }
3767
3768 /// isVEXTRACTIndex - Return true if the specified
3769 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3770 /// suitable for instruction that extract 128 or 256 bit vectors
3771 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3772   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3773   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3774     return false;
3775
3776   // The index should be aligned on a vecWidth-bit boundary.
3777   uint64_t Index =
3778     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3779
3780   MVT VT = N->getSimpleValueType(0);
3781   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3782   bool Result = (Index * ElSize) % vecWidth == 0;
3783
3784   return Result;
3785 }
3786
3787 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3788 /// operand specifies a subvector insert that is suitable for input to
3789 /// insertion of 128 or 256-bit subvectors
3790 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3791   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3792   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3793     return false;
3794   // The index should be aligned on a vecWidth-bit boundary.
3795   uint64_t Index =
3796     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3797
3798   MVT VT = N->getSimpleValueType(0);
3799   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3800   bool Result = (Index * ElSize) % vecWidth == 0;
3801
3802   return Result;
3803 }
3804
3805 bool X86::isVINSERT128Index(SDNode *N) {
3806   return isVINSERTIndex(N, 128);
3807 }
3808
3809 bool X86::isVINSERT256Index(SDNode *N) {
3810   return isVINSERTIndex(N, 256);
3811 }
3812
3813 bool X86::isVEXTRACT128Index(SDNode *N) {
3814   return isVEXTRACTIndex(N, 128);
3815 }
3816
3817 bool X86::isVEXTRACT256Index(SDNode *N) {
3818   return isVEXTRACTIndex(N, 256);
3819 }
3820
3821 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3822   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3823   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3824     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3825
3826   uint64_t Index =
3827     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3828
3829   MVT VecVT = N->getOperand(0).getSimpleValueType();
3830   MVT ElVT = VecVT.getVectorElementType();
3831
3832   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3833   return Index / NumElemsPerChunk;
3834 }
3835
3836 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3837   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3838   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3839     llvm_unreachable("Illegal insert subvector for VINSERT");
3840
3841   uint64_t Index =
3842     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3843
3844   MVT VecVT = N->getSimpleValueType(0);
3845   MVT ElVT = VecVT.getVectorElementType();
3846
3847   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3848   return Index / NumElemsPerChunk;
3849 }
3850
3851 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3852 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3853 /// and VINSERTI128 instructions.
3854 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3855   return getExtractVEXTRACTImmediate(N, 128);
3856 }
3857
3858 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3859 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3860 /// and VINSERTI64x4 instructions.
3861 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3862   return getExtractVEXTRACTImmediate(N, 256);
3863 }
3864
3865 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3866 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3867 /// and VINSERTI128 instructions.
3868 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3869   return getInsertVINSERTImmediate(N, 128);
3870 }
3871
3872 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3873 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3874 /// and VINSERTI64x4 instructions.
3875 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3876   return getInsertVINSERTImmediate(N, 256);
3877 }
3878
3879 /// isZero - Returns true if Elt is a constant integer zero
3880 static bool isZero(SDValue V) {
3881   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3882   return C && C->isNullValue();
3883 }
3884
3885 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3886 /// constant +0.0.
3887 bool X86::isZeroNode(SDValue Elt) {
3888   if (isZero(Elt))
3889     return true;
3890   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
3891     return CFP->getValueAPF().isPosZero();
3892   return false;
3893 }
3894
3895 /// getZeroVector - Returns a vector of specified type with all zero elements.
3896 ///
3897 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
3898                              SelectionDAG &DAG, SDLoc dl) {
3899   assert(VT.isVector() && "Expected a vector type");
3900
3901   // Always build SSE zero vectors as <4 x i32> bitcasted
3902   // to their dest type. This ensures they get CSE'd.
3903   SDValue Vec;
3904   if (VT.is128BitVector()) {  // SSE
3905     if (Subtarget->hasSSE2()) {  // SSE2
3906       SDValue Cst = DAG.getConstant(0, MVT::i32);
3907       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3908     } else { // SSE1
3909       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
3910       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3911     }
3912   } else if (VT.is256BitVector()) { // AVX
3913     if (Subtarget->hasInt256()) { // AVX2
3914       SDValue Cst = DAG.getConstant(0, MVT::i32);
3915       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3916       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
3917     } else {
3918       // 256-bit logic and arithmetic instructions in AVX are all
3919       // floating-point, no support for integer ops. Emit fp zeroed vectors.
3920       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
3921       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3922       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
3923     }
3924   } else if (VT.is512BitVector()) { // AVX-512
3925       SDValue Cst = DAG.getConstant(0, MVT::i32);
3926       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
3927                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3928       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
3929   } else if (VT.getScalarType() == MVT::i1) {
3930
3931     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
3932             && "Unexpected vector type");
3933     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
3934             && "Unexpected vector type");
3935     SDValue Cst = DAG.getConstant(0, MVT::i1);
3936     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
3937     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
3938   } else
3939     llvm_unreachable("Unexpected vector type");
3940
3941   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3942 }
3943
3944 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
3945                                 SelectionDAG &DAG, SDLoc dl,
3946                                 unsigned vectorWidth) {
3947   assert((vectorWidth == 128 || vectorWidth == 256) &&
3948          "Unsupported vector width");
3949   EVT VT = Vec.getValueType();
3950   EVT ElVT = VT.getVectorElementType();
3951   unsigned Factor = VT.getSizeInBits()/vectorWidth;
3952   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
3953                                   VT.getVectorNumElements()/Factor);
3954
3955   // Extract from UNDEF is UNDEF.
3956   if (Vec.getOpcode() == ISD::UNDEF)
3957     return DAG.getUNDEF(ResultVT);
3958
3959   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
3960   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
3961
3962   // This is the index of the first element of the vectorWidth-bit chunk
3963   // we want.
3964   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
3965                                * ElemsPerChunk);
3966
3967   // If the input is a buildvector just emit a smaller one.
3968   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
3969     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
3970                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
3971                                     ElemsPerChunk));
3972
3973   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
3974   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
3975 }
3976
3977 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
3978 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
3979 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
3980 /// instructions or a simple subregister reference. Idx is an index in the
3981 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
3982 /// lowering EXTRACT_VECTOR_ELT operations easier.
3983 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
3984                                    SelectionDAG &DAG, SDLoc dl) {
3985   assert((Vec.getValueType().is256BitVector() ||
3986           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
3987   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
3988 }
3989
3990 /// Generate a DAG to grab 256-bits from a 512-bit vector.
3991 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
3992                                    SelectionDAG &DAG, SDLoc dl) {
3993   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
3994   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
3995 }
3996
3997 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
3998                                unsigned IdxVal, SelectionDAG &DAG,
3999                                SDLoc dl, unsigned vectorWidth) {
4000   assert((vectorWidth == 128 || vectorWidth == 256) &&
4001          "Unsupported vector width");
4002   // Inserting UNDEF is Result
4003   if (Vec.getOpcode() == ISD::UNDEF)
4004     return Result;
4005   EVT VT = Vec.getValueType();
4006   EVT ElVT = VT.getVectorElementType();
4007   EVT ResultVT = Result.getValueType();
4008
4009   // Insert the relevant vectorWidth bits.
4010   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4011
4012   // This is the index of the first element of the vectorWidth-bit chunk
4013   // we want.
4014   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4015                                * ElemsPerChunk);
4016
4017   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
4018   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4019 }
4020
4021 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4022 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4023 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4024 /// simple superregister reference.  Idx is an index in the 128 bits
4025 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4026 /// lowering INSERT_VECTOR_ELT operations easier.
4027 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4028                                   SelectionDAG &DAG, SDLoc dl) {
4029   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4030
4031   // For insertion into the zero index (low half) of a 256-bit vector, it is
4032   // more efficient to generate a blend with immediate instead of an insert*128.
4033   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4034   // extend the subvector to the size of the result vector. Make sure that
4035   // we are not recursing on that node by checking for undef here.
4036   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4037       Result.getOpcode() != ISD::UNDEF) {
4038     EVT ResultVT = Result.getValueType();
4039     SDValue ZeroIndex = DAG.getIntPtrConstant(0);
4040     SDValue Undef = DAG.getUNDEF(ResultVT);
4041     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4042                                  Vec, ZeroIndex);
4043
4044     // The blend instruction, and therefore its mask, depend on the data type.
4045     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4046     if (ScalarType.isFloatingPoint()) {
4047       // Choose either vblendps (float) or vblendpd (double).
4048       unsigned ScalarSize = ScalarType.getSizeInBits();
4049       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4050       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4051       SDValue Mask = DAG.getConstant(MaskVal, MVT::i8);
4052       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4053     }
4054
4055     const X86Subtarget &Subtarget =
4056     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4057
4058     // AVX2 is needed for 256-bit integer blend support.
4059     // Integers must be cast to 32-bit because there is only vpblendd;
4060     // vpblendw can't be used for this because it has a handicapped mask.
4061
4062     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4063     // is still more efficient than using the wrong domain vinsertf128 that
4064     // will be created by InsertSubVector().
4065     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4066
4067     SDValue Mask = DAG.getConstant(0x0f, MVT::i8);
4068     Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4069     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4070     return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4071   }
4072
4073   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4074 }
4075
4076 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4077                                   SelectionDAG &DAG, SDLoc dl) {
4078   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4079   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4080 }
4081
4082 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4083 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4084 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4085 /// large BUILD_VECTORS.
4086 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4087                                    unsigned NumElems, SelectionDAG &DAG,
4088                                    SDLoc dl) {
4089   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4090   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4091 }
4092
4093 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4094                                    unsigned NumElems, SelectionDAG &DAG,
4095                                    SDLoc dl) {
4096   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4097   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4098 }
4099
4100 /// getOnesVector - Returns a vector of specified type with all bits set.
4101 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4102 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4103 /// Then bitcast to their original type, ensuring they get CSE'd.
4104 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4105                              SDLoc dl) {
4106   assert(VT.isVector() && "Expected a vector type");
4107
4108   SDValue Cst = DAG.getConstant(~0U, MVT::i32);
4109   SDValue Vec;
4110   if (VT.is256BitVector()) {
4111     if (HasInt256) { // AVX2
4112       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4113       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4114     } else { // AVX
4115       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4116       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4117     }
4118   } else if (VT.is128BitVector()) {
4119     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4120   } else
4121     llvm_unreachable("Unexpected vector type");
4122
4123   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4124 }
4125
4126 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4127 /// operation of specified width.
4128 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4129                        SDValue V2) {
4130   unsigned NumElems = VT.getVectorNumElements();
4131   SmallVector<int, 8> Mask;
4132   Mask.push_back(NumElems);
4133   for (unsigned i = 1; i != NumElems; ++i)
4134     Mask.push_back(i);
4135   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4136 }
4137
4138 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4139 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4140                           SDValue V2) {
4141   unsigned NumElems = VT.getVectorNumElements();
4142   SmallVector<int, 8> Mask;
4143   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4144     Mask.push_back(i);
4145     Mask.push_back(i + NumElems);
4146   }
4147   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4148 }
4149
4150 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4151 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4152                           SDValue V2) {
4153   unsigned NumElems = VT.getVectorNumElements();
4154   SmallVector<int, 8> Mask;
4155   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4156     Mask.push_back(i + Half);
4157     Mask.push_back(i + NumElems + Half);
4158   }
4159   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4160 }
4161
4162 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4163 /// vector of zero or undef vector.  This produces a shuffle where the low
4164 /// element of V2 is swizzled into the zero/undef vector, landing at element
4165 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4166 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4167                                            bool IsZero,
4168                                            const X86Subtarget *Subtarget,
4169                                            SelectionDAG &DAG) {
4170   MVT VT = V2.getSimpleValueType();
4171   SDValue V1 = IsZero
4172     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4173   unsigned NumElems = VT.getVectorNumElements();
4174   SmallVector<int, 16> MaskVec;
4175   for (unsigned i = 0; i != NumElems; ++i)
4176     // If this is the insertion idx, put the low elt of V2 here.
4177     MaskVec.push_back(i == Idx ? NumElems : i);
4178   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4179 }
4180
4181 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4182 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4183 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4184 /// shuffles which use a single input multiple times, and in those cases it will
4185 /// adjust the mask to only have indices within that single input.
4186 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4187                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4188   unsigned NumElems = VT.getVectorNumElements();
4189   SDValue ImmN;
4190
4191   IsUnary = false;
4192   bool IsFakeUnary = false;
4193   switch(N->getOpcode()) {
4194   case X86ISD::BLENDI:
4195     ImmN = N->getOperand(N->getNumOperands()-1);
4196     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4197     break;
4198   case X86ISD::SHUFP:
4199     ImmN = N->getOperand(N->getNumOperands()-1);
4200     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4201     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4202     break;
4203   case X86ISD::UNPCKH:
4204     DecodeUNPCKHMask(VT, Mask);
4205     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4206     break;
4207   case X86ISD::UNPCKL:
4208     DecodeUNPCKLMask(VT, Mask);
4209     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4210     break;
4211   case X86ISD::MOVHLPS:
4212     DecodeMOVHLPSMask(NumElems, Mask);
4213     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4214     break;
4215   case X86ISD::MOVLHPS:
4216     DecodeMOVLHPSMask(NumElems, Mask);
4217     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4218     break;
4219   case X86ISD::PALIGNR:
4220     ImmN = N->getOperand(N->getNumOperands()-1);
4221     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4222     break;
4223   case X86ISD::PSHUFD:
4224   case X86ISD::VPERMILPI:
4225     ImmN = N->getOperand(N->getNumOperands()-1);
4226     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4227     IsUnary = true;
4228     break;
4229   case X86ISD::PSHUFHW:
4230     ImmN = N->getOperand(N->getNumOperands()-1);
4231     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4232     IsUnary = true;
4233     break;
4234   case X86ISD::PSHUFLW:
4235     ImmN = N->getOperand(N->getNumOperands()-1);
4236     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4237     IsUnary = true;
4238     break;
4239   case X86ISD::PSHUFB: {
4240     IsUnary = true;
4241     SDValue MaskNode = N->getOperand(1);
4242     while (MaskNode->getOpcode() == ISD::BITCAST)
4243       MaskNode = MaskNode->getOperand(0);
4244
4245     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4246       // If we have a build-vector, then things are easy.
4247       EVT VT = MaskNode.getValueType();
4248       assert(VT.isVector() &&
4249              "Can't produce a non-vector with a build_vector!");
4250       if (!VT.isInteger())
4251         return false;
4252
4253       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4254
4255       SmallVector<uint64_t, 32> RawMask;
4256       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4257         SDValue Op = MaskNode->getOperand(i);
4258         if (Op->getOpcode() == ISD::UNDEF) {
4259           RawMask.push_back((uint64_t)SM_SentinelUndef);
4260           continue;
4261         }
4262         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4263         if (!CN)
4264           return false;
4265         APInt MaskElement = CN->getAPIntValue();
4266
4267         // We now have to decode the element which could be any integer size and
4268         // extract each byte of it.
4269         for (int j = 0; j < NumBytesPerElement; ++j) {
4270           // Note that this is x86 and so always little endian: the low byte is
4271           // the first byte of the mask.
4272           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4273           MaskElement = MaskElement.lshr(8);
4274         }
4275       }
4276       DecodePSHUFBMask(RawMask, Mask);
4277       break;
4278     }
4279
4280     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4281     if (!MaskLoad)
4282       return false;
4283
4284     SDValue Ptr = MaskLoad->getBasePtr();
4285     if (Ptr->getOpcode() == X86ISD::Wrapper)
4286       Ptr = Ptr->getOperand(0);
4287
4288     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4289     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4290       return false;
4291
4292     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4293       DecodePSHUFBMask(C, Mask);
4294       if (Mask.empty())
4295         return false;
4296       break;
4297     }
4298
4299     return false;
4300   }
4301   case X86ISD::VPERMI:
4302     ImmN = N->getOperand(N->getNumOperands()-1);
4303     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4304     IsUnary = true;
4305     break;
4306   case X86ISD::MOVSS:
4307   case X86ISD::MOVSD:
4308     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4309     break;
4310   case X86ISD::VPERM2X128:
4311     ImmN = N->getOperand(N->getNumOperands()-1);
4312     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4313     if (Mask.empty()) return false;
4314     break;
4315   case X86ISD::MOVSLDUP:
4316     DecodeMOVSLDUPMask(VT, Mask);
4317     IsUnary = true;
4318     break;
4319   case X86ISD::MOVSHDUP:
4320     DecodeMOVSHDUPMask(VT, Mask);
4321     IsUnary = true;
4322     break;
4323   case X86ISD::MOVDDUP:
4324     DecodeMOVDDUPMask(VT, Mask);
4325     IsUnary = true;
4326     break;
4327   case X86ISD::MOVLHPD:
4328   case X86ISD::MOVLPD:
4329   case X86ISD::MOVLPS:
4330     // Not yet implemented
4331     return false;
4332   default: llvm_unreachable("unknown target shuffle node");
4333   }
4334
4335   // If we have a fake unary shuffle, the shuffle mask is spread across two
4336   // inputs that are actually the same node. Re-map the mask to always point
4337   // into the first input.
4338   if (IsFakeUnary)
4339     for (int &M : Mask)
4340       if (M >= (int)Mask.size())
4341         M -= Mask.size();
4342
4343   return true;
4344 }
4345
4346 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4347 /// element of the result of the vector shuffle.
4348 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4349                                    unsigned Depth) {
4350   if (Depth == 6)
4351     return SDValue();  // Limit search depth.
4352
4353   SDValue V = SDValue(N, 0);
4354   EVT VT = V.getValueType();
4355   unsigned Opcode = V.getOpcode();
4356
4357   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4358   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4359     int Elt = SV->getMaskElt(Index);
4360
4361     if (Elt < 0)
4362       return DAG.getUNDEF(VT.getVectorElementType());
4363
4364     unsigned NumElems = VT.getVectorNumElements();
4365     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4366                                          : SV->getOperand(1);
4367     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4368   }
4369
4370   // Recurse into target specific vector shuffles to find scalars.
4371   if (isTargetShuffle(Opcode)) {
4372     MVT ShufVT = V.getSimpleValueType();
4373     unsigned NumElems = ShufVT.getVectorNumElements();
4374     SmallVector<int, 16> ShuffleMask;
4375     bool IsUnary;
4376
4377     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4378       return SDValue();
4379
4380     int Elt = ShuffleMask[Index];
4381     if (Elt < 0)
4382       return DAG.getUNDEF(ShufVT.getVectorElementType());
4383
4384     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4385                                          : N->getOperand(1);
4386     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4387                                Depth+1);
4388   }
4389
4390   // Actual nodes that may contain scalar elements
4391   if (Opcode == ISD::BITCAST) {
4392     V = V.getOperand(0);
4393     EVT SrcVT = V.getValueType();
4394     unsigned NumElems = VT.getVectorNumElements();
4395
4396     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4397       return SDValue();
4398   }
4399
4400   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4401     return (Index == 0) ? V.getOperand(0)
4402                         : DAG.getUNDEF(VT.getVectorElementType());
4403
4404   if (V.getOpcode() == ISD::BUILD_VECTOR)
4405     return V.getOperand(Index);
4406
4407   return SDValue();
4408 }
4409
4410 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4411 ///
4412 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4413                                        unsigned NumNonZero, unsigned NumZero,
4414                                        SelectionDAG &DAG,
4415                                        const X86Subtarget* Subtarget,
4416                                        const TargetLowering &TLI) {
4417   if (NumNonZero > 8)
4418     return SDValue();
4419
4420   SDLoc dl(Op);
4421   SDValue V;
4422   bool First = true;
4423   for (unsigned i = 0; i < 16; ++i) {
4424     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4425     if (ThisIsNonZero && First) {
4426       if (NumZero)
4427         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4428       else
4429         V = DAG.getUNDEF(MVT::v8i16);
4430       First = false;
4431     }
4432
4433     if ((i & 1) != 0) {
4434       SDValue ThisElt, LastElt;
4435       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4436       if (LastIsNonZero) {
4437         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4438                               MVT::i16, Op.getOperand(i-1));
4439       }
4440       if (ThisIsNonZero) {
4441         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4442         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4443                               ThisElt, DAG.getConstant(8, MVT::i8));
4444         if (LastIsNonZero)
4445           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4446       } else
4447         ThisElt = LastElt;
4448
4449       if (ThisElt.getNode())
4450         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4451                         DAG.getIntPtrConstant(i/2));
4452     }
4453   }
4454
4455   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4456 }
4457
4458 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4459 ///
4460 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4461                                      unsigned NumNonZero, unsigned NumZero,
4462                                      SelectionDAG &DAG,
4463                                      const X86Subtarget* Subtarget,
4464                                      const TargetLowering &TLI) {
4465   if (NumNonZero > 4)
4466     return SDValue();
4467
4468   SDLoc dl(Op);
4469   SDValue V;
4470   bool First = true;
4471   for (unsigned i = 0; i < 8; ++i) {
4472     bool isNonZero = (NonZeros & (1 << i)) != 0;
4473     if (isNonZero) {
4474       if (First) {
4475         if (NumZero)
4476           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4477         else
4478           V = DAG.getUNDEF(MVT::v8i16);
4479         First = false;
4480       }
4481       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4482                       MVT::v8i16, V, Op.getOperand(i),
4483                       DAG.getIntPtrConstant(i));
4484     }
4485   }
4486
4487   return V;
4488 }
4489
4490 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4491 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4492                                      const X86Subtarget *Subtarget,
4493                                      const TargetLowering &TLI) {
4494   // Find all zeroable elements.
4495   std::bitset<4> Zeroable;
4496   for (int i=0; i < 4; ++i) {
4497     SDValue Elt = Op->getOperand(i);
4498     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4499   }
4500   assert(Zeroable.size() - Zeroable.count() > 1 &&
4501          "We expect at least two non-zero elements!");
4502
4503   // We only know how to deal with build_vector nodes where elements are either
4504   // zeroable or extract_vector_elt with constant index.
4505   SDValue FirstNonZero;
4506   unsigned FirstNonZeroIdx;
4507   for (unsigned i=0; i < 4; ++i) {
4508     if (Zeroable[i])
4509       continue;
4510     SDValue Elt = Op->getOperand(i);
4511     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4512         !isa<ConstantSDNode>(Elt.getOperand(1)))
4513       return SDValue();
4514     // Make sure that this node is extracting from a 128-bit vector.
4515     MVT VT = Elt.getOperand(0).getSimpleValueType();
4516     if (!VT.is128BitVector())
4517       return SDValue();
4518     if (!FirstNonZero.getNode()) {
4519       FirstNonZero = Elt;
4520       FirstNonZeroIdx = i;
4521     }
4522   }
4523
4524   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4525   SDValue V1 = FirstNonZero.getOperand(0);
4526   MVT VT = V1.getSimpleValueType();
4527
4528   // See if this build_vector can be lowered as a blend with zero.
4529   SDValue Elt;
4530   unsigned EltMaskIdx, EltIdx;
4531   int Mask[4];
4532   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4533     if (Zeroable[EltIdx]) {
4534       // The zero vector will be on the right hand side.
4535       Mask[EltIdx] = EltIdx+4;
4536       continue;
4537     }
4538
4539     Elt = Op->getOperand(EltIdx);
4540     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4541     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4542     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4543       break;
4544     Mask[EltIdx] = EltIdx;
4545   }
4546
4547   if (EltIdx == 4) {
4548     // Let the shuffle legalizer deal with blend operations.
4549     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4550     if (V1.getSimpleValueType() != VT)
4551       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4552     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4553   }
4554
4555   // See if we can lower this build_vector to a INSERTPS.
4556   if (!Subtarget->hasSSE41())
4557     return SDValue();
4558
4559   SDValue V2 = Elt.getOperand(0);
4560   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4561     V1 = SDValue();
4562
4563   bool CanFold = true;
4564   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4565     if (Zeroable[i])
4566       continue;
4567
4568     SDValue Current = Op->getOperand(i);
4569     SDValue SrcVector = Current->getOperand(0);
4570     if (!V1.getNode())
4571       V1 = SrcVector;
4572     CanFold = SrcVector == V1 &&
4573       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4574   }
4575
4576   if (!CanFold)
4577     return SDValue();
4578
4579   assert(V1.getNode() && "Expected at least two non-zero elements!");
4580   if (V1.getSimpleValueType() != MVT::v4f32)
4581     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4582   if (V2.getSimpleValueType() != MVT::v4f32)
4583     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4584
4585   // Ok, we can emit an INSERTPS instruction.
4586   unsigned ZMask = Zeroable.to_ulong();
4587
4588   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4589   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4590   SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
4591                                DAG.getIntPtrConstant(InsertPSMask));
4592   return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
4593 }
4594
4595 /// Return a vector logical shift node.
4596 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4597                          unsigned NumBits, SelectionDAG &DAG,
4598                          const TargetLowering &TLI, SDLoc dl) {
4599   assert(VT.is128BitVector() && "Unknown type for VShift");
4600   MVT ShVT = MVT::v2i64;
4601   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4602   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4603   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4604   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4605   SDValue ShiftVal = DAG.getConstant(NumBits/8, ScalarShiftTy);
4606   return DAG.getNode(ISD::BITCAST, dl, VT,
4607                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4608 }
4609
4610 static SDValue
4611 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4612
4613   // Check if the scalar load can be widened into a vector load. And if
4614   // the address is "base + cst" see if the cst can be "absorbed" into
4615   // the shuffle mask.
4616   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4617     SDValue Ptr = LD->getBasePtr();
4618     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4619       return SDValue();
4620     EVT PVT = LD->getValueType(0);
4621     if (PVT != MVT::i32 && PVT != MVT::f32)
4622       return SDValue();
4623
4624     int FI = -1;
4625     int64_t Offset = 0;
4626     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4627       FI = FINode->getIndex();
4628       Offset = 0;
4629     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4630                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4631       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4632       Offset = Ptr.getConstantOperandVal(1);
4633       Ptr = Ptr.getOperand(0);
4634     } else {
4635       return SDValue();
4636     }
4637
4638     // FIXME: 256-bit vector instructions don't require a strict alignment,
4639     // improve this code to support it better.
4640     unsigned RequiredAlign = VT.getSizeInBits()/8;
4641     SDValue Chain = LD->getChain();
4642     // Make sure the stack object alignment is at least 16 or 32.
4643     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4644     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4645       if (MFI->isFixedObjectIndex(FI)) {
4646         // Can't change the alignment. FIXME: It's possible to compute
4647         // the exact stack offset and reference FI + adjust offset instead.
4648         // If someone *really* cares about this. That's the way to implement it.
4649         return SDValue();
4650       } else {
4651         MFI->setObjectAlignment(FI, RequiredAlign);
4652       }
4653     }
4654
4655     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4656     // Ptr + (Offset & ~15).
4657     if (Offset < 0)
4658       return SDValue();
4659     if ((Offset % RequiredAlign) & 3)
4660       return SDValue();
4661     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4662     if (StartOffset)
4663       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
4664                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4665
4666     int EltNo = (Offset - StartOffset) >> 2;
4667     unsigned NumElems = VT.getVectorNumElements();
4668
4669     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4670     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4671                              LD->getPointerInfo().getWithOffset(StartOffset),
4672                              false, false, false, 0);
4673
4674     SmallVector<int, 8> Mask(NumElems, EltNo);
4675
4676     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4677   }
4678
4679   return SDValue();
4680 }
4681
4682 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4683 /// elements can be replaced by a single large load which has the same value as
4684 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4685 ///
4686 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4687 ///
4688 /// FIXME: we'd also like to handle the case where the last elements are zero
4689 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4690 /// There's even a handy isZeroNode for that purpose.
4691 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4692                                         SDLoc &DL, SelectionDAG &DAG,
4693                                         bool isAfterLegalize) {
4694   unsigned NumElems = Elts.size();
4695
4696   LoadSDNode *LDBase = nullptr;
4697   unsigned LastLoadedElt = -1U;
4698
4699   // For each element in the initializer, see if we've found a load or an undef.
4700   // If we don't find an initial load element, or later load elements are
4701   // non-consecutive, bail out.
4702   for (unsigned i = 0; i < NumElems; ++i) {
4703     SDValue Elt = Elts[i];
4704     // Look through a bitcast.
4705     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4706       Elt = Elt.getOperand(0);
4707     if (!Elt.getNode() ||
4708         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4709       return SDValue();
4710     if (!LDBase) {
4711       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4712         return SDValue();
4713       LDBase = cast<LoadSDNode>(Elt.getNode());
4714       LastLoadedElt = i;
4715       continue;
4716     }
4717     if (Elt.getOpcode() == ISD::UNDEF)
4718       continue;
4719
4720     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4721     EVT LdVT = Elt.getValueType();
4722     // Each loaded element must be the correct fractional portion of the
4723     // requested vector load.
4724     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4725       return SDValue();
4726     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4727       return SDValue();
4728     LastLoadedElt = i;
4729   }
4730
4731   // If we have found an entire vector of loads and undefs, then return a large
4732   // load of the entire vector width starting at the base pointer.  If we found
4733   // consecutive loads for the low half, generate a vzext_load node.
4734   if (LastLoadedElt == NumElems - 1) {
4735     assert(LDBase && "Did not find base load for merging consecutive loads");
4736     EVT EltVT = LDBase->getValueType(0);
4737     // Ensure that the input vector size for the merged loads matches the
4738     // cumulative size of the input elements.
4739     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4740       return SDValue();
4741
4742     if (isAfterLegalize &&
4743         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4744       return SDValue();
4745
4746     SDValue NewLd = SDValue();
4747
4748     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4749                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4750                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4751                         LDBase->getAlignment());
4752
4753     if (LDBase->hasAnyUseOfValue(1)) {
4754       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4755                                      SDValue(LDBase, 1),
4756                                      SDValue(NewLd.getNode(), 1));
4757       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4758       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4759                              SDValue(NewLd.getNode(), 1));
4760     }
4761
4762     return NewLd;
4763   }
4764
4765   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4766   //of a v4i32 / v4f32. It's probably worth generalizing.
4767   EVT EltVT = VT.getVectorElementType();
4768   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4769       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4770     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4771     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4772     SDValue ResNode =
4773         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4774                                 LDBase->getPointerInfo(),
4775                                 LDBase->getAlignment(),
4776                                 false/*isVolatile*/, true/*ReadMem*/,
4777                                 false/*WriteMem*/);
4778
4779     // Make sure the newly-created LOAD is in the same position as LDBase in
4780     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4781     // update uses of LDBase's output chain to use the TokenFactor.
4782     if (LDBase->hasAnyUseOfValue(1)) {
4783       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4784                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4785       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4786       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4787                              SDValue(ResNode.getNode(), 1));
4788     }
4789
4790     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4791   }
4792   return SDValue();
4793 }
4794
4795 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4796 /// to generate a splat value for the following cases:
4797 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4798 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4799 /// a scalar load, or a constant.
4800 /// The VBROADCAST node is returned when a pattern is found,
4801 /// or SDValue() otherwise.
4802 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4803                                     SelectionDAG &DAG) {
4804   // VBROADCAST requires AVX.
4805   // TODO: Splats could be generated for non-AVX CPUs using SSE
4806   // instructions, but there's less potential gain for only 128-bit vectors.
4807   if (!Subtarget->hasAVX())
4808     return SDValue();
4809
4810   MVT VT = Op.getSimpleValueType();
4811   SDLoc dl(Op);
4812
4813   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4814          "Unsupported vector type for broadcast.");
4815
4816   SDValue Ld;
4817   bool ConstSplatVal;
4818
4819   switch (Op.getOpcode()) {
4820     default:
4821       // Unknown pattern found.
4822       return SDValue();
4823
4824     case ISD::BUILD_VECTOR: {
4825       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4826       BitVector UndefElements;
4827       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4828
4829       // We need a splat of a single value to use broadcast, and it doesn't
4830       // make any sense if the value is only in one element of the vector.
4831       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4832         return SDValue();
4833
4834       Ld = Splat;
4835       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4836                        Ld.getOpcode() == ISD::ConstantFP);
4837
4838       // Make sure that all of the users of a non-constant load are from the
4839       // BUILD_VECTOR node.
4840       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4841         return SDValue();
4842       break;
4843     }
4844
4845     case ISD::VECTOR_SHUFFLE: {
4846       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4847
4848       // Shuffles must have a splat mask where the first element is
4849       // broadcasted.
4850       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4851         return SDValue();
4852
4853       SDValue Sc = Op.getOperand(0);
4854       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4855           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4856
4857         if (!Subtarget->hasInt256())
4858           return SDValue();
4859
4860         // Use the register form of the broadcast instruction available on AVX2.
4861         if (VT.getSizeInBits() >= 256)
4862           Sc = Extract128BitVector(Sc, 0, DAG, dl);
4863         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4864       }
4865
4866       Ld = Sc.getOperand(0);
4867       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4868                        Ld.getOpcode() == ISD::ConstantFP);
4869
4870       // The scalar_to_vector node and the suspected
4871       // load node must have exactly one user.
4872       // Constants may have multiple users.
4873
4874       // AVX-512 has register version of the broadcast
4875       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4876         Ld.getValueType().getSizeInBits() >= 32;
4877       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
4878           !hasRegVer))
4879         return SDValue();
4880       break;
4881     }
4882   }
4883
4884   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4885   bool IsGE256 = (VT.getSizeInBits() >= 256);
4886
4887   // When optimizing for size, generate up to 5 extra bytes for a broadcast
4888   // instruction to save 8 or more bytes of constant pool data.
4889   // TODO: If multiple splats are generated to load the same constant,
4890   // it may be detrimental to overall size. There needs to be a way to detect
4891   // that condition to know if this is truly a size win.
4892   const Function *F = DAG.getMachineFunction().getFunction();
4893   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
4894
4895   // Handle broadcasting a single constant scalar from the constant pool
4896   // into a vector.
4897   // On Sandybridge (no AVX2), it is still better to load a constant vector
4898   // from the constant pool and not to broadcast it from a scalar.
4899   // But override that restriction when optimizing for size.
4900   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
4901   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
4902     EVT CVT = Ld.getValueType();
4903     assert(!CVT.isVector() && "Must not broadcast a vector type");
4904
4905     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
4906     // For size optimization, also splat v2f64 and v2i64, and for size opt
4907     // with AVX2, also splat i8 and i16.
4908     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
4909     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4910         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
4911       const Constant *C = nullptr;
4912       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
4913         C = CI->getConstantIntValue();
4914       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
4915         C = CF->getConstantFPValue();
4916
4917       assert(C && "Invalid constant type");
4918
4919       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4920       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
4921       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
4922       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
4923                        MachinePointerInfo::getConstantPool(),
4924                        false, false, false, Alignment);
4925
4926       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4927     }
4928   }
4929
4930   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
4931
4932   // Handle AVX2 in-register broadcasts.
4933   if (!IsLoad && Subtarget->hasInt256() &&
4934       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
4935     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4936
4937   // The scalar source must be a normal load.
4938   if (!IsLoad)
4939     return SDValue();
4940
4941   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4942       (Subtarget->hasVLX() && ScalarSize == 64))
4943     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4944
4945   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
4946   // double since there is no vbroadcastsd xmm
4947   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
4948     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
4949       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4950   }
4951
4952   // Unsupported broadcast.
4953   return SDValue();
4954 }
4955
4956 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
4957 /// underlying vector and index.
4958 ///
4959 /// Modifies \p ExtractedFromVec to the real vector and returns the real
4960 /// index.
4961 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
4962                                          SDValue ExtIdx) {
4963   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
4964   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
4965     return Idx;
4966
4967   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
4968   // lowered this:
4969   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
4970   // to:
4971   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
4972   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
4973   //                           undef)
4974   //                       Constant<0>)
4975   // In this case the vector is the extract_subvector expression and the index
4976   // is 2, as specified by the shuffle.
4977   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
4978   SDValue ShuffleVec = SVOp->getOperand(0);
4979   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
4980   assert(ShuffleVecVT.getVectorElementType() ==
4981          ExtractedFromVec.getSimpleValueType().getVectorElementType());
4982
4983   int ShuffleIdx = SVOp->getMaskElt(Idx);
4984   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
4985     ExtractedFromVec = ShuffleVec;
4986     return ShuffleIdx;
4987   }
4988   return Idx;
4989 }
4990
4991 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
4992   MVT VT = Op.getSimpleValueType();
4993
4994   // Skip if insert_vec_elt is not supported.
4995   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4996   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
4997     return SDValue();
4998
4999   SDLoc DL(Op);
5000   unsigned NumElems = Op.getNumOperands();
5001
5002   SDValue VecIn1;
5003   SDValue VecIn2;
5004   SmallVector<unsigned, 4> InsertIndices;
5005   SmallVector<int, 8> Mask(NumElems, -1);
5006
5007   for (unsigned i = 0; i != NumElems; ++i) {
5008     unsigned Opc = Op.getOperand(i).getOpcode();
5009
5010     if (Opc == ISD::UNDEF)
5011       continue;
5012
5013     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5014       // Quit if more than 1 elements need inserting.
5015       if (InsertIndices.size() > 1)
5016         return SDValue();
5017
5018       InsertIndices.push_back(i);
5019       continue;
5020     }
5021
5022     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5023     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5024     // Quit if non-constant index.
5025     if (!isa<ConstantSDNode>(ExtIdx))
5026       return SDValue();
5027     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5028
5029     // Quit if extracted from vector of different type.
5030     if (ExtractedFromVec.getValueType() != VT)
5031       return SDValue();
5032
5033     if (!VecIn1.getNode())
5034       VecIn1 = ExtractedFromVec;
5035     else if (VecIn1 != ExtractedFromVec) {
5036       if (!VecIn2.getNode())
5037         VecIn2 = ExtractedFromVec;
5038       else if (VecIn2 != ExtractedFromVec)
5039         // Quit if more than 2 vectors to shuffle
5040         return SDValue();
5041     }
5042
5043     if (ExtractedFromVec == VecIn1)
5044       Mask[i] = Idx;
5045     else if (ExtractedFromVec == VecIn2)
5046       Mask[i] = Idx + NumElems;
5047   }
5048
5049   if (!VecIn1.getNode())
5050     return SDValue();
5051
5052   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5053   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5054   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5055     unsigned Idx = InsertIndices[i];
5056     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5057                      DAG.getIntPtrConstant(Idx));
5058   }
5059
5060   return NV;
5061 }
5062
5063 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5064 SDValue
5065 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5066
5067   MVT VT = Op.getSimpleValueType();
5068   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5069          "Unexpected type in LowerBUILD_VECTORvXi1!");
5070
5071   SDLoc dl(Op);
5072   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5073     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5074     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5075     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5076   }
5077
5078   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5079     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5080     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5081     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5082   }
5083
5084   bool AllContants = true;
5085   uint64_t Immediate = 0;
5086   int NonConstIdx = -1;
5087   bool IsSplat = true;
5088   unsigned NumNonConsts = 0;
5089   unsigned NumConsts = 0;
5090   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5091     SDValue In = Op.getOperand(idx);
5092     if (In.getOpcode() == ISD::UNDEF)
5093       continue;
5094     if (!isa<ConstantSDNode>(In)) {
5095       AllContants = false;
5096       NonConstIdx = idx;
5097       NumNonConsts++;
5098     } else {
5099       NumConsts++;
5100       if (cast<ConstantSDNode>(In)->getZExtValue())
5101       Immediate |= (1ULL << idx);
5102     }
5103     if (In != Op.getOperand(0))
5104       IsSplat = false;
5105   }
5106
5107   if (AllContants) {
5108     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5109       DAG.getConstant(Immediate, MVT::i16));
5110     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5111                        DAG.getIntPtrConstant(0));
5112   }
5113
5114   if (NumNonConsts == 1 && NonConstIdx != 0) {
5115     SDValue DstVec;
5116     if (NumConsts) {
5117       SDValue VecAsImm = DAG.getConstant(Immediate,
5118                                          MVT::getIntegerVT(VT.getSizeInBits()));
5119       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5120     }
5121     else
5122       DstVec = DAG.getUNDEF(VT);
5123     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5124                        Op.getOperand(NonConstIdx),
5125                        DAG.getIntPtrConstant(NonConstIdx));
5126   }
5127   if (!IsSplat && (NonConstIdx != 0))
5128     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5129   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5130   SDValue Select;
5131   if (IsSplat)
5132     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5133                           DAG.getConstant(-1, SelectVT),
5134                           DAG.getConstant(0, SelectVT));
5135   else
5136     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5137                          DAG.getConstant((Immediate | 1), SelectVT),
5138                          DAG.getConstant(Immediate, SelectVT));
5139   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5140 }
5141
5142 /// \brief Return true if \p N implements a horizontal binop and return the
5143 /// operands for the horizontal binop into V0 and V1.
5144 ///
5145 /// This is a helper function of PerformBUILD_VECTORCombine.
5146 /// This function checks that the build_vector \p N in input implements a
5147 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5148 /// operation to match.
5149 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5150 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5151 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5152 /// arithmetic sub.
5153 ///
5154 /// This function only analyzes elements of \p N whose indices are
5155 /// in range [BaseIdx, LastIdx).
5156 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5157                               SelectionDAG &DAG,
5158                               unsigned BaseIdx, unsigned LastIdx,
5159                               SDValue &V0, SDValue &V1) {
5160   EVT VT = N->getValueType(0);
5161
5162   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5163   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5164          "Invalid Vector in input!");
5165
5166   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5167   bool CanFold = true;
5168   unsigned ExpectedVExtractIdx = BaseIdx;
5169   unsigned NumElts = LastIdx - BaseIdx;
5170   V0 = DAG.getUNDEF(VT);
5171   V1 = DAG.getUNDEF(VT);
5172
5173   // Check if N implements a horizontal binop.
5174   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5175     SDValue Op = N->getOperand(i + BaseIdx);
5176
5177     // Skip UNDEFs.
5178     if (Op->getOpcode() == ISD::UNDEF) {
5179       // Update the expected vector extract index.
5180       if (i * 2 == NumElts)
5181         ExpectedVExtractIdx = BaseIdx;
5182       ExpectedVExtractIdx += 2;
5183       continue;
5184     }
5185
5186     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5187
5188     if (!CanFold)
5189       break;
5190
5191     SDValue Op0 = Op.getOperand(0);
5192     SDValue Op1 = Op.getOperand(1);
5193
5194     // Try to match the following pattern:
5195     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5196     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5197         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5198         Op0.getOperand(0) == Op1.getOperand(0) &&
5199         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5200         isa<ConstantSDNode>(Op1.getOperand(1)));
5201     if (!CanFold)
5202       break;
5203
5204     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5205     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5206
5207     if (i * 2 < NumElts) {
5208       if (V0.getOpcode() == ISD::UNDEF)
5209         V0 = Op0.getOperand(0);
5210     } else {
5211       if (V1.getOpcode() == ISD::UNDEF)
5212         V1 = Op0.getOperand(0);
5213       if (i * 2 == NumElts)
5214         ExpectedVExtractIdx = BaseIdx;
5215     }
5216
5217     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5218     if (I0 == ExpectedVExtractIdx)
5219       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5220     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5221       // Try to match the following dag sequence:
5222       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5223       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5224     } else
5225       CanFold = false;
5226
5227     ExpectedVExtractIdx += 2;
5228   }
5229
5230   return CanFold;
5231 }
5232
5233 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5234 /// a concat_vector.
5235 ///
5236 /// This is a helper function of PerformBUILD_VECTORCombine.
5237 /// This function expects two 256-bit vectors called V0 and V1.
5238 /// At first, each vector is split into two separate 128-bit vectors.
5239 /// Then, the resulting 128-bit vectors are used to implement two
5240 /// horizontal binary operations.
5241 ///
5242 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5243 ///
5244 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5245 /// the two new horizontal binop.
5246 /// When Mode is set, the first horizontal binop dag node would take as input
5247 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5248 /// horizontal binop dag node would take as input the lower 128-bit of V1
5249 /// and the upper 128-bit of V1.
5250 ///   Example:
5251 ///     HADD V0_LO, V0_HI
5252 ///     HADD V1_LO, V1_HI
5253 ///
5254 /// Otherwise, the first horizontal binop dag node takes as input the lower
5255 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5256 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5257 ///   Example:
5258 ///     HADD V0_LO, V1_LO
5259 ///     HADD V0_HI, V1_HI
5260 ///
5261 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5262 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5263 /// the upper 128-bits of the result.
5264 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5265                                      SDLoc DL, SelectionDAG &DAG,
5266                                      unsigned X86Opcode, bool Mode,
5267                                      bool isUndefLO, bool isUndefHI) {
5268   EVT VT = V0.getValueType();
5269   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5270          "Invalid nodes in input!");
5271
5272   unsigned NumElts = VT.getVectorNumElements();
5273   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5274   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5275   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5276   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5277   EVT NewVT = V0_LO.getValueType();
5278
5279   SDValue LO = DAG.getUNDEF(NewVT);
5280   SDValue HI = DAG.getUNDEF(NewVT);
5281
5282   if (Mode) {
5283     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5284     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5285       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5286     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5287       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5288   } else {
5289     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5290     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5291                        V1_LO->getOpcode() != ISD::UNDEF))
5292       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5293
5294     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5295                        V1_HI->getOpcode() != ISD::UNDEF))
5296       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5297   }
5298
5299   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5300 }
5301
5302 /// \brief Try to fold a build_vector that performs an 'addsub' into the
5303 /// sequence of 'vadd + vsub + blendi'.
5304 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
5305                            const X86Subtarget *Subtarget) {
5306   SDLoc DL(BV);
5307   EVT VT = BV->getValueType(0);
5308   unsigned NumElts = VT.getVectorNumElements();
5309   SDValue InVec0 = DAG.getUNDEF(VT);
5310   SDValue InVec1 = DAG.getUNDEF(VT);
5311
5312   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5313           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5314
5315   // Odd-numbered elements in the input build vector are obtained from
5316   // adding two integer/float elements.
5317   // Even-numbered elements in the input build vector are obtained from
5318   // subtracting two integer/float elements.
5319   unsigned ExpectedOpcode = ISD::FSUB;
5320   unsigned NextExpectedOpcode = ISD::FADD;
5321   bool AddFound = false;
5322   bool SubFound = false;
5323
5324   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5325     SDValue Op = BV->getOperand(i);
5326
5327     // Skip 'undef' values.
5328     unsigned Opcode = Op.getOpcode();
5329     if (Opcode == ISD::UNDEF) {
5330       std::swap(ExpectedOpcode, NextExpectedOpcode);
5331       continue;
5332     }
5333
5334     // Early exit if we found an unexpected opcode.
5335     if (Opcode != ExpectedOpcode)
5336       return SDValue();
5337
5338     SDValue Op0 = Op.getOperand(0);
5339     SDValue Op1 = Op.getOperand(1);
5340
5341     // Try to match the following pattern:
5342     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5343     // Early exit if we cannot match that sequence.
5344     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5345         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5346         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5347         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5348         Op0.getOperand(1) != Op1.getOperand(1))
5349       return SDValue();
5350
5351     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5352     if (I0 != i)
5353       return SDValue();
5354
5355     // We found a valid add/sub node. Update the information accordingly.
5356     if (i & 1)
5357       AddFound = true;
5358     else
5359       SubFound = true;
5360
5361     // Update InVec0 and InVec1.
5362     if (InVec0.getOpcode() == ISD::UNDEF)
5363       InVec0 = Op0.getOperand(0);
5364     if (InVec1.getOpcode() == ISD::UNDEF)
5365       InVec1 = Op1.getOperand(0);
5366
5367     // Make sure that operands in input to each add/sub node always
5368     // come from a same pair of vectors.
5369     if (InVec0 != Op0.getOperand(0)) {
5370       if (ExpectedOpcode == ISD::FSUB)
5371         return SDValue();
5372
5373       // FADD is commutable. Try to commute the operands
5374       // and then test again.
5375       std::swap(Op0, Op1);
5376       if (InVec0 != Op0.getOperand(0))
5377         return SDValue();
5378     }
5379
5380     if (InVec1 != Op1.getOperand(0))
5381       return SDValue();
5382
5383     // Update the pair of expected opcodes.
5384     std::swap(ExpectedOpcode, NextExpectedOpcode);
5385   }
5386
5387   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5388   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5389       InVec1.getOpcode() != ISD::UNDEF)
5390     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5391
5392   return SDValue();
5393 }
5394
5395 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
5396                                           const X86Subtarget *Subtarget) {
5397   SDLoc DL(N);
5398   EVT VT = N->getValueType(0);
5399   unsigned NumElts = VT.getVectorNumElements();
5400   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
5401   SDValue InVec0, InVec1;
5402
5403   // Try to match an ADDSUB.
5404   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
5405       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
5406     SDValue Value = matchAddSub(BV, DAG, Subtarget);
5407     if (Value.getNode())
5408       return Value;
5409   }
5410
5411   // Try to match horizontal ADD/SUB.
5412   unsigned NumUndefsLO = 0;
5413   unsigned NumUndefsHI = 0;
5414   unsigned Half = NumElts/2;
5415
5416   // Count the number of UNDEF operands in the build_vector in input.
5417   for (unsigned i = 0, e = Half; i != e; ++i)
5418     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5419       NumUndefsLO++;
5420
5421   for (unsigned i = Half, e = NumElts; i != e; ++i)
5422     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5423       NumUndefsHI++;
5424
5425   // Early exit if this is either a build_vector of all UNDEFs or all the
5426   // operands but one are UNDEF.
5427   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5428     return SDValue();
5429
5430   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5431     // Try to match an SSE3 float HADD/HSUB.
5432     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5433       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5434
5435     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5436       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5437   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5438     // Try to match an SSSE3 integer HADD/HSUB.
5439     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5440       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5441
5442     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5443       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5444   }
5445
5446   if (!Subtarget->hasAVX())
5447     return SDValue();
5448
5449   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5450     // Try to match an AVX horizontal add/sub of packed single/double
5451     // precision floating point values from 256-bit vectors.
5452     SDValue InVec2, InVec3;
5453     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5454         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5455         ((InVec0.getOpcode() == ISD::UNDEF ||
5456           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5457         ((InVec1.getOpcode() == ISD::UNDEF ||
5458           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5459       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5460
5461     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5462         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5463         ((InVec0.getOpcode() == ISD::UNDEF ||
5464           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5465         ((InVec1.getOpcode() == ISD::UNDEF ||
5466           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5467       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5468   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5469     // Try to match an AVX2 horizontal add/sub of signed integers.
5470     SDValue InVec2, InVec3;
5471     unsigned X86Opcode;
5472     bool CanFold = true;
5473
5474     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5475         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5476         ((InVec0.getOpcode() == ISD::UNDEF ||
5477           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5478         ((InVec1.getOpcode() == ISD::UNDEF ||
5479           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5480       X86Opcode = X86ISD::HADD;
5481     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5482         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5483         ((InVec0.getOpcode() == ISD::UNDEF ||
5484           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5485         ((InVec1.getOpcode() == ISD::UNDEF ||
5486           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5487       X86Opcode = X86ISD::HSUB;
5488     else
5489       CanFold = false;
5490
5491     if (CanFold) {
5492       // Fold this build_vector into a single horizontal add/sub.
5493       // Do this only if the target has AVX2.
5494       if (Subtarget->hasAVX2())
5495         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5496
5497       // Do not try to expand this build_vector into a pair of horizontal
5498       // add/sub if we can emit a pair of scalar add/sub.
5499       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5500         return SDValue();
5501
5502       // Convert this build_vector into a pair of horizontal binop followed by
5503       // a concat vector.
5504       bool isUndefLO = NumUndefsLO == Half;
5505       bool isUndefHI = NumUndefsHI == Half;
5506       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5507                                    isUndefLO, isUndefHI);
5508     }
5509   }
5510
5511   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5512        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5513     unsigned X86Opcode;
5514     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5515       X86Opcode = X86ISD::HADD;
5516     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5517       X86Opcode = X86ISD::HSUB;
5518     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5519       X86Opcode = X86ISD::FHADD;
5520     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5521       X86Opcode = X86ISD::FHSUB;
5522     else
5523       return SDValue();
5524
5525     // Don't try to expand this build_vector into a pair of horizontal add/sub
5526     // if we can simply emit a pair of scalar add/sub.
5527     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5528       return SDValue();
5529
5530     // Convert this build_vector into two horizontal add/sub followed by
5531     // a concat vector.
5532     bool isUndefLO = NumUndefsLO == Half;
5533     bool isUndefHI = NumUndefsHI == Half;
5534     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5535                                  isUndefLO, isUndefHI);
5536   }
5537
5538   return SDValue();
5539 }
5540
5541 SDValue
5542 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5543   SDLoc dl(Op);
5544
5545   MVT VT = Op.getSimpleValueType();
5546   MVT ExtVT = VT.getVectorElementType();
5547   unsigned NumElems = Op.getNumOperands();
5548
5549   // Generate vectors for predicate vectors.
5550   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5551     return LowerBUILD_VECTORvXi1(Op, DAG);
5552
5553   // Vectors containing all zeros can be matched by pxor and xorps later
5554   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5555     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5556     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5557     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5558       return Op;
5559
5560     return getZeroVector(VT, Subtarget, DAG, dl);
5561   }
5562
5563   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5564   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5565   // vpcmpeqd on 256-bit vectors.
5566   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5567     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5568       return Op;
5569
5570     if (!VT.is512BitVector())
5571       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5572   }
5573
5574   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5575     return Broadcast;
5576
5577   unsigned EVTBits = ExtVT.getSizeInBits();
5578
5579   unsigned NumZero  = 0;
5580   unsigned NumNonZero = 0;
5581   unsigned NonZeros = 0;
5582   bool IsAllConstants = true;
5583   SmallSet<SDValue, 8> Values;
5584   for (unsigned i = 0; i < NumElems; ++i) {
5585     SDValue Elt = Op.getOperand(i);
5586     if (Elt.getOpcode() == ISD::UNDEF)
5587       continue;
5588     Values.insert(Elt);
5589     if (Elt.getOpcode() != ISD::Constant &&
5590         Elt.getOpcode() != ISD::ConstantFP)
5591       IsAllConstants = false;
5592     if (X86::isZeroNode(Elt))
5593       NumZero++;
5594     else {
5595       NonZeros |= (1 << i);
5596       NumNonZero++;
5597     }
5598   }
5599
5600   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5601   if (NumNonZero == 0)
5602     return DAG.getUNDEF(VT);
5603
5604   // Special case for single non-zero, non-undef, element.
5605   if (NumNonZero == 1) {
5606     unsigned Idx = countTrailingZeros(NonZeros);
5607     SDValue Item = Op.getOperand(Idx);
5608
5609     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5610     // the value are obviously zero, truncate the value to i32 and do the
5611     // insertion that way.  Only do this if the value is non-constant or if the
5612     // value is a constant being inserted into element 0.  It is cheaper to do
5613     // a constant pool load than it is to do a movd + shuffle.
5614     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5615         (!IsAllConstants || Idx == 0)) {
5616       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5617         // Handle SSE only.
5618         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5619         EVT VecVT = MVT::v4i32;
5620
5621         // Truncate the value (which may itself be a constant) to i32, and
5622         // convert it to a vector with movd (S2V+shuffle to zero extend).
5623         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5624         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5625         return DAG.getNode(
5626             ISD::BITCAST, dl, VT,
5627             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5628       }
5629     }
5630
5631     // If we have a constant or non-constant insertion into the low element of
5632     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5633     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5634     // depending on what the source datatype is.
5635     if (Idx == 0) {
5636       if (NumZero == 0)
5637         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5638
5639       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5640           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5641         if (VT.is512BitVector()) {
5642           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5643           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5644                              Item, DAG.getIntPtrConstant(0));
5645         }
5646         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5647                "Expected an SSE value type!");
5648         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5649         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5650         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5651       }
5652
5653       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5654         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5655         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5656         if (VT.is256BitVector()) {
5657           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5658           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5659         } else {
5660           assert(VT.is128BitVector() && "Expected an SSE value type!");
5661           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5662         }
5663         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5664       }
5665     }
5666
5667     // Is it a vector logical left shift?
5668     if (NumElems == 2 && Idx == 1 &&
5669         X86::isZeroNode(Op.getOperand(0)) &&
5670         !X86::isZeroNode(Op.getOperand(1))) {
5671       unsigned NumBits = VT.getSizeInBits();
5672       return getVShift(true, VT,
5673                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5674                                    VT, Op.getOperand(1)),
5675                        NumBits/2, DAG, *this, dl);
5676     }
5677
5678     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5679       return SDValue();
5680
5681     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5682     // is a non-constant being inserted into an element other than the low one,
5683     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5684     // movd/movss) to move this into the low element, then shuffle it into
5685     // place.
5686     if (EVTBits == 32) {
5687       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5688       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5689     }
5690   }
5691
5692   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5693   if (Values.size() == 1) {
5694     if (EVTBits == 32) {
5695       // Instead of a shuffle like this:
5696       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5697       // Check if it's possible to issue this instead.
5698       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5699       unsigned Idx = countTrailingZeros(NonZeros);
5700       SDValue Item = Op.getOperand(Idx);
5701       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5702         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5703     }
5704     return SDValue();
5705   }
5706
5707   // A vector full of immediates; various special cases are already
5708   // handled, so this is best done with a single constant-pool load.
5709   if (IsAllConstants)
5710     return SDValue();
5711
5712   // For AVX-length vectors, see if we can use a vector load to get all of the
5713   // elements, otherwise build the individual 128-bit pieces and use
5714   // shuffles to put them in place.
5715   if (VT.is256BitVector() || VT.is512BitVector()) {
5716     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5717
5718     // Check for a build vector of consecutive loads.
5719     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5720       return LD;
5721
5722     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5723
5724     // Build both the lower and upper subvector.
5725     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5726                                 makeArrayRef(&V[0], NumElems/2));
5727     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5728                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5729
5730     // Recreate the wider vector with the lower and upper part.
5731     if (VT.is256BitVector())
5732       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5733     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5734   }
5735
5736   // Let legalizer expand 2-wide build_vectors.
5737   if (EVTBits == 64) {
5738     if (NumNonZero == 1) {
5739       // One half is zero or undef.
5740       unsigned Idx = countTrailingZeros(NonZeros);
5741       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5742                                  Op.getOperand(Idx));
5743       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5744     }
5745     return SDValue();
5746   }
5747
5748   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5749   if (EVTBits == 8 && NumElems == 16)
5750     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5751                                         Subtarget, *this))
5752       return V;
5753
5754   if (EVTBits == 16 && NumElems == 8)
5755     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5756                                       Subtarget, *this))
5757       return V;
5758
5759   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5760   if (EVTBits == 32 && NumElems == 4)
5761     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5762       return V;
5763
5764   // If element VT is == 32 bits, turn it into a number of shuffles.
5765   SmallVector<SDValue, 8> V(NumElems);
5766   if (NumElems == 4 && NumZero > 0) {
5767     for (unsigned i = 0; i < 4; ++i) {
5768       bool isZero = !(NonZeros & (1 << i));
5769       if (isZero)
5770         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5771       else
5772         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5773     }
5774
5775     for (unsigned i = 0; i < 2; ++i) {
5776       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5777         default: break;
5778         case 0:
5779           V[i] = V[i*2];  // Must be a zero vector.
5780           break;
5781         case 1:
5782           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5783           break;
5784         case 2:
5785           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5786           break;
5787         case 3:
5788           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5789           break;
5790       }
5791     }
5792
5793     bool Reverse1 = (NonZeros & 0x3) == 2;
5794     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5795     int MaskVec[] = {
5796       Reverse1 ? 1 : 0,
5797       Reverse1 ? 0 : 1,
5798       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5799       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5800     };
5801     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5802   }
5803
5804   if (Values.size() > 1 && VT.is128BitVector()) {
5805     // Check for a build vector of consecutive loads.
5806     for (unsigned i = 0; i < NumElems; ++i)
5807       V[i] = Op.getOperand(i);
5808
5809     // Check for elements which are consecutive loads.
5810     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5811       return LD;
5812
5813     // Check for a build vector from mostly shuffle plus few inserting.
5814     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
5815       return Sh;
5816
5817     // For SSE 4.1, use insertps to put the high elements into the low element.
5818     if (Subtarget->hasSSE41()) {
5819       SDValue Result;
5820       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5821         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5822       else
5823         Result = DAG.getUNDEF(VT);
5824
5825       for (unsigned i = 1; i < NumElems; ++i) {
5826         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5827         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5828                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5829       }
5830       return Result;
5831     }
5832
5833     // Otherwise, expand into a number of unpckl*, start by extending each of
5834     // our (non-undef) elements to the full vector width with the element in the
5835     // bottom slot of the vector (which generates no code for SSE).
5836     for (unsigned i = 0; i < NumElems; ++i) {
5837       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5838         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5839       else
5840         V[i] = DAG.getUNDEF(VT);
5841     }
5842
5843     // Next, we iteratively mix elements, e.g. for v4f32:
5844     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5845     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5846     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5847     unsigned EltStride = NumElems >> 1;
5848     while (EltStride != 0) {
5849       for (unsigned i = 0; i < EltStride; ++i) {
5850         // If V[i+EltStride] is undef and this is the first round of mixing,
5851         // then it is safe to just drop this shuffle: V[i] is already in the
5852         // right place, the one element (since it's the first round) being
5853         // inserted as undef can be dropped.  This isn't safe for successive
5854         // rounds because they will permute elements within both vectors.
5855         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5856             EltStride == NumElems/2)
5857           continue;
5858
5859         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5860       }
5861       EltStride >>= 1;
5862     }
5863     return V[0];
5864   }
5865   return SDValue();
5866 }
5867
5868 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5869 // to create 256-bit vectors from two other 128-bit ones.
5870 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5871   SDLoc dl(Op);
5872   MVT ResVT = Op.getSimpleValueType();
5873
5874   assert((ResVT.is256BitVector() ||
5875           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
5876
5877   SDValue V1 = Op.getOperand(0);
5878   SDValue V2 = Op.getOperand(1);
5879   unsigned NumElems = ResVT.getVectorNumElements();
5880   if(ResVT.is256BitVector())
5881     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5882
5883   if (Op.getNumOperands() == 4) {
5884     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5885                                 ResVT.getVectorNumElements()/2);
5886     SDValue V3 = Op.getOperand(2);
5887     SDValue V4 = Op.getOperand(3);
5888     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
5889       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
5890   }
5891   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5892 }
5893
5894 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
5895                                        const X86Subtarget *Subtarget,
5896                                        SelectionDAG & DAG) {
5897   SDLoc dl(Op);
5898   MVT ResVT = Op.getSimpleValueType();
5899   unsigned NumOfOperands = Op.getNumOperands();
5900
5901   assert(isPowerOf2_32(NumOfOperands) &&
5902          "Unexpected number of operands in CONCAT_VECTORS");
5903
5904   if (NumOfOperands > 2) {
5905     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5906                                   ResVT.getVectorNumElements()/2);
5907     SmallVector<SDValue, 2> Ops;
5908     for (unsigned i = 0; i < NumOfOperands/2; i++)
5909       Ops.push_back(Op.getOperand(i));
5910     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
5911     Ops.clear();
5912     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
5913       Ops.push_back(Op.getOperand(i));
5914     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
5915     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
5916   }
5917
5918   SDValue V1 = Op.getOperand(0);
5919   SDValue V2 = Op.getOperand(1);
5920   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
5921   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
5922
5923   if (IsZeroV1 && IsZeroV2)
5924     return getZeroVector(ResVT, Subtarget, DAG, dl);
5925
5926   SDValue ZeroIdx = DAG.getIntPtrConstant(0);
5927   SDValue Undef = DAG.getUNDEF(ResVT);
5928   unsigned NumElems = ResVT.getVectorNumElements();
5929   SDValue ShiftBits = DAG.getConstant(NumElems/2, MVT::i8);
5930
5931   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
5932   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
5933   if (IsZeroV1)
5934     return V2;
5935
5936   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
5937   // Zero the upper bits of V1
5938   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
5939   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
5940   if (IsZeroV2)
5941     return V1;
5942   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
5943 }
5944
5945 static SDValue LowerCONCAT_VECTORS(SDValue Op,
5946                                    const X86Subtarget *Subtarget,
5947                                    SelectionDAG &DAG) {
5948   MVT VT = Op.getSimpleValueType();
5949   if (VT.getVectorElementType() == MVT::i1)
5950     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
5951
5952   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
5953          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
5954           Op.getNumOperands() == 4)));
5955
5956   // AVX can use the vinsertf128 instruction to create 256-bit vectors
5957   // from two other 128-bit ones.
5958
5959   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
5960   return LowerAVXCONCAT_VECTORS(Op, DAG);
5961 }
5962
5963
5964 //===----------------------------------------------------------------------===//
5965 // Vector shuffle lowering
5966 //
5967 // This is an experimental code path for lowering vector shuffles on x86. It is
5968 // designed to handle arbitrary vector shuffles and blends, gracefully
5969 // degrading performance as necessary. It works hard to recognize idiomatic
5970 // shuffles and lower them to optimal instruction patterns without leaving
5971 // a framework that allows reasonably efficient handling of all vector shuffle
5972 // patterns.
5973 //===----------------------------------------------------------------------===//
5974
5975 /// \brief Tiny helper function to identify a no-op mask.
5976 ///
5977 /// This is a somewhat boring predicate function. It checks whether the mask
5978 /// array input, which is assumed to be a single-input shuffle mask of the kind
5979 /// used by the X86 shuffle instructions (not a fully general
5980 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
5981 /// in-place shuffle are 'no-op's.
5982 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
5983   for (int i = 0, Size = Mask.size(); i < Size; ++i)
5984     if (Mask[i] != -1 && Mask[i] != i)
5985       return false;
5986   return true;
5987 }
5988
5989 /// \brief Helper function to classify a mask as a single-input mask.
5990 ///
5991 /// This isn't a generic single-input test because in the vector shuffle
5992 /// lowering we canonicalize single inputs to be the first input operand. This
5993 /// means we can more quickly test for a single input by only checking whether
5994 /// an input from the second operand exists. We also assume that the size of
5995 /// mask corresponds to the size of the input vectors which isn't true in the
5996 /// fully general case.
5997 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
5998   for (int M : Mask)
5999     if (M >= (int)Mask.size())
6000       return false;
6001   return true;
6002 }
6003
6004 /// \brief Test whether there are elements crossing 128-bit lanes in this
6005 /// shuffle mask.
6006 ///
6007 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6008 /// and we routinely test for these.
6009 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6010   int LaneSize = 128 / VT.getScalarSizeInBits();
6011   int Size = Mask.size();
6012   for (int i = 0; i < Size; ++i)
6013     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6014       return true;
6015   return false;
6016 }
6017
6018 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6019 ///
6020 /// This checks a shuffle mask to see if it is performing the same
6021 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6022 /// that it is also not lane-crossing. It may however involve a blend from the
6023 /// same lane of a second vector.
6024 ///
6025 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6026 /// non-trivial to compute in the face of undef lanes. The representation is
6027 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6028 /// entries from both V1 and V2 inputs to the wider mask.
6029 static bool
6030 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6031                                 SmallVectorImpl<int> &RepeatedMask) {
6032   int LaneSize = 128 / VT.getScalarSizeInBits();
6033   RepeatedMask.resize(LaneSize, -1);
6034   int Size = Mask.size();
6035   for (int i = 0; i < Size; ++i) {
6036     if (Mask[i] < 0)
6037       continue;
6038     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6039       // This entry crosses lanes, so there is no way to model this shuffle.
6040       return false;
6041
6042     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6043     if (RepeatedMask[i % LaneSize] == -1)
6044       // This is the first non-undef entry in this slot of a 128-bit lane.
6045       RepeatedMask[i % LaneSize] =
6046           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6047     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6048       // Found a mismatch with the repeated mask.
6049       return false;
6050   }
6051   return true;
6052 }
6053
6054 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6055 /// arguments.
6056 ///
6057 /// This is a fast way to test a shuffle mask against a fixed pattern:
6058 ///
6059 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6060 ///
6061 /// It returns true if the mask is exactly as wide as the argument list, and
6062 /// each element of the mask is either -1 (signifying undef) or the value given
6063 /// in the argument.
6064 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6065                                 ArrayRef<int> ExpectedMask) {
6066   if (Mask.size() != ExpectedMask.size())
6067     return false;
6068
6069   int Size = Mask.size();
6070
6071   // If the values are build vectors, we can look through them to find
6072   // equivalent inputs that make the shuffles equivalent.
6073   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6074   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6075
6076   for (int i = 0; i < Size; ++i)
6077     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6078       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6079       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6080       if (!MaskBV || !ExpectedBV ||
6081           MaskBV->getOperand(Mask[i] % Size) !=
6082               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6083         return false;
6084     }
6085
6086   return true;
6087 }
6088
6089 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6090 ///
6091 /// This helper function produces an 8-bit shuffle immediate corresponding to
6092 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6093 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6094 /// example.
6095 ///
6096 /// NB: We rely heavily on "undef" masks preserving the input lane.
6097 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6098                                           SelectionDAG &DAG) {
6099   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6100   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6101   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6102   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6103   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6104
6105   unsigned Imm = 0;
6106   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6107   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6108   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6109   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6110   return DAG.getConstant(Imm, MVT::i8);
6111 }
6112
6113 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6114 ///
6115 /// This is used as a fallback approach when first class blend instructions are
6116 /// unavailable. Currently it is only suitable for integer vectors, but could
6117 /// be generalized for floating point vectors if desirable.
6118 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6119                                             SDValue V2, ArrayRef<int> Mask,
6120                                             SelectionDAG &DAG) {
6121   assert(VT.isInteger() && "Only supports integer vector types!");
6122   MVT EltVT = VT.getScalarType();
6123   int NumEltBits = EltVT.getSizeInBits();
6124   SDValue Zero = DAG.getConstant(0, EltVT);
6125   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), EltVT);
6126   SmallVector<SDValue, 16> MaskOps;
6127   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6128     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6129       return SDValue(); // Shuffled input!
6130     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6131   }
6132
6133   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6134   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6135   // We have to cast V2 around.
6136   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6137   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6138                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6139                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6140                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6141   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6142 }
6143
6144 /// \brief Try to emit a blend instruction for a shuffle.
6145 ///
6146 /// This doesn't do any checks for the availability of instructions for blending
6147 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6148 /// be matched in the backend with the type given. What it does check for is
6149 /// that the shuffle mask is in fact a blend.
6150 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6151                                          SDValue V2, ArrayRef<int> Mask,
6152                                          const X86Subtarget *Subtarget,
6153                                          SelectionDAG &DAG) {
6154   unsigned BlendMask = 0;
6155   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6156     if (Mask[i] >= Size) {
6157       if (Mask[i] != i + Size)
6158         return SDValue(); // Shuffled V2 input!
6159       BlendMask |= 1u << i;
6160       continue;
6161     }
6162     if (Mask[i] >= 0 && Mask[i] != i)
6163       return SDValue(); // Shuffled V1 input!
6164   }
6165   switch (VT.SimpleTy) {
6166   case MVT::v2f64:
6167   case MVT::v4f32:
6168   case MVT::v4f64:
6169   case MVT::v8f32:
6170     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6171                        DAG.getConstant(BlendMask, MVT::i8));
6172
6173   case MVT::v4i64:
6174   case MVT::v8i32:
6175     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6176     // FALLTHROUGH
6177   case MVT::v2i64:
6178   case MVT::v4i32:
6179     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6180     // that instruction.
6181     if (Subtarget->hasAVX2()) {
6182       // Scale the blend by the number of 32-bit dwords per element.
6183       int Scale =  VT.getScalarSizeInBits() / 32;
6184       BlendMask = 0;
6185       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6186         if (Mask[i] >= Size)
6187           for (int j = 0; j < Scale; ++j)
6188             BlendMask |= 1u << (i * Scale + j);
6189
6190       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6191       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6192       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6193       return DAG.getNode(ISD::BITCAST, DL, VT,
6194                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6195                                      DAG.getConstant(BlendMask, MVT::i8)));
6196     }
6197     // FALLTHROUGH
6198   case MVT::v8i16: {
6199     // For integer shuffles we need to expand the mask and cast the inputs to
6200     // v8i16s prior to blending.
6201     int Scale = 8 / VT.getVectorNumElements();
6202     BlendMask = 0;
6203     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6204       if (Mask[i] >= Size)
6205         for (int j = 0; j < Scale; ++j)
6206           BlendMask |= 1u << (i * Scale + j);
6207
6208     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6209     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6210     return DAG.getNode(ISD::BITCAST, DL, VT,
6211                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6212                                    DAG.getConstant(BlendMask, MVT::i8)));
6213   }
6214
6215   case MVT::v16i16: {
6216     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6217     SmallVector<int, 8> RepeatedMask;
6218     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6219       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6220       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6221       BlendMask = 0;
6222       for (int i = 0; i < 8; ++i)
6223         if (RepeatedMask[i] >= 16)
6224           BlendMask |= 1u << i;
6225       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6226                          DAG.getConstant(BlendMask, MVT::i8));
6227     }
6228   }
6229     // FALLTHROUGH
6230   case MVT::v16i8:
6231   case MVT::v32i8: {
6232     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6233            "256-bit byte-blends require AVX2 support!");
6234
6235     // Scale the blend by the number of bytes per element.
6236     int Scale = VT.getScalarSizeInBits() / 8;
6237
6238     // This form of blend is always done on bytes. Compute the byte vector
6239     // type.
6240     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6241
6242     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6243     // mix of LLVM's code generator and the x86 backend. We tell the code
6244     // generator that boolean values in the elements of an x86 vector register
6245     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6246     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6247     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6248     // of the element (the remaining are ignored) and 0 in that high bit would
6249     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6250     // the LLVM model for boolean values in vector elements gets the relevant
6251     // bit set, it is set backwards and over constrained relative to x86's
6252     // actual model.
6253     SmallVector<SDValue, 32> VSELECTMask;
6254     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6255       for (int j = 0; j < Scale; ++j)
6256         VSELECTMask.push_back(
6257             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6258                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8));
6259
6260     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6261     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6262     return DAG.getNode(
6263         ISD::BITCAST, DL, VT,
6264         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6265                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6266                     V1, V2));
6267   }
6268
6269   default:
6270     llvm_unreachable("Not a supported integer vector type!");
6271   }
6272 }
6273
6274 /// \brief Try to lower as a blend of elements from two inputs followed by
6275 /// a single-input permutation.
6276 ///
6277 /// This matches the pattern where we can blend elements from two inputs and
6278 /// then reduce the shuffle to a single-input permutation.
6279 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6280                                                    SDValue V2,
6281                                                    ArrayRef<int> Mask,
6282                                                    SelectionDAG &DAG) {
6283   // We build up the blend mask while checking whether a blend is a viable way
6284   // to reduce the shuffle.
6285   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6286   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6287
6288   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6289     if (Mask[i] < 0)
6290       continue;
6291
6292     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6293
6294     if (BlendMask[Mask[i] % Size] == -1)
6295       BlendMask[Mask[i] % Size] = Mask[i];
6296     else if (BlendMask[Mask[i] % Size] != Mask[i])
6297       return SDValue(); // Can't blend in the needed input!
6298
6299     PermuteMask[i] = Mask[i] % Size;
6300   }
6301
6302   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6303   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6304 }
6305
6306 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6307 /// blends and permutes.
6308 ///
6309 /// This matches the extremely common pattern for handling combined
6310 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6311 /// operations. It will try to pick the best arrangement of shuffles and
6312 /// blends.
6313 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6314                                                           SDValue V1,
6315                                                           SDValue V2,
6316                                                           ArrayRef<int> Mask,
6317                                                           SelectionDAG &DAG) {
6318   // Shuffle the input elements into the desired positions in V1 and V2 and
6319   // blend them together.
6320   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6321   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6322   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6323   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6324     if (Mask[i] >= 0 && Mask[i] < Size) {
6325       V1Mask[i] = Mask[i];
6326       BlendMask[i] = i;
6327     } else if (Mask[i] >= Size) {
6328       V2Mask[i] = Mask[i] - Size;
6329       BlendMask[i] = i + Size;
6330     }
6331
6332   // Try to lower with the simpler initial blend strategy unless one of the
6333   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6334   // shuffle may be able to fold with a load or other benefit. However, when
6335   // we'll have to do 2x as many shuffles in order to achieve this, blending
6336   // first is a better strategy.
6337   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6338     if (SDValue BlendPerm =
6339             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6340       return BlendPerm;
6341
6342   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6343   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6344   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6345 }
6346
6347 /// \brief Try to lower a vector shuffle as a byte rotation.
6348 ///
6349 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6350 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6351 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6352 /// try to generically lower a vector shuffle through such an pattern. It
6353 /// does not check for the profitability of lowering either as PALIGNR or
6354 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6355 /// This matches shuffle vectors that look like:
6356 ///
6357 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6358 ///
6359 /// Essentially it concatenates V1 and V2, shifts right by some number of
6360 /// elements, and takes the low elements as the result. Note that while this is
6361 /// specified as a *right shift* because x86 is little-endian, it is a *left
6362 /// rotate* of the vector lanes.
6363 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6364                                               SDValue V2,
6365                                               ArrayRef<int> Mask,
6366                                               const X86Subtarget *Subtarget,
6367                                               SelectionDAG &DAG) {
6368   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6369
6370   int NumElts = Mask.size();
6371   int NumLanes = VT.getSizeInBits() / 128;
6372   int NumLaneElts = NumElts / NumLanes;
6373
6374   // We need to detect various ways of spelling a rotation:
6375   //   [11, 12, 13, 14, 15,  0,  1,  2]
6376   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6377   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6378   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6379   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6380   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6381   int Rotation = 0;
6382   SDValue Lo, Hi;
6383   for (int l = 0; l < NumElts; l += NumLaneElts) {
6384     for (int i = 0; i < NumLaneElts; ++i) {
6385       if (Mask[l + i] == -1)
6386         continue;
6387       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6388
6389       // Get the mod-Size index and lane correct it.
6390       int LaneIdx = (Mask[l + i] % NumElts) - l;
6391       // Make sure it was in this lane.
6392       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6393         return SDValue();
6394
6395       // Determine where a rotated vector would have started.
6396       int StartIdx = i - LaneIdx;
6397       if (StartIdx == 0)
6398         // The identity rotation isn't interesting, stop.
6399         return SDValue();
6400
6401       // If we found the tail of a vector the rotation must be the missing
6402       // front. If we found the head of a vector, it must be how much of the
6403       // head.
6404       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6405
6406       if (Rotation == 0)
6407         Rotation = CandidateRotation;
6408       else if (Rotation != CandidateRotation)
6409         // The rotations don't match, so we can't match this mask.
6410         return SDValue();
6411
6412       // Compute which value this mask is pointing at.
6413       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6414
6415       // Compute which of the two target values this index should be assigned
6416       // to. This reflects whether the high elements are remaining or the low
6417       // elements are remaining.
6418       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6419
6420       // Either set up this value if we've not encountered it before, or check
6421       // that it remains consistent.
6422       if (!TargetV)
6423         TargetV = MaskV;
6424       else if (TargetV != MaskV)
6425         // This may be a rotation, but it pulls from the inputs in some
6426         // unsupported interleaving.
6427         return SDValue();
6428     }
6429   }
6430
6431   // Check that we successfully analyzed the mask, and normalize the results.
6432   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6433   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6434   if (!Lo)
6435     Lo = Hi;
6436   else if (!Hi)
6437     Hi = Lo;
6438
6439   // The actual rotate instruction rotates bytes, so we need to scale the
6440   // rotation based on how many bytes are in the vector lane.
6441   int Scale = 16 / NumLaneElts;
6442
6443   // SSSE3 targets can use the palignr instruction.
6444   if (Subtarget->hasSSSE3()) {
6445     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6446     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6447     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6448     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6449
6450     return DAG.getNode(ISD::BITCAST, DL, VT,
6451                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6452                                    DAG.getConstant(Rotation * Scale, MVT::i8)));
6453   }
6454
6455   assert(VT.getSizeInBits() == 128 &&
6456          "Rotate-based lowering only supports 128-bit lowering!");
6457   assert(Mask.size() <= 16 &&
6458          "Can shuffle at most 16 bytes in a 128-bit vector!");
6459
6460   // Default SSE2 implementation
6461   int LoByteShift = 16 - Rotation * Scale;
6462   int HiByteShift = Rotation * Scale;
6463
6464   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6465   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6466   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6467
6468   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6469                                 DAG.getConstant(LoByteShift, MVT::i8));
6470   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6471                                 DAG.getConstant(HiByteShift, MVT::i8));
6472   return DAG.getNode(ISD::BITCAST, DL, VT,
6473                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6474 }
6475
6476 /// \brief Compute whether each element of a shuffle is zeroable.
6477 ///
6478 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6479 /// Either it is an undef element in the shuffle mask, the element of the input
6480 /// referenced is undef, or the element of the input referenced is known to be
6481 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6482 /// as many lanes with this technique as possible to simplify the remaining
6483 /// shuffle.
6484 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6485                                                      SDValue V1, SDValue V2) {
6486   SmallBitVector Zeroable(Mask.size(), false);
6487
6488   while (V1.getOpcode() == ISD::BITCAST)
6489     V1 = V1->getOperand(0);
6490   while (V2.getOpcode() == ISD::BITCAST)
6491     V2 = V2->getOperand(0);
6492
6493   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6494   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6495
6496   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6497     int M = Mask[i];
6498     // Handle the easy cases.
6499     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6500       Zeroable[i] = true;
6501       continue;
6502     }
6503
6504     // If this is an index into a build_vector node (which has the same number
6505     // of elements), dig out the input value and use it.
6506     SDValue V = M < Size ? V1 : V2;
6507     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6508       continue;
6509
6510     SDValue Input = V.getOperand(M % Size);
6511     // The UNDEF opcode check really should be dead code here, but not quite
6512     // worth asserting on (it isn't invalid, just unexpected).
6513     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6514       Zeroable[i] = true;
6515   }
6516
6517   return Zeroable;
6518 }
6519
6520 /// \brief Try to emit a bitmask instruction for a shuffle.
6521 ///
6522 /// This handles cases where we can model a blend exactly as a bitmask due to
6523 /// one of the inputs being zeroable.
6524 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6525                                            SDValue V2, ArrayRef<int> Mask,
6526                                            SelectionDAG &DAG) {
6527   MVT EltVT = VT.getScalarType();
6528   int NumEltBits = EltVT.getSizeInBits();
6529   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6530   SDValue Zero = DAG.getConstant(0, IntEltVT);
6531   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), IntEltVT);
6532   if (EltVT.isFloatingPoint()) {
6533     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6534     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6535   }
6536   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6537   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6538   SDValue V;
6539   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6540     if (Zeroable[i])
6541       continue;
6542     if (Mask[i] % Size != i)
6543       return SDValue(); // Not a blend.
6544     if (!V)
6545       V = Mask[i] < Size ? V1 : V2;
6546     else if (V != (Mask[i] < Size ? V1 : V2))
6547       return SDValue(); // Can only let one input through the mask.
6548
6549     VMaskOps[i] = AllOnes;
6550   }
6551   if (!V)
6552     return SDValue(); // No non-zeroable elements!
6553
6554   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6555   V = DAG.getNode(VT.isFloatingPoint()
6556                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6557                   DL, VT, V, VMask);
6558   return V;
6559 }
6560
6561 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6562 ///
6563 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6564 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6565 /// matches elements from one of the input vectors shuffled to the left or
6566 /// right with zeroable elements 'shifted in'. It handles both the strictly
6567 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6568 /// quad word lane.
6569 ///
6570 /// PSHL : (little-endian) left bit shift.
6571 /// [ zz, 0, zz,  2 ]
6572 /// [ -1, 4, zz, -1 ]
6573 /// PSRL : (little-endian) right bit shift.
6574 /// [  1, zz,  3, zz]
6575 /// [ -1, -1,  7, zz]
6576 /// PSLLDQ : (little-endian) left byte shift
6577 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6578 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6579 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6580 /// PSRLDQ : (little-endian) right byte shift
6581 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6582 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6583 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6584 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6585                                          SDValue V2, ArrayRef<int> Mask,
6586                                          SelectionDAG &DAG) {
6587   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6588
6589   int Size = Mask.size();
6590   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6591
6592   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6593     for (int i = 0; i < Size; i += Scale)
6594       for (int j = 0; j < Shift; ++j)
6595         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6596           return false;
6597
6598     return true;
6599   };
6600
6601   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6602     for (int i = 0; i != Size; i += Scale) {
6603       unsigned Pos = Left ? i + Shift : i;
6604       unsigned Low = Left ? i : i + Shift;
6605       unsigned Len = Scale - Shift;
6606       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6607                                       Low + (V == V1 ? 0 : Size)))
6608         return SDValue();
6609     }
6610
6611     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6612     bool ByteShift = ShiftEltBits > 64;
6613     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6614                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6615     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6616
6617     // Normalize the scale for byte shifts to still produce an i64 element
6618     // type.
6619     Scale = ByteShift ? Scale / 2 : Scale;
6620
6621     // We need to round trip through the appropriate type for the shift.
6622     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6623     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6624     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6625            "Illegal integer vector type");
6626     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6627
6628     V = DAG.getNode(OpCode, DL, ShiftVT, V, DAG.getConstant(ShiftAmt, MVT::i8));
6629     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6630   };
6631
6632   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6633   // keep doubling the size of the integer elements up to that. We can
6634   // then shift the elements of the integer vector by whole multiples of
6635   // their width within the elements of the larger integer vector. Test each
6636   // multiple to see if we can find a match with the moved element indices
6637   // and that the shifted in elements are all zeroable.
6638   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6639     for (int Shift = 1; Shift != Scale; ++Shift)
6640       for (bool Left : {true, false})
6641         if (CheckZeros(Shift, Scale, Left))
6642           for (SDValue V : {V1, V2})
6643             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6644               return Match;
6645
6646   // no match
6647   return SDValue();
6648 }
6649
6650 /// \brief Lower a vector shuffle as a zero or any extension.
6651 ///
6652 /// Given a specific number of elements, element bit width, and extension
6653 /// stride, produce either a zero or any extension based on the available
6654 /// features of the subtarget.
6655 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6656     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6657     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6658   assert(Scale > 1 && "Need a scale to extend.");
6659   int NumElements = VT.getVectorNumElements();
6660   int EltBits = VT.getScalarSizeInBits();
6661   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6662          "Only 8, 16, and 32 bit elements can be extended.");
6663   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6664
6665   // Found a valid zext mask! Try various lowering strategies based on the
6666   // input type and available ISA extensions.
6667   if (Subtarget->hasSSE41()) {
6668     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6669                                  NumElements / Scale);
6670     return DAG.getNode(ISD::BITCAST, DL, VT,
6671                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6672   }
6673
6674   // For any extends we can cheat for larger element sizes and use shuffle
6675   // instructions that can fold with a load and/or copy.
6676   if (AnyExt && EltBits == 32) {
6677     int PSHUFDMask[4] = {0, -1, 1, -1};
6678     return DAG.getNode(
6679         ISD::BITCAST, DL, VT,
6680         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6681                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6682                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
6683   }
6684   if (AnyExt && EltBits == 16 && Scale > 2) {
6685     int PSHUFDMask[4] = {0, -1, 0, -1};
6686     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6687                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6688                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
6689     int PSHUFHWMask[4] = {1, -1, -1, -1};
6690     return DAG.getNode(
6691         ISD::BITCAST, DL, VT,
6692         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6693                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6694                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
6695   }
6696
6697   // If this would require more than 2 unpack instructions to expand, use
6698   // pshufb when available. We can only use more than 2 unpack instructions
6699   // when zero extending i8 elements which also makes it easier to use pshufb.
6700   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6701     assert(NumElements == 16 && "Unexpected byte vector width!");
6702     SDValue PSHUFBMask[16];
6703     for (int i = 0; i < 16; ++i)
6704       PSHUFBMask[i] =
6705           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
6706     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6707     return DAG.getNode(ISD::BITCAST, DL, VT,
6708                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6709                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6710                                                MVT::v16i8, PSHUFBMask)));
6711   }
6712
6713   // Otherwise emit a sequence of unpacks.
6714   do {
6715     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6716     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6717                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6718     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6719     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6720     Scale /= 2;
6721     EltBits *= 2;
6722     NumElements /= 2;
6723   } while (Scale > 1);
6724   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6725 }
6726
6727 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6728 ///
6729 /// This routine will try to do everything in its power to cleverly lower
6730 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6731 /// check for the profitability of this lowering,  it tries to aggressively
6732 /// match this pattern. It will use all of the micro-architectural details it
6733 /// can to emit an efficient lowering. It handles both blends with all-zero
6734 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6735 /// masking out later).
6736 ///
6737 /// The reason we have dedicated lowering for zext-style shuffles is that they
6738 /// are both incredibly common and often quite performance sensitive.
6739 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6740     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6741     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6742   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6743
6744   int Bits = VT.getSizeInBits();
6745   int NumElements = VT.getVectorNumElements();
6746   assert(VT.getScalarSizeInBits() <= 32 &&
6747          "Exceeds 32-bit integer zero extension limit");
6748   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6749
6750   // Define a helper function to check a particular ext-scale and lower to it if
6751   // valid.
6752   auto Lower = [&](int Scale) -> SDValue {
6753     SDValue InputV;
6754     bool AnyExt = true;
6755     for (int i = 0; i < NumElements; ++i) {
6756       if (Mask[i] == -1)
6757         continue; // Valid anywhere but doesn't tell us anything.
6758       if (i % Scale != 0) {
6759         // Each of the extended elements need to be zeroable.
6760         if (!Zeroable[i])
6761           return SDValue();
6762
6763         // We no longer are in the anyext case.
6764         AnyExt = false;
6765         continue;
6766       }
6767
6768       // Each of the base elements needs to be consecutive indices into the
6769       // same input vector.
6770       SDValue V = Mask[i] < NumElements ? V1 : V2;
6771       if (!InputV)
6772         InputV = V;
6773       else if (InputV != V)
6774         return SDValue(); // Flip-flopping inputs.
6775
6776       if (Mask[i] % NumElements != i / Scale)
6777         return SDValue(); // Non-consecutive strided elements.
6778     }
6779
6780     // If we fail to find an input, we have a zero-shuffle which should always
6781     // have already been handled.
6782     // FIXME: Maybe handle this here in case during blending we end up with one?
6783     if (!InputV)
6784       return SDValue();
6785
6786     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6787         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6788   };
6789
6790   // The widest scale possible for extending is to a 64-bit integer.
6791   assert(Bits % 64 == 0 &&
6792          "The number of bits in a vector must be divisible by 64 on x86!");
6793   int NumExtElements = Bits / 64;
6794
6795   // Each iteration, try extending the elements half as much, but into twice as
6796   // many elements.
6797   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6798     assert(NumElements % NumExtElements == 0 &&
6799            "The input vector size must be divisible by the extended size.");
6800     if (SDValue V = Lower(NumElements / NumExtElements))
6801       return V;
6802   }
6803
6804   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6805   if (Bits != 128)
6806     return SDValue();
6807
6808   // Returns one of the source operands if the shuffle can be reduced to a
6809   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6810   auto CanZExtLowHalf = [&]() {
6811     for (int i = NumElements / 2; i != NumElements; ++i)
6812       if (!Zeroable[i])
6813         return SDValue();
6814     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6815       return V1;
6816     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6817       return V2;
6818     return SDValue();
6819   };
6820
6821   if (SDValue V = CanZExtLowHalf()) {
6822     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6823     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6824     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6825   }
6826
6827   // No viable ext lowering found.
6828   return SDValue();
6829 }
6830
6831 /// \brief Try to get a scalar value for a specific element of a vector.
6832 ///
6833 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6834 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6835                                               SelectionDAG &DAG) {
6836   MVT VT = V.getSimpleValueType();
6837   MVT EltVT = VT.getVectorElementType();
6838   while (V.getOpcode() == ISD::BITCAST)
6839     V = V.getOperand(0);
6840   // If the bitcasts shift the element size, we can't extract an equivalent
6841   // element from it.
6842   MVT NewVT = V.getSimpleValueType();
6843   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6844     return SDValue();
6845
6846   if (V.getOpcode() == ISD::BUILD_VECTOR ||
6847       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
6848     return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
6849
6850   return SDValue();
6851 }
6852
6853 /// \brief Helper to test for a load that can be folded with x86 shuffles.
6854 ///
6855 /// This is particularly important because the set of instructions varies
6856 /// significantly based on whether the operand is a load or not.
6857 static bool isShuffleFoldableLoad(SDValue V) {
6858   while (V.getOpcode() == ISD::BITCAST)
6859     V = V.getOperand(0);
6860
6861   return ISD::isNON_EXTLoad(V.getNode());
6862 }
6863
6864 /// \brief Try to lower insertion of a single element into a zero vector.
6865 ///
6866 /// This is a common pattern that we have especially efficient patterns to lower
6867 /// across all subtarget feature sets.
6868 static SDValue lowerVectorShuffleAsElementInsertion(
6869     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6870     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6871   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6872   MVT ExtVT = VT;
6873   MVT EltVT = VT.getVectorElementType();
6874
6875   int V2Index = std::find_if(Mask.begin(), Mask.end(),
6876                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
6877                 Mask.begin();
6878   bool IsV1Zeroable = true;
6879   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6880     if (i != V2Index && !Zeroable[i]) {
6881       IsV1Zeroable = false;
6882       break;
6883     }
6884
6885   // Check for a single input from a SCALAR_TO_VECTOR node.
6886   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
6887   // all the smarts here sunk into that routine. However, the current
6888   // lowering of BUILD_VECTOR makes that nearly impossible until the old
6889   // vector shuffle lowering is dead.
6890   if (SDValue V2S = getScalarValueForVectorElement(
6891           V2, Mask[V2Index] - Mask.size(), DAG)) {
6892     // We need to zext the scalar if it is smaller than an i32.
6893     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
6894     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
6895       // Using zext to expand a narrow element won't work for non-zero
6896       // insertions.
6897       if (!IsV1Zeroable)
6898         return SDValue();
6899
6900       // Zero-extend directly to i32.
6901       ExtVT = MVT::v4i32;
6902       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
6903     }
6904     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
6905   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
6906              EltVT == MVT::i16) {
6907     // Either not inserting from the low element of the input or the input
6908     // element size is too small to use VZEXT_MOVL to clear the high bits.
6909     return SDValue();
6910   }
6911
6912   if (!IsV1Zeroable) {
6913     // If V1 can't be treated as a zero vector we have fewer options to lower
6914     // this. We can't support integer vectors or non-zero targets cheaply, and
6915     // the V1 elements can't be permuted in any way.
6916     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
6917     if (!VT.isFloatingPoint() || V2Index != 0)
6918       return SDValue();
6919     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
6920     V1Mask[V2Index] = -1;
6921     if (!isNoopShuffleMask(V1Mask))
6922       return SDValue();
6923     // This is essentially a special case blend operation, but if we have
6924     // general purpose blend operations, they are always faster. Bail and let
6925     // the rest of the lowering handle these as blends.
6926     if (Subtarget->hasSSE41())
6927       return SDValue();
6928
6929     // Otherwise, use MOVSD or MOVSS.
6930     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
6931            "Only two types of floating point element types to handle!");
6932     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
6933                        ExtVT, V1, V2);
6934   }
6935
6936   // This lowering only works for the low element with floating point vectors.
6937   if (VT.isFloatingPoint() && V2Index != 0)
6938     return SDValue();
6939
6940   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
6941   if (ExtVT != VT)
6942     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6943
6944   if (V2Index != 0) {
6945     // If we have 4 or fewer lanes we can cheaply shuffle the element into
6946     // the desired position. Otherwise it is more efficient to do a vector
6947     // shift left. We know that we can do a vector shift left because all
6948     // the inputs are zero.
6949     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
6950       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
6951       V2Shuffle[V2Index] = 0;
6952       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
6953     } else {
6954       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
6955       V2 = DAG.getNode(
6956           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
6957           DAG.getConstant(
6958               V2Index * EltVT.getSizeInBits()/8,
6959               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
6960       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6961     }
6962   }
6963   return V2;
6964 }
6965
6966 /// \brief Try to lower broadcast of a single element.
6967 ///
6968 /// For convenience, this code also bundles all of the subtarget feature set
6969 /// filtering. While a little annoying to re-dispatch on type here, there isn't
6970 /// a convenient way to factor it out.
6971 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
6972                                              ArrayRef<int> Mask,
6973                                              const X86Subtarget *Subtarget,
6974                                              SelectionDAG &DAG) {
6975   if (!Subtarget->hasAVX())
6976     return SDValue();
6977   if (VT.isInteger() && !Subtarget->hasAVX2())
6978     return SDValue();
6979
6980   // Check that the mask is a broadcast.
6981   int BroadcastIdx = -1;
6982   for (int M : Mask)
6983     if (M >= 0 && BroadcastIdx == -1)
6984       BroadcastIdx = M;
6985     else if (M >= 0 && M != BroadcastIdx)
6986       return SDValue();
6987
6988   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
6989                                             "a sorted mask where the broadcast "
6990                                             "comes from V1.");
6991
6992   // Go up the chain of (vector) values to find a scalar load that we can
6993   // combine with the broadcast.
6994   for (;;) {
6995     switch (V.getOpcode()) {
6996     case ISD::CONCAT_VECTORS: {
6997       int OperandSize = Mask.size() / V.getNumOperands();
6998       V = V.getOperand(BroadcastIdx / OperandSize);
6999       BroadcastIdx %= OperandSize;
7000       continue;
7001     }
7002
7003     case ISD::INSERT_SUBVECTOR: {
7004       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7005       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7006       if (!ConstantIdx)
7007         break;
7008
7009       int BeginIdx = (int)ConstantIdx->getZExtValue();
7010       int EndIdx =
7011           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7012       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7013         BroadcastIdx -= BeginIdx;
7014         V = VInner;
7015       } else {
7016         V = VOuter;
7017       }
7018       continue;
7019     }
7020     }
7021     break;
7022   }
7023
7024   // Check if this is a broadcast of a scalar. We special case lowering
7025   // for scalars so that we can more effectively fold with loads.
7026   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7027       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7028     V = V.getOperand(BroadcastIdx);
7029
7030     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7031     // Only AVX2 has register broadcasts.
7032     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7033       return SDValue();
7034   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7035     // We can't broadcast from a vector register without AVX2, and we can only
7036     // broadcast from the zero-element of a vector register.
7037     return SDValue();
7038   }
7039
7040   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7041 }
7042
7043 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7044 // INSERTPS when the V1 elements are already in the correct locations
7045 // because otherwise we can just always use two SHUFPS instructions which
7046 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7047 // perform INSERTPS if a single V1 element is out of place and all V2
7048 // elements are zeroable.
7049 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7050                                             ArrayRef<int> Mask,
7051                                             SelectionDAG &DAG) {
7052   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7053   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7054   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7055   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7056
7057   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7058
7059   unsigned ZMask = 0;
7060   int V1DstIndex = -1;
7061   int V2DstIndex = -1;
7062   bool V1UsedInPlace = false;
7063
7064   for (int i = 0; i < 4; ++i) {
7065     // Synthesize a zero mask from the zeroable elements (includes undefs).
7066     if (Zeroable[i]) {
7067       ZMask |= 1 << i;
7068       continue;
7069     }
7070
7071     // Flag if we use any V1 inputs in place.
7072     if (i == Mask[i]) {
7073       V1UsedInPlace = true;
7074       continue;
7075     }
7076
7077     // We can only insert a single non-zeroable element.
7078     if (V1DstIndex != -1 || V2DstIndex != -1)
7079       return SDValue();
7080
7081     if (Mask[i] < 4) {
7082       // V1 input out of place for insertion.
7083       V1DstIndex = i;
7084     } else {
7085       // V2 input for insertion.
7086       V2DstIndex = i;
7087     }
7088   }
7089
7090   // Don't bother if we have no (non-zeroable) element for insertion.
7091   if (V1DstIndex == -1 && V2DstIndex == -1)
7092     return SDValue();
7093
7094   // Determine element insertion src/dst indices. The src index is from the
7095   // start of the inserted vector, not the start of the concatenated vector.
7096   unsigned V2SrcIndex = 0;
7097   if (V1DstIndex != -1) {
7098     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7099     // and don't use the original V2 at all.
7100     V2SrcIndex = Mask[V1DstIndex];
7101     V2DstIndex = V1DstIndex;
7102     V2 = V1;
7103   } else {
7104     V2SrcIndex = Mask[V2DstIndex] - 4;
7105   }
7106
7107   // If no V1 inputs are used in place, then the result is created only from
7108   // the zero mask and the V2 insertion - so remove V1 dependency.
7109   if (!V1UsedInPlace)
7110     V1 = DAG.getUNDEF(MVT::v4f32);
7111
7112   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7113   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7114
7115   // Insert the V2 element into the desired position.
7116   SDLoc DL(Op);
7117   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7118                      DAG.getConstant(InsertPSMask, MVT::i8));
7119 }
7120
7121 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7122 /// UNPCK instruction.
7123 ///
7124 /// This specifically targets cases where we end up with alternating between
7125 /// the two inputs, and so can permute them into something that feeds a single
7126 /// UNPCK instruction. Note that this routine only targets integer vectors
7127 /// because for floating point vectors we have a generalized SHUFPS lowering
7128 /// strategy that handles everything that doesn't *exactly* match an unpack,
7129 /// making this clever lowering unnecessary.
7130 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7131                                           SDValue V2, ArrayRef<int> Mask,
7132                                           SelectionDAG &DAG) {
7133   assert(!VT.isFloatingPoint() &&
7134          "This routine only supports integer vectors.");
7135   assert(!isSingleInputShuffleMask(Mask) &&
7136          "This routine should only be used when blending two inputs.");
7137   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7138
7139   int Size = Mask.size();
7140
7141   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7142     return M >= 0 && M % Size < Size / 2;
7143   });
7144   int NumHiInputs = std::count_if(
7145       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7146
7147   bool UnpackLo = NumLoInputs >= NumHiInputs;
7148
7149   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7150     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7151     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7152
7153     for (int i = 0; i < Size; ++i) {
7154       if (Mask[i] < 0)
7155         continue;
7156
7157       // Each element of the unpack contains Scale elements from this mask.
7158       int UnpackIdx = i / Scale;
7159
7160       // We only handle the case where V1 feeds the first slots of the unpack.
7161       // We rely on canonicalization to ensure this is the case.
7162       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7163         return SDValue();
7164
7165       // Setup the mask for this input. The indexing is tricky as we have to
7166       // handle the unpack stride.
7167       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7168       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7169           Mask[i] % Size;
7170     }
7171
7172     // If we will have to shuffle both inputs to use the unpack, check whether
7173     // we can just unpack first and shuffle the result. If so, skip this unpack.
7174     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7175         !isNoopShuffleMask(V2Mask))
7176       return SDValue();
7177
7178     // Shuffle the inputs into place.
7179     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7180     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7181
7182     // Cast the inputs to the type we will use to unpack them.
7183     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7184     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7185
7186     // Unpack the inputs and cast the result back to the desired type.
7187     return DAG.getNode(ISD::BITCAST, DL, VT,
7188                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7189                                    DL, UnpackVT, V1, V2));
7190   };
7191
7192   // We try each unpack from the largest to the smallest to try and find one
7193   // that fits this mask.
7194   int OrigNumElements = VT.getVectorNumElements();
7195   int OrigScalarSize = VT.getScalarSizeInBits();
7196   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7197     int Scale = ScalarSize / OrigScalarSize;
7198     int NumElements = OrigNumElements / Scale;
7199     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7200     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7201       return Unpack;
7202   }
7203
7204   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7205   // initial unpack.
7206   if (NumLoInputs == 0 || NumHiInputs == 0) {
7207     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7208            "We have to have *some* inputs!");
7209     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7210
7211     // FIXME: We could consider the total complexity of the permute of each
7212     // possible unpacking. Or at the least we should consider how many
7213     // half-crossings are created.
7214     // FIXME: We could consider commuting the unpacks.
7215
7216     SmallVector<int, 32> PermMask;
7217     PermMask.assign(Size, -1);
7218     for (int i = 0; i < Size; ++i) {
7219       if (Mask[i] < 0)
7220         continue;
7221
7222       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7223
7224       PermMask[i] =
7225           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7226     }
7227     return DAG.getVectorShuffle(
7228         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7229                             DL, VT, V1, V2),
7230         DAG.getUNDEF(VT), PermMask);
7231   }
7232
7233   return SDValue();
7234 }
7235
7236 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7237 ///
7238 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7239 /// support for floating point shuffles but not integer shuffles. These
7240 /// instructions will incur a domain crossing penalty on some chips though so
7241 /// it is better to avoid lowering through this for integer vectors where
7242 /// possible.
7243 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7244                                        const X86Subtarget *Subtarget,
7245                                        SelectionDAG &DAG) {
7246   SDLoc DL(Op);
7247   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7248   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7249   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7250   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7251   ArrayRef<int> Mask = SVOp->getMask();
7252   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7253
7254   if (isSingleInputShuffleMask(Mask)) {
7255     // Use low duplicate instructions for masks that match their pattern.
7256     if (Subtarget->hasSSE3())
7257       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7258         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7259
7260     // Straight shuffle of a single input vector. Simulate this by using the
7261     // single input as both of the "inputs" to this instruction..
7262     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7263
7264     if (Subtarget->hasAVX()) {
7265       // If we have AVX, we can use VPERMILPS which will allow folding a load
7266       // into the shuffle.
7267       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7268                          DAG.getConstant(SHUFPDMask, MVT::i8));
7269     }
7270
7271     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7272                        DAG.getConstant(SHUFPDMask, MVT::i8));
7273   }
7274   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7275   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7276
7277   // If we have a single input, insert that into V1 if we can do so cheaply.
7278   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7279     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7280             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7281       return Insertion;
7282     // Try inverting the insertion since for v2 masks it is easy to do and we
7283     // can't reliably sort the mask one way or the other.
7284     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7285                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7286     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7287             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7288       return Insertion;
7289   }
7290
7291   // Try to use one of the special instruction patterns to handle two common
7292   // blend patterns if a zero-blend above didn't work.
7293   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7294       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7295     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7296       // We can either use a special instruction to load over the low double or
7297       // to move just the low double.
7298       return DAG.getNode(
7299           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7300           DL, MVT::v2f64, V2,
7301           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7302
7303   if (Subtarget->hasSSE41())
7304     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7305                                                   Subtarget, DAG))
7306       return Blend;
7307
7308   // Use dedicated unpack instructions for masks that match their pattern.
7309   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7310     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7311   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7312     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7313
7314   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7315   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7316                      DAG.getConstant(SHUFPDMask, MVT::i8));
7317 }
7318
7319 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7320 ///
7321 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7322 /// the integer unit to minimize domain crossing penalties. However, for blends
7323 /// it falls back to the floating point shuffle operation with appropriate bit
7324 /// casting.
7325 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7326                                        const X86Subtarget *Subtarget,
7327                                        SelectionDAG &DAG) {
7328   SDLoc DL(Op);
7329   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7330   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7331   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7332   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7333   ArrayRef<int> Mask = SVOp->getMask();
7334   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7335
7336   if (isSingleInputShuffleMask(Mask)) {
7337     // Check for being able to broadcast a single element.
7338     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7339                                                           Mask, Subtarget, DAG))
7340       return Broadcast;
7341
7342     // Straight shuffle of a single input vector. For everything from SSE2
7343     // onward this has a single fast instruction with no scary immediates.
7344     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7345     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7346     int WidenedMask[4] = {
7347         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7348         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7349     return DAG.getNode(
7350         ISD::BITCAST, DL, MVT::v2i64,
7351         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7352                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7353   }
7354   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7355   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7356   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7357   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7358
7359   // If we have a blend of two PACKUS operations an the blend aligns with the
7360   // low and half halves, we can just merge the PACKUS operations. This is
7361   // particularly important as it lets us merge shuffles that this routine itself
7362   // creates.
7363   auto GetPackNode = [](SDValue V) {
7364     while (V.getOpcode() == ISD::BITCAST)
7365       V = V.getOperand(0);
7366
7367     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7368   };
7369   if (SDValue V1Pack = GetPackNode(V1))
7370     if (SDValue V2Pack = GetPackNode(V2))
7371       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7372                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7373                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7374                                                   : V1Pack.getOperand(1),
7375                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7376                                                   : V2Pack.getOperand(1)));
7377
7378   // Try to use shift instructions.
7379   if (SDValue Shift =
7380           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7381     return Shift;
7382
7383   // When loading a scalar and then shuffling it into a vector we can often do
7384   // the insertion cheaply.
7385   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7386           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7387     return Insertion;
7388   // Try inverting the insertion since for v2 masks it is easy to do and we
7389   // can't reliably sort the mask one way or the other.
7390   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7391   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7392           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7393     return Insertion;
7394
7395   // We have different paths for blend lowering, but they all must use the
7396   // *exact* same predicate.
7397   bool IsBlendSupported = Subtarget->hasSSE41();
7398   if (IsBlendSupported)
7399     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7400                                                   Subtarget, DAG))
7401       return Blend;
7402
7403   // Use dedicated unpack instructions for masks that match their pattern.
7404   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7405     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7406   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7407     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7408
7409   // Try to use byte rotation instructions.
7410   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7411   if (Subtarget->hasSSSE3())
7412     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7413             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7414       return Rotate;
7415
7416   // If we have direct support for blends, we should lower by decomposing into
7417   // a permute. That will be faster than the domain cross.
7418   if (IsBlendSupported)
7419     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7420                                                       Mask, DAG);
7421
7422   // We implement this with SHUFPD which is pretty lame because it will likely
7423   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7424   // However, all the alternatives are still more cycles and newer chips don't
7425   // have this problem. It would be really nice if x86 had better shuffles here.
7426   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7427   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7428   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7429                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7430 }
7431
7432 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7433 ///
7434 /// This is used to disable more specialized lowerings when the shufps lowering
7435 /// will happen to be efficient.
7436 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7437   // This routine only handles 128-bit shufps.
7438   assert(Mask.size() == 4 && "Unsupported mask size!");
7439
7440   // To lower with a single SHUFPS we need to have the low half and high half
7441   // each requiring a single input.
7442   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7443     return false;
7444   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7445     return false;
7446
7447   return true;
7448 }
7449
7450 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7451 ///
7452 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7453 /// It makes no assumptions about whether this is the *best* lowering, it simply
7454 /// uses it.
7455 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7456                                             ArrayRef<int> Mask, SDValue V1,
7457                                             SDValue V2, SelectionDAG &DAG) {
7458   SDValue LowV = V1, HighV = V2;
7459   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7460
7461   int NumV2Elements =
7462       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7463
7464   if (NumV2Elements == 1) {
7465     int V2Index =
7466         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7467         Mask.begin();
7468
7469     // Compute the index adjacent to V2Index and in the same half by toggling
7470     // the low bit.
7471     int V2AdjIndex = V2Index ^ 1;
7472
7473     if (Mask[V2AdjIndex] == -1) {
7474       // Handles all the cases where we have a single V2 element and an undef.
7475       // This will only ever happen in the high lanes because we commute the
7476       // vector otherwise.
7477       if (V2Index < 2)
7478         std::swap(LowV, HighV);
7479       NewMask[V2Index] -= 4;
7480     } else {
7481       // Handle the case where the V2 element ends up adjacent to a V1 element.
7482       // To make this work, blend them together as the first step.
7483       int V1Index = V2AdjIndex;
7484       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7485       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7486                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7487
7488       // Now proceed to reconstruct the final blend as we have the necessary
7489       // high or low half formed.
7490       if (V2Index < 2) {
7491         LowV = V2;
7492         HighV = V1;
7493       } else {
7494         HighV = V2;
7495       }
7496       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7497       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7498     }
7499   } else if (NumV2Elements == 2) {
7500     if (Mask[0] < 4 && Mask[1] < 4) {
7501       // Handle the easy case where we have V1 in the low lanes and V2 in the
7502       // high lanes.
7503       NewMask[2] -= 4;
7504       NewMask[3] -= 4;
7505     } else if (Mask[2] < 4 && Mask[3] < 4) {
7506       // We also handle the reversed case because this utility may get called
7507       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7508       // arrange things in the right direction.
7509       NewMask[0] -= 4;
7510       NewMask[1] -= 4;
7511       HighV = V1;
7512       LowV = V2;
7513     } else {
7514       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7515       // trying to place elements directly, just blend them and set up the final
7516       // shuffle to place them.
7517
7518       // The first two blend mask elements are for V1, the second two are for
7519       // V2.
7520       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7521                           Mask[2] < 4 ? Mask[2] : Mask[3],
7522                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7523                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7524       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7525                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7526
7527       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7528       // a blend.
7529       LowV = HighV = V1;
7530       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7531       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7532       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7533       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7534     }
7535   }
7536   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7537                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7538 }
7539
7540 /// \brief Lower 4-lane 32-bit floating point shuffles.
7541 ///
7542 /// Uses instructions exclusively from the floating point unit to minimize
7543 /// domain crossing penalties, as these are sufficient to implement all v4f32
7544 /// shuffles.
7545 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7546                                        const X86Subtarget *Subtarget,
7547                                        SelectionDAG &DAG) {
7548   SDLoc DL(Op);
7549   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7550   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7551   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7552   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7553   ArrayRef<int> Mask = SVOp->getMask();
7554   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7555
7556   int NumV2Elements =
7557       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7558
7559   if (NumV2Elements == 0) {
7560     // Check for being able to broadcast a single element.
7561     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7562                                                           Mask, Subtarget, DAG))
7563       return Broadcast;
7564
7565     // Use even/odd duplicate instructions for masks that match their pattern.
7566     if (Subtarget->hasSSE3()) {
7567       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7568         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7569       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7570         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7571     }
7572
7573     if (Subtarget->hasAVX()) {
7574       // If we have AVX, we can use VPERMILPS which will allow folding a load
7575       // into the shuffle.
7576       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7577                          getV4X86ShuffleImm8ForMask(Mask, DAG));
7578     }
7579
7580     // Otherwise, use a straight shuffle of a single input vector. We pass the
7581     // input vector to both operands to simulate this with a SHUFPS.
7582     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7583                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7584   }
7585
7586   // There are special ways we can lower some single-element blends. However, we
7587   // have custom ways we can lower more complex single-element blends below that
7588   // we defer to if both this and BLENDPS fail to match, so restrict this to
7589   // when the V2 input is targeting element 0 of the mask -- that is the fast
7590   // case here.
7591   if (NumV2Elements == 1 && Mask[0] >= 4)
7592     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7593                                                          Mask, Subtarget, DAG))
7594       return V;
7595
7596   if (Subtarget->hasSSE41()) {
7597     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7598                                                   Subtarget, DAG))
7599       return Blend;
7600
7601     // Use INSERTPS if we can complete the shuffle efficiently.
7602     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7603       return V;
7604
7605     if (!isSingleSHUFPSMask(Mask))
7606       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7607               DL, MVT::v4f32, V1, V2, Mask, DAG))
7608         return BlendPerm;
7609   }
7610
7611   // Use dedicated unpack instructions for masks that match their pattern.
7612   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7613     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7614   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7615     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7616   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7617     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7618   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7619     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7620
7621   // Otherwise fall back to a SHUFPS lowering strategy.
7622   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7623 }
7624
7625 /// \brief Lower 4-lane i32 vector shuffles.
7626 ///
7627 /// We try to handle these with integer-domain shuffles where we can, but for
7628 /// blends we use the floating point domain blend instructions.
7629 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7630                                        const X86Subtarget *Subtarget,
7631                                        SelectionDAG &DAG) {
7632   SDLoc DL(Op);
7633   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7634   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7635   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7636   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7637   ArrayRef<int> Mask = SVOp->getMask();
7638   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7639
7640   // Whenever we can lower this as a zext, that instruction is strictly faster
7641   // than any alternative. It also allows us to fold memory operands into the
7642   // shuffle in many cases.
7643   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7644                                                          Mask, Subtarget, DAG))
7645     return ZExt;
7646
7647   int NumV2Elements =
7648       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7649
7650   if (NumV2Elements == 0) {
7651     // Check for being able to broadcast a single element.
7652     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7653                                                           Mask, Subtarget, DAG))
7654       return Broadcast;
7655
7656     // Straight shuffle of a single input vector. For everything from SSE2
7657     // onward this has a single fast instruction with no scary immediates.
7658     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7659     // but we aren't actually going to use the UNPCK instruction because doing
7660     // so prevents folding a load into this instruction or making a copy.
7661     const int UnpackLoMask[] = {0, 0, 1, 1};
7662     const int UnpackHiMask[] = {2, 2, 3, 3};
7663     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7664       Mask = UnpackLoMask;
7665     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7666       Mask = UnpackHiMask;
7667
7668     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7669                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7670   }
7671
7672   // Try to use shift instructions.
7673   if (SDValue Shift =
7674           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7675     return Shift;
7676
7677   // There are special ways we can lower some single-element blends.
7678   if (NumV2Elements == 1)
7679     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7680                                                          Mask, Subtarget, DAG))
7681       return V;
7682
7683   // We have different paths for blend lowering, but they all must use the
7684   // *exact* same predicate.
7685   bool IsBlendSupported = Subtarget->hasSSE41();
7686   if (IsBlendSupported)
7687     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7688                                                   Subtarget, DAG))
7689       return Blend;
7690
7691   if (SDValue Masked =
7692           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7693     return Masked;
7694
7695   // Use dedicated unpack instructions for masks that match their pattern.
7696   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7697     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7698   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7699     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7700   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7701     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7702   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7703     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7704
7705   // Try to use byte rotation instructions.
7706   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7707   if (Subtarget->hasSSSE3())
7708     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7709             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7710       return Rotate;
7711
7712   // If we have direct support for blends, we should lower by decomposing into
7713   // a permute. That will be faster than the domain cross.
7714   if (IsBlendSupported)
7715     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7716                                                       Mask, DAG);
7717
7718   // Try to lower by permuting the inputs into an unpack instruction.
7719   if (SDValue Unpack =
7720           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7721     return Unpack;
7722
7723   // We implement this with SHUFPS because it can blend from two vectors.
7724   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7725   // up the inputs, bypassing domain shift penalties that we would encur if we
7726   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7727   // relevant.
7728   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7729                      DAG.getVectorShuffle(
7730                          MVT::v4f32, DL,
7731                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7732                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7733 }
7734
7735 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7736 /// shuffle lowering, and the most complex part.
7737 ///
7738 /// The lowering strategy is to try to form pairs of input lanes which are
7739 /// targeted at the same half of the final vector, and then use a dword shuffle
7740 /// to place them onto the right half, and finally unpack the paired lanes into
7741 /// their final position.
7742 ///
7743 /// The exact breakdown of how to form these dword pairs and align them on the
7744 /// correct sides is really tricky. See the comments within the function for
7745 /// more of the details.
7746 ///
7747 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7748 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7749 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7750 /// vector, form the analogous 128-bit 8-element Mask.
7751 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7752     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7753     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7754   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7755   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7756
7757   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7758   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7759   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7760
7761   SmallVector<int, 4> LoInputs;
7762   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7763                [](int M) { return M >= 0; });
7764   std::sort(LoInputs.begin(), LoInputs.end());
7765   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7766   SmallVector<int, 4> HiInputs;
7767   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7768                [](int M) { return M >= 0; });
7769   std::sort(HiInputs.begin(), HiInputs.end());
7770   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7771   int NumLToL =
7772       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7773   int NumHToL = LoInputs.size() - NumLToL;
7774   int NumLToH =
7775       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7776   int NumHToH = HiInputs.size() - NumLToH;
7777   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7778   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7779   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7780   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7781
7782   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7783   // such inputs we can swap two of the dwords across the half mark and end up
7784   // with <=2 inputs to each half in each half. Once there, we can fall through
7785   // to the generic code below. For example:
7786   //
7787   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7788   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7789   //
7790   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7791   // and an existing 2-into-2 on the other half. In this case we may have to
7792   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7793   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7794   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7795   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7796   // half than the one we target for fixing) will be fixed when we re-enter this
7797   // path. We will also combine away any sequence of PSHUFD instructions that
7798   // result into a single instruction. Here is an example of the tricky case:
7799   //
7800   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7801   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7802   //
7803   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7804   //
7805   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7806   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7807   //
7808   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7809   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7810   //
7811   // The result is fine to be handled by the generic logic.
7812   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7813                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7814                           int AOffset, int BOffset) {
7815     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7816            "Must call this with A having 3 or 1 inputs from the A half.");
7817     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7818            "Must call this with B having 1 or 3 inputs from the B half.");
7819     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7820            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7821
7822     // Compute the index of dword with only one word among the three inputs in
7823     // a half by taking the sum of the half with three inputs and subtracting
7824     // the sum of the actual three inputs. The difference is the remaining
7825     // slot.
7826     int ADWord, BDWord;
7827     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7828     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7829     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7830     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7831     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7832     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7833     int TripleNonInputIdx =
7834         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7835     TripleDWord = TripleNonInputIdx / 2;
7836
7837     // We use xor with one to compute the adjacent DWord to whichever one the
7838     // OneInput is in.
7839     OneInputDWord = (OneInput / 2) ^ 1;
7840
7841     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7842     // and BToA inputs. If there is also such a problem with the BToB and AToB
7843     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7844     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7845     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7846     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7847       // Compute how many inputs will be flipped by swapping these DWords. We
7848       // need
7849       // to balance this to ensure we don't form a 3-1 shuffle in the other
7850       // half.
7851       int NumFlippedAToBInputs =
7852           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7853           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7854       int NumFlippedBToBInputs =
7855           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7856           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7857       if ((NumFlippedAToBInputs == 1 &&
7858            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7859           (NumFlippedBToBInputs == 1 &&
7860            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7861         // We choose whether to fix the A half or B half based on whether that
7862         // half has zero flipped inputs. At zero, we may not be able to fix it
7863         // with that half. We also bias towards fixing the B half because that
7864         // will more commonly be the high half, and we have to bias one way.
7865         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7866                                                        ArrayRef<int> Inputs) {
7867           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7868           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7869                                          PinnedIdx ^ 1) != Inputs.end();
7870           // Determine whether the free index is in the flipped dword or the
7871           // unflipped dword based on where the pinned index is. We use this bit
7872           // in an xor to conditionally select the adjacent dword.
7873           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7874           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7875                                              FixFreeIdx) != Inputs.end();
7876           if (IsFixIdxInput == IsFixFreeIdxInput)
7877             FixFreeIdx += 1;
7878           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7879                                         FixFreeIdx) != Inputs.end();
7880           assert(IsFixIdxInput != IsFixFreeIdxInput &&
7881                  "We need to be changing the number of flipped inputs!");
7882           int PSHUFHalfMask[] = {0, 1, 2, 3};
7883           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7884           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7885                           MVT::v8i16, V,
7886                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7887
7888           for (int &M : Mask)
7889             if (M != -1 && M == FixIdx)
7890               M = FixFreeIdx;
7891             else if (M != -1 && M == FixFreeIdx)
7892               M = FixIdx;
7893         };
7894         if (NumFlippedBToBInputs != 0) {
7895           int BPinnedIdx =
7896               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7897           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7898         } else {
7899           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7900           int APinnedIdx =
7901               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7902           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7903         }
7904       }
7905     }
7906
7907     int PSHUFDMask[] = {0, 1, 2, 3};
7908     PSHUFDMask[ADWord] = BDWord;
7909     PSHUFDMask[BDWord] = ADWord;
7910     V = DAG.getNode(ISD::BITCAST, DL, VT,
7911                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
7912                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
7913                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7914
7915     // Adjust the mask to match the new locations of A and B.
7916     for (int &M : Mask)
7917       if (M != -1 && M/2 == ADWord)
7918         M = 2 * BDWord + M % 2;
7919       else if (M != -1 && M/2 == BDWord)
7920         M = 2 * ADWord + M % 2;
7921
7922     // Recurse back into this routine to re-compute state now that this isn't
7923     // a 3 and 1 problem.
7924     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
7925                                                      DAG);
7926   };
7927   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7928     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7929   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7930     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7931
7932   // At this point there are at most two inputs to the low and high halves from
7933   // each half. That means the inputs can always be grouped into dwords and
7934   // those dwords can then be moved to the correct half with a dword shuffle.
7935   // We use at most one low and one high word shuffle to collect these paired
7936   // inputs into dwords, and finally a dword shuffle to place them.
7937   int PSHUFLMask[4] = {-1, -1, -1, -1};
7938   int PSHUFHMask[4] = {-1, -1, -1, -1};
7939   int PSHUFDMask[4] = {-1, -1, -1, -1};
7940
7941   // First fix the masks for all the inputs that are staying in their
7942   // original halves. This will then dictate the targets of the cross-half
7943   // shuffles.
7944   auto fixInPlaceInputs =
7945       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7946                     MutableArrayRef<int> SourceHalfMask,
7947                     MutableArrayRef<int> HalfMask, int HalfOffset) {
7948     if (InPlaceInputs.empty())
7949       return;
7950     if (InPlaceInputs.size() == 1) {
7951       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7952           InPlaceInputs[0] - HalfOffset;
7953       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7954       return;
7955     }
7956     if (IncomingInputs.empty()) {
7957       // Just fix all of the in place inputs.
7958       for (int Input : InPlaceInputs) {
7959         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7960         PSHUFDMask[Input / 2] = Input / 2;
7961       }
7962       return;
7963     }
7964
7965     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7966     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7967         InPlaceInputs[0] - HalfOffset;
7968     // Put the second input next to the first so that they are packed into
7969     // a dword. We find the adjacent index by toggling the low bit.
7970     int AdjIndex = InPlaceInputs[0] ^ 1;
7971     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7972     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7973     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7974   };
7975   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7976   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7977
7978   // Now gather the cross-half inputs and place them into a free dword of
7979   // their target half.
7980   // FIXME: This operation could almost certainly be simplified dramatically to
7981   // look more like the 3-1 fixing operation.
7982   auto moveInputsToRightHalf = [&PSHUFDMask](
7983       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7984       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7985       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7986       int DestOffset) {
7987     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7988       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7989     };
7990     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7991                                                int Word) {
7992       int LowWord = Word & ~1;
7993       int HighWord = Word | 1;
7994       return isWordClobbered(SourceHalfMask, LowWord) ||
7995              isWordClobbered(SourceHalfMask, HighWord);
7996     };
7997
7998     if (IncomingInputs.empty())
7999       return;
8000
8001     if (ExistingInputs.empty()) {
8002       // Map any dwords with inputs from them into the right half.
8003       for (int Input : IncomingInputs) {
8004         // If the source half mask maps over the inputs, turn those into
8005         // swaps and use the swapped lane.
8006         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8007           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8008             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8009                 Input - SourceOffset;
8010             // We have to swap the uses in our half mask in one sweep.
8011             for (int &M : HalfMask)
8012               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8013                 M = Input;
8014               else if (M == Input)
8015                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8016           } else {
8017             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8018                        Input - SourceOffset &&
8019                    "Previous placement doesn't match!");
8020           }
8021           // Note that this correctly re-maps both when we do a swap and when
8022           // we observe the other side of the swap above. We rely on that to
8023           // avoid swapping the members of the input list directly.
8024           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8025         }
8026
8027         // Map the input's dword into the correct half.
8028         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8029           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8030         else
8031           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8032                      Input / 2 &&
8033                  "Previous placement doesn't match!");
8034       }
8035
8036       // And just directly shift any other-half mask elements to be same-half
8037       // as we will have mirrored the dword containing the element into the
8038       // same position within that half.
8039       for (int &M : HalfMask)
8040         if (M >= SourceOffset && M < SourceOffset + 4) {
8041           M = M - SourceOffset + DestOffset;
8042           assert(M >= 0 && "This should never wrap below zero!");
8043         }
8044       return;
8045     }
8046
8047     // Ensure we have the input in a viable dword of its current half. This
8048     // is particularly tricky because the original position may be clobbered
8049     // by inputs being moved and *staying* in that half.
8050     if (IncomingInputs.size() == 1) {
8051       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8052         int InputFixed = std::find(std::begin(SourceHalfMask),
8053                                    std::end(SourceHalfMask), -1) -
8054                          std::begin(SourceHalfMask) + SourceOffset;
8055         SourceHalfMask[InputFixed - SourceOffset] =
8056             IncomingInputs[0] - SourceOffset;
8057         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8058                      InputFixed);
8059         IncomingInputs[0] = InputFixed;
8060       }
8061     } else if (IncomingInputs.size() == 2) {
8062       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8063           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8064         // We have two non-adjacent or clobbered inputs we need to extract from
8065         // the source half. To do this, we need to map them into some adjacent
8066         // dword slot in the source mask.
8067         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8068                               IncomingInputs[1] - SourceOffset};
8069
8070         // If there is a free slot in the source half mask adjacent to one of
8071         // the inputs, place the other input in it. We use (Index XOR 1) to
8072         // compute an adjacent index.
8073         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8074             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8075           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8076           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8077           InputsFixed[1] = InputsFixed[0] ^ 1;
8078         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8079                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8080           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8081           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8082           InputsFixed[0] = InputsFixed[1] ^ 1;
8083         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8084                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8085           // The two inputs are in the same DWord but it is clobbered and the
8086           // adjacent DWord isn't used at all. Move both inputs to the free
8087           // slot.
8088           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8089           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8090           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8091           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8092         } else {
8093           // The only way we hit this point is if there is no clobbering
8094           // (because there are no off-half inputs to this half) and there is no
8095           // free slot adjacent to one of the inputs. In this case, we have to
8096           // swap an input with a non-input.
8097           for (int i = 0; i < 4; ++i)
8098             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8099                    "We can't handle any clobbers here!");
8100           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8101                  "Cannot have adjacent inputs here!");
8102
8103           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8104           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8105
8106           // We also have to update the final source mask in this case because
8107           // it may need to undo the above swap.
8108           for (int &M : FinalSourceHalfMask)
8109             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8110               M = InputsFixed[1] + SourceOffset;
8111             else if (M == InputsFixed[1] + SourceOffset)
8112               M = (InputsFixed[0] ^ 1) + SourceOffset;
8113
8114           InputsFixed[1] = InputsFixed[0] ^ 1;
8115         }
8116
8117         // Point everything at the fixed inputs.
8118         for (int &M : HalfMask)
8119           if (M == IncomingInputs[0])
8120             M = InputsFixed[0] + SourceOffset;
8121           else if (M == IncomingInputs[1])
8122             M = InputsFixed[1] + SourceOffset;
8123
8124         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8125         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8126       }
8127     } else {
8128       llvm_unreachable("Unhandled input size!");
8129     }
8130
8131     // Now hoist the DWord down to the right half.
8132     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8133     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8134     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8135     for (int &M : HalfMask)
8136       for (int Input : IncomingInputs)
8137         if (M == Input)
8138           M = FreeDWord * 2 + Input % 2;
8139   };
8140   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8141                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8142   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8143                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8144
8145   // Now enact all the shuffles we've computed to move the inputs into their
8146   // target half.
8147   if (!isNoopShuffleMask(PSHUFLMask))
8148     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8149                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8150   if (!isNoopShuffleMask(PSHUFHMask))
8151     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8152                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8153   if (!isNoopShuffleMask(PSHUFDMask))
8154     V = DAG.getNode(ISD::BITCAST, DL, VT,
8155                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8156                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8157                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8158
8159   // At this point, each half should contain all its inputs, and we can then
8160   // just shuffle them into their final position.
8161   assert(std::count_if(LoMask.begin(), LoMask.end(),
8162                        [](int M) { return M >= 4; }) == 0 &&
8163          "Failed to lift all the high half inputs to the low mask!");
8164   assert(std::count_if(HiMask.begin(), HiMask.end(),
8165                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8166          "Failed to lift all the low half inputs to the high mask!");
8167
8168   // Do a half shuffle for the low mask.
8169   if (!isNoopShuffleMask(LoMask))
8170     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8171                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
8172
8173   // Do a half shuffle with the high mask after shifting its values down.
8174   for (int &M : HiMask)
8175     if (M >= 0)
8176       M -= 4;
8177   if (!isNoopShuffleMask(HiMask))
8178     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8179                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
8180
8181   return V;
8182 }
8183
8184 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8185 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8186                                           SDValue V2, ArrayRef<int> Mask,
8187                                           SelectionDAG &DAG, bool &V1InUse,
8188                                           bool &V2InUse) {
8189   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8190   SDValue V1Mask[16];
8191   SDValue V2Mask[16];
8192   V1InUse = false;
8193   V2InUse = false;
8194
8195   int Size = Mask.size();
8196   int Scale = 16 / Size;
8197   for (int i = 0; i < 16; ++i) {
8198     if (Mask[i / Scale] == -1) {
8199       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8200     } else {
8201       const int ZeroMask = 0x80;
8202       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8203                                           : ZeroMask;
8204       int V2Idx = Mask[i / Scale] < Size
8205                       ? ZeroMask
8206                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8207       if (Zeroable[i / Scale])
8208         V1Idx = V2Idx = ZeroMask;
8209       V1Mask[i] = DAG.getConstant(V1Idx, MVT::i8);
8210       V2Mask[i] = DAG.getConstant(V2Idx, MVT::i8);
8211       V1InUse |= (ZeroMask != V1Idx);
8212       V2InUse |= (ZeroMask != V2Idx);
8213     }
8214   }
8215
8216   if (V1InUse)
8217     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8218                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8219                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8220   if (V2InUse)
8221     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8222                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8223                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8224
8225   // If we need shuffled inputs from both, blend the two.
8226   SDValue V;
8227   if (V1InUse && V2InUse)
8228     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8229   else
8230     V = V1InUse ? V1 : V2;
8231
8232   // Cast the result back to the correct type.
8233   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8234 }
8235
8236 /// \brief Generic lowering of 8-lane i16 shuffles.
8237 ///
8238 /// This handles both single-input shuffles and combined shuffle/blends with
8239 /// two inputs. The single input shuffles are immediately delegated to
8240 /// a dedicated lowering routine.
8241 ///
8242 /// The blends are lowered in one of three fundamental ways. If there are few
8243 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8244 /// of the input is significantly cheaper when lowered as an interleaving of
8245 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8246 /// halves of the inputs separately (making them have relatively few inputs)
8247 /// and then concatenate them.
8248 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8249                                        const X86Subtarget *Subtarget,
8250                                        SelectionDAG &DAG) {
8251   SDLoc DL(Op);
8252   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8253   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8254   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8255   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8256   ArrayRef<int> OrigMask = SVOp->getMask();
8257   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8258                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8259   MutableArrayRef<int> Mask(MaskStorage);
8260
8261   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8262
8263   // Whenever we can lower this as a zext, that instruction is strictly faster
8264   // than any alternative.
8265   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8266           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8267     return ZExt;
8268
8269   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8270   (void)isV1;
8271   auto isV2 = [](int M) { return M >= 8; };
8272
8273   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8274
8275   if (NumV2Inputs == 0) {
8276     // Check for being able to broadcast a single element.
8277     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8278                                                           Mask, Subtarget, DAG))
8279       return Broadcast;
8280
8281     // Try to use shift instructions.
8282     if (SDValue Shift =
8283             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8284       return Shift;
8285
8286     // Use dedicated unpack instructions for masks that match their pattern.
8287     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8288       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8289     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8290       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8291
8292     // Try to use byte rotation instructions.
8293     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8294                                                         Mask, Subtarget, DAG))
8295       return Rotate;
8296
8297     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8298                                                      Subtarget, DAG);
8299   }
8300
8301   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8302          "All single-input shuffles should be canonicalized to be V1-input "
8303          "shuffles.");
8304
8305   // Try to use shift instructions.
8306   if (SDValue Shift =
8307           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8308     return Shift;
8309
8310   // There are special ways we can lower some single-element blends.
8311   if (NumV2Inputs == 1)
8312     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8313                                                          Mask, Subtarget, DAG))
8314       return V;
8315
8316   // We have different paths for blend lowering, but they all must use the
8317   // *exact* same predicate.
8318   bool IsBlendSupported = Subtarget->hasSSE41();
8319   if (IsBlendSupported)
8320     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8321                                                   Subtarget, DAG))
8322       return Blend;
8323
8324   if (SDValue Masked =
8325           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8326     return Masked;
8327
8328   // Use dedicated unpack instructions for masks that match their pattern.
8329   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8330     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8331   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8332     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8333
8334   // Try to use byte rotation instructions.
8335   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8336           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8337     return Rotate;
8338
8339   if (SDValue BitBlend =
8340           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8341     return BitBlend;
8342
8343   if (SDValue Unpack =
8344           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8345     return Unpack;
8346
8347   // If we can't directly blend but can use PSHUFB, that will be better as it
8348   // can both shuffle and set up the inefficient blend.
8349   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8350     bool V1InUse, V2InUse;
8351     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8352                                       V1InUse, V2InUse);
8353   }
8354
8355   // We can always bit-blend if we have to so the fallback strategy is to
8356   // decompose into single-input permutes and blends.
8357   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8358                                                       Mask, DAG);
8359 }
8360
8361 /// \brief Check whether a compaction lowering can be done by dropping even
8362 /// elements and compute how many times even elements must be dropped.
8363 ///
8364 /// This handles shuffles which take every Nth element where N is a power of
8365 /// two. Example shuffle masks:
8366 ///
8367 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8368 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8369 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8370 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8371 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8372 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8373 ///
8374 /// Any of these lanes can of course be undef.
8375 ///
8376 /// This routine only supports N <= 3.
8377 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8378 /// for larger N.
8379 ///
8380 /// \returns N above, or the number of times even elements must be dropped if
8381 /// there is such a number. Otherwise returns zero.
8382 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8383   // Figure out whether we're looping over two inputs or just one.
8384   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8385
8386   // The modulus for the shuffle vector entries is based on whether this is
8387   // a single input or not.
8388   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8389   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8390          "We should only be called with masks with a power-of-2 size!");
8391
8392   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8393
8394   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8395   // and 2^3 simultaneously. This is because we may have ambiguity with
8396   // partially undef inputs.
8397   bool ViableForN[3] = {true, true, true};
8398
8399   for (int i = 0, e = Mask.size(); i < e; ++i) {
8400     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8401     // want.
8402     if (Mask[i] == -1)
8403       continue;
8404
8405     bool IsAnyViable = false;
8406     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8407       if (ViableForN[j]) {
8408         uint64_t N = j + 1;
8409
8410         // The shuffle mask must be equal to (i * 2^N) % M.
8411         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8412           IsAnyViable = true;
8413         else
8414           ViableForN[j] = false;
8415       }
8416     // Early exit if we exhaust the possible powers of two.
8417     if (!IsAnyViable)
8418       break;
8419   }
8420
8421   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8422     if (ViableForN[j])
8423       return j + 1;
8424
8425   // Return 0 as there is no viable power of two.
8426   return 0;
8427 }
8428
8429 /// \brief Generic lowering of v16i8 shuffles.
8430 ///
8431 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8432 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8433 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8434 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8435 /// back together.
8436 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8437                                        const X86Subtarget *Subtarget,
8438                                        SelectionDAG &DAG) {
8439   SDLoc DL(Op);
8440   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8441   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8442   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8443   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8444   ArrayRef<int> Mask = SVOp->getMask();
8445   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8446
8447   // Try to use shift instructions.
8448   if (SDValue Shift =
8449           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8450     return Shift;
8451
8452   // Try to use byte rotation instructions.
8453   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8454           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8455     return Rotate;
8456
8457   // Try to use a zext lowering.
8458   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8459           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8460     return ZExt;
8461
8462   int NumV2Elements =
8463       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8464
8465   // For single-input shuffles, there are some nicer lowering tricks we can use.
8466   if (NumV2Elements == 0) {
8467     // Check for being able to broadcast a single element.
8468     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8469                                                           Mask, Subtarget, DAG))
8470       return Broadcast;
8471
8472     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8473     // Notably, this handles splat and partial-splat shuffles more efficiently.
8474     // However, it only makes sense if the pre-duplication shuffle simplifies
8475     // things significantly. Currently, this means we need to be able to
8476     // express the pre-duplication shuffle as an i16 shuffle.
8477     //
8478     // FIXME: We should check for other patterns which can be widened into an
8479     // i16 shuffle as well.
8480     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8481       for (int i = 0; i < 16; i += 2)
8482         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8483           return false;
8484
8485       return true;
8486     };
8487     auto tryToWidenViaDuplication = [&]() -> SDValue {
8488       if (!canWidenViaDuplication(Mask))
8489         return SDValue();
8490       SmallVector<int, 4> LoInputs;
8491       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8492                    [](int M) { return M >= 0 && M < 8; });
8493       std::sort(LoInputs.begin(), LoInputs.end());
8494       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8495                      LoInputs.end());
8496       SmallVector<int, 4> HiInputs;
8497       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8498                    [](int M) { return M >= 8; });
8499       std::sort(HiInputs.begin(), HiInputs.end());
8500       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8501                      HiInputs.end());
8502
8503       bool TargetLo = LoInputs.size() >= HiInputs.size();
8504       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8505       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8506
8507       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8508       SmallDenseMap<int, int, 8> LaneMap;
8509       for (int I : InPlaceInputs) {
8510         PreDupI16Shuffle[I/2] = I/2;
8511         LaneMap[I] = I;
8512       }
8513       int j = TargetLo ? 0 : 4, je = j + 4;
8514       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8515         // Check if j is already a shuffle of this input. This happens when
8516         // there are two adjacent bytes after we move the low one.
8517         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8518           // If we haven't yet mapped the input, search for a slot into which
8519           // we can map it.
8520           while (j < je && PreDupI16Shuffle[j] != -1)
8521             ++j;
8522
8523           if (j == je)
8524             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8525             return SDValue();
8526
8527           // Map this input with the i16 shuffle.
8528           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8529         }
8530
8531         // Update the lane map based on the mapping we ended up with.
8532         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8533       }
8534       V1 = DAG.getNode(
8535           ISD::BITCAST, DL, MVT::v16i8,
8536           DAG.getVectorShuffle(MVT::v8i16, DL,
8537                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8538                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8539
8540       // Unpack the bytes to form the i16s that will be shuffled into place.
8541       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8542                        MVT::v16i8, V1, V1);
8543
8544       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8545       for (int i = 0; i < 16; ++i)
8546         if (Mask[i] != -1) {
8547           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8548           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8549           if (PostDupI16Shuffle[i / 2] == -1)
8550             PostDupI16Shuffle[i / 2] = MappedMask;
8551           else
8552             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8553                    "Conflicting entrties in the original shuffle!");
8554         }
8555       return DAG.getNode(
8556           ISD::BITCAST, DL, MVT::v16i8,
8557           DAG.getVectorShuffle(MVT::v8i16, DL,
8558                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8559                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8560     };
8561     if (SDValue V = tryToWidenViaDuplication())
8562       return V;
8563   }
8564
8565   // Use dedicated unpack instructions for masks that match their pattern.
8566   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8567                                          0, 16, 1, 17, 2, 18, 3, 19,
8568                                          // High half.
8569                                          4, 20, 5, 21, 6, 22, 7, 23}))
8570     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8571   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8572                                          8, 24, 9, 25, 10, 26, 11, 27,
8573                                          // High half.
8574                                          12, 28, 13, 29, 14, 30, 15, 31}))
8575     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8576
8577   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8578   // with PSHUFB. It is important to do this before we attempt to generate any
8579   // blends but after all of the single-input lowerings. If the single input
8580   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8581   // want to preserve that and we can DAG combine any longer sequences into
8582   // a PSHUFB in the end. But once we start blending from multiple inputs,
8583   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8584   // and there are *very* few patterns that would actually be faster than the
8585   // PSHUFB approach because of its ability to zero lanes.
8586   //
8587   // FIXME: The only exceptions to the above are blends which are exact
8588   // interleavings with direct instructions supporting them. We currently don't
8589   // handle those well here.
8590   if (Subtarget->hasSSSE3()) {
8591     bool V1InUse = false;
8592     bool V2InUse = false;
8593
8594     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8595                                                 DAG, V1InUse, V2InUse);
8596
8597     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8598     // do so. This avoids using them to handle blends-with-zero which is
8599     // important as a single pshufb is significantly faster for that.
8600     if (V1InUse && V2InUse) {
8601       if (Subtarget->hasSSE41())
8602         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8603                                                       Mask, Subtarget, DAG))
8604           return Blend;
8605
8606       // We can use an unpack to do the blending rather than an or in some
8607       // cases. Even though the or may be (very minorly) more efficient, we
8608       // preference this lowering because there are common cases where part of
8609       // the complexity of the shuffles goes away when we do the final blend as
8610       // an unpack.
8611       // FIXME: It might be worth trying to detect if the unpack-feeding
8612       // shuffles will both be pshufb, in which case we shouldn't bother with
8613       // this.
8614       if (SDValue Unpack =
8615               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8616         return Unpack;
8617     }
8618
8619     return PSHUFB;
8620   }
8621
8622   // There are special ways we can lower some single-element blends.
8623   if (NumV2Elements == 1)
8624     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8625                                                          Mask, Subtarget, DAG))
8626       return V;
8627
8628   if (SDValue BitBlend =
8629           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8630     return BitBlend;
8631
8632   // Check whether a compaction lowering can be done. This handles shuffles
8633   // which take every Nth element for some even N. See the helper function for
8634   // details.
8635   //
8636   // We special case these as they can be particularly efficiently handled with
8637   // the PACKUSB instruction on x86 and they show up in common patterns of
8638   // rearranging bytes to truncate wide elements.
8639   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8640     // NumEvenDrops is the power of two stride of the elements. Another way of
8641     // thinking about it is that we need to drop the even elements this many
8642     // times to get the original input.
8643     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8644
8645     // First we need to zero all the dropped bytes.
8646     assert(NumEvenDrops <= 3 &&
8647            "No support for dropping even elements more than 3 times.");
8648     // We use the mask type to pick which bytes are preserved based on how many
8649     // elements are dropped.
8650     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8651     SDValue ByteClearMask =
8652         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8653                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8654     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8655     if (!IsSingleInput)
8656       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8657
8658     // Now pack things back together.
8659     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8660     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8661     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8662     for (int i = 1; i < NumEvenDrops; ++i) {
8663       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8664       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8665     }
8666
8667     return Result;
8668   }
8669
8670   // Handle multi-input cases by blending single-input shuffles.
8671   if (NumV2Elements > 0)
8672     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8673                                                       Mask, DAG);
8674
8675   // The fallback path for single-input shuffles widens this into two v8i16
8676   // vectors with unpacks, shuffles those, and then pulls them back together
8677   // with a pack.
8678   SDValue V = V1;
8679
8680   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8681   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8682   for (int i = 0; i < 16; ++i)
8683     if (Mask[i] >= 0)
8684       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8685
8686   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8687
8688   SDValue VLoHalf, VHiHalf;
8689   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8690   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8691   // i16s.
8692   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8693                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8694       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8695                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8696     // Use a mask to drop the high bytes.
8697     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8698     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8699                      DAG.getConstant(0x00FF, MVT::v8i16));
8700
8701     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8702     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8703
8704     // Squash the masks to point directly into VLoHalf.
8705     for (int &M : LoBlendMask)
8706       if (M >= 0)
8707         M /= 2;
8708     for (int &M : HiBlendMask)
8709       if (M >= 0)
8710         M /= 2;
8711   } else {
8712     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8713     // VHiHalf so that we can blend them as i16s.
8714     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8715                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8716     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8717                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8718   }
8719
8720   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8721   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8722
8723   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8724 }
8725
8726 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8727 ///
8728 /// This routine breaks down the specific type of 128-bit shuffle and
8729 /// dispatches to the lowering routines accordingly.
8730 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8731                                         MVT VT, const X86Subtarget *Subtarget,
8732                                         SelectionDAG &DAG) {
8733   switch (VT.SimpleTy) {
8734   case MVT::v2i64:
8735     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8736   case MVT::v2f64:
8737     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8738   case MVT::v4i32:
8739     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8740   case MVT::v4f32:
8741     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8742   case MVT::v8i16:
8743     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8744   case MVT::v16i8:
8745     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8746
8747   default:
8748     llvm_unreachable("Unimplemented!");
8749   }
8750 }
8751
8752 /// \brief Helper function to test whether a shuffle mask could be
8753 /// simplified by widening the elements being shuffled.
8754 ///
8755 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8756 /// leaves it in an unspecified state.
8757 ///
8758 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8759 /// shuffle masks. The latter have the special property of a '-2' representing
8760 /// a zero-ed lane of a vector.
8761 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8762                                     SmallVectorImpl<int> &WidenedMask) {
8763   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8764     // If both elements are undef, its trivial.
8765     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8766       WidenedMask.push_back(SM_SentinelUndef);
8767       continue;
8768     }
8769
8770     // Check for an undef mask and a mask value properly aligned to fit with
8771     // a pair of values. If we find such a case, use the non-undef mask's value.
8772     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8773       WidenedMask.push_back(Mask[i + 1] / 2);
8774       continue;
8775     }
8776     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8777       WidenedMask.push_back(Mask[i] / 2);
8778       continue;
8779     }
8780
8781     // When zeroing, we need to spread the zeroing across both lanes to widen.
8782     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8783       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8784           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8785         WidenedMask.push_back(SM_SentinelZero);
8786         continue;
8787       }
8788       return false;
8789     }
8790
8791     // Finally check if the two mask values are adjacent and aligned with
8792     // a pair.
8793     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8794       WidenedMask.push_back(Mask[i] / 2);
8795       continue;
8796     }
8797
8798     // Otherwise we can't safely widen the elements used in this shuffle.
8799     return false;
8800   }
8801   assert(WidenedMask.size() == Mask.size() / 2 &&
8802          "Incorrect size of mask after widening the elements!");
8803
8804   return true;
8805 }
8806
8807 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8808 ///
8809 /// This routine just extracts two subvectors, shuffles them independently, and
8810 /// then concatenates them back together. This should work effectively with all
8811 /// AVX vector shuffle types.
8812 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8813                                           SDValue V2, ArrayRef<int> Mask,
8814                                           SelectionDAG &DAG) {
8815   assert(VT.getSizeInBits() >= 256 &&
8816          "Only for 256-bit or wider vector shuffles!");
8817   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8818   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8819
8820   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8821   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8822
8823   int NumElements = VT.getVectorNumElements();
8824   int SplitNumElements = NumElements / 2;
8825   MVT ScalarVT = VT.getScalarType();
8826   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8827
8828   // Rather than splitting build-vectors, just build two narrower build
8829   // vectors. This helps shuffling with splats and zeros.
8830   auto SplitVector = [&](SDValue V) {
8831     while (V.getOpcode() == ISD::BITCAST)
8832       V = V->getOperand(0);
8833
8834     MVT OrigVT = V.getSimpleValueType();
8835     int OrigNumElements = OrigVT.getVectorNumElements();
8836     int OrigSplitNumElements = OrigNumElements / 2;
8837     MVT OrigScalarVT = OrigVT.getScalarType();
8838     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8839
8840     SDValue LoV, HiV;
8841
8842     auto *BV = dyn_cast<BuildVectorSDNode>(V);
8843     if (!BV) {
8844       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8845                         DAG.getIntPtrConstant(0));
8846       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8847                         DAG.getIntPtrConstant(OrigSplitNumElements));
8848     } else {
8849
8850       SmallVector<SDValue, 16> LoOps, HiOps;
8851       for (int i = 0; i < OrigSplitNumElements; ++i) {
8852         LoOps.push_back(BV->getOperand(i));
8853         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
8854       }
8855       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
8856       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
8857     }
8858     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
8859                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
8860   };
8861
8862   SDValue LoV1, HiV1, LoV2, HiV2;
8863   std::tie(LoV1, HiV1) = SplitVector(V1);
8864   std::tie(LoV2, HiV2) = SplitVector(V2);
8865
8866   // Now create two 4-way blends of these half-width vectors.
8867   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8868     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
8869     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
8870     for (int i = 0; i < SplitNumElements; ++i) {
8871       int M = HalfMask[i];
8872       if (M >= NumElements) {
8873         if (M >= NumElements + SplitNumElements)
8874           UseHiV2 = true;
8875         else
8876           UseLoV2 = true;
8877         V2BlendMask.push_back(M - NumElements);
8878         V1BlendMask.push_back(-1);
8879         BlendMask.push_back(SplitNumElements + i);
8880       } else if (M >= 0) {
8881         if (M >= SplitNumElements)
8882           UseHiV1 = true;
8883         else
8884           UseLoV1 = true;
8885         V2BlendMask.push_back(-1);
8886         V1BlendMask.push_back(M);
8887         BlendMask.push_back(i);
8888       } else {
8889         V2BlendMask.push_back(-1);
8890         V1BlendMask.push_back(-1);
8891         BlendMask.push_back(-1);
8892       }
8893     }
8894
8895     // Because the lowering happens after all combining takes place, we need to
8896     // manually combine these blend masks as much as possible so that we create
8897     // a minimal number of high-level vector shuffle nodes.
8898
8899     // First try just blending the halves of V1 or V2.
8900     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
8901       return DAG.getUNDEF(SplitVT);
8902     if (!UseLoV2 && !UseHiV2)
8903       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8904     if (!UseLoV1 && !UseHiV1)
8905       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8906
8907     SDValue V1Blend, V2Blend;
8908     if (UseLoV1 && UseHiV1) {
8909       V1Blend =
8910         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8911     } else {
8912       // We only use half of V1 so map the usage down into the final blend mask.
8913       V1Blend = UseLoV1 ? LoV1 : HiV1;
8914       for (int i = 0; i < SplitNumElements; ++i)
8915         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
8916           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
8917     }
8918     if (UseLoV2 && UseHiV2) {
8919       V2Blend =
8920         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8921     } else {
8922       // We only use half of V2 so map the usage down into the final blend mask.
8923       V2Blend = UseLoV2 ? LoV2 : HiV2;
8924       for (int i = 0; i < SplitNumElements; ++i)
8925         if (BlendMask[i] >= SplitNumElements)
8926           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
8927     }
8928     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8929   };
8930   SDValue Lo = HalfBlend(LoMask);
8931   SDValue Hi = HalfBlend(HiMask);
8932   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8933 }
8934
8935 /// \brief Either split a vector in halves or decompose the shuffles and the
8936 /// blend.
8937 ///
8938 /// This is provided as a good fallback for many lowerings of non-single-input
8939 /// shuffles with more than one 128-bit lane. In those cases, we want to select
8940 /// between splitting the shuffle into 128-bit components and stitching those
8941 /// back together vs. extracting the single-input shuffles and blending those
8942 /// results.
8943 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
8944                                                 SDValue V2, ArrayRef<int> Mask,
8945                                                 SelectionDAG &DAG) {
8946   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
8947                                             "lower single-input shuffles as it "
8948                                             "could then recurse on itself.");
8949   int Size = Mask.size();
8950
8951   // If this can be modeled as a broadcast of two elements followed by a blend,
8952   // prefer that lowering. This is especially important because broadcasts can
8953   // often fold with memory operands.
8954   auto DoBothBroadcast = [&] {
8955     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
8956     for (int M : Mask)
8957       if (M >= Size) {
8958         if (V2BroadcastIdx == -1)
8959           V2BroadcastIdx = M - Size;
8960         else if (M - Size != V2BroadcastIdx)
8961           return false;
8962       } else if (M >= 0) {
8963         if (V1BroadcastIdx == -1)
8964           V1BroadcastIdx = M;
8965         else if (M != V1BroadcastIdx)
8966           return false;
8967       }
8968     return true;
8969   };
8970   if (DoBothBroadcast())
8971     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
8972                                                       DAG);
8973
8974   // If the inputs all stem from a single 128-bit lane of each input, then we
8975   // split them rather than blending because the split will decompose to
8976   // unusually few instructions.
8977   int LaneCount = VT.getSizeInBits() / 128;
8978   int LaneSize = Size / LaneCount;
8979   SmallBitVector LaneInputs[2];
8980   LaneInputs[0].resize(LaneCount, false);
8981   LaneInputs[1].resize(LaneCount, false);
8982   for (int i = 0; i < Size; ++i)
8983     if (Mask[i] >= 0)
8984       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
8985   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
8986     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
8987
8988   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
8989   // that the decomposed single-input shuffles don't end up here.
8990   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
8991 }
8992
8993 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
8994 /// a permutation and blend of those lanes.
8995 ///
8996 /// This essentially blends the out-of-lane inputs to each lane into the lane
8997 /// from a permuted copy of the vector. This lowering strategy results in four
8998 /// instructions in the worst case for a single-input cross lane shuffle which
8999 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9000 /// of. Special cases for each particular shuffle pattern should be handled
9001 /// prior to trying this lowering.
9002 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9003                                                        SDValue V1, SDValue V2,
9004                                                        ArrayRef<int> Mask,
9005                                                        SelectionDAG &DAG) {
9006   // FIXME: This should probably be generalized for 512-bit vectors as well.
9007   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9008   int LaneSize = Mask.size() / 2;
9009
9010   // If there are only inputs from one 128-bit lane, splitting will in fact be
9011   // less expensive. The flags track whether the given lane contains an element
9012   // that crosses to another lane.
9013   bool LaneCrossing[2] = {false, false};
9014   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9015     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9016       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9017   if (!LaneCrossing[0] || !LaneCrossing[1])
9018     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9019
9020   if (isSingleInputShuffleMask(Mask)) {
9021     SmallVector<int, 32> FlippedBlendMask;
9022     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9023       FlippedBlendMask.push_back(
9024           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9025                                   ? Mask[i]
9026                                   : Mask[i] % LaneSize +
9027                                         (i / LaneSize) * LaneSize + Size));
9028
9029     // Flip the vector, and blend the results which should now be in-lane. The
9030     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9031     // 5 for the high source. The value 3 selects the high half of source 2 and
9032     // the value 2 selects the low half of source 2. We only use source 2 to
9033     // allow folding it into a memory operand.
9034     unsigned PERMMask = 3 | 2 << 4;
9035     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9036                                   V1, DAG.getConstant(PERMMask, MVT::i8));
9037     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9038   }
9039
9040   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9041   // will be handled by the above logic and a blend of the results, much like
9042   // other patterns in AVX.
9043   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9044 }
9045
9046 /// \brief Handle lowering 2-lane 128-bit shuffles.
9047 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9048                                         SDValue V2, ArrayRef<int> Mask,
9049                                         const X86Subtarget *Subtarget,
9050                                         SelectionDAG &DAG) {
9051   // TODO: If minimizing size and one of the inputs is a zero vector and the
9052   // the zero vector has only one use, we could use a VPERM2X128 to save the
9053   // instruction bytes needed to explicitly generate the zero vector.
9054
9055   // Blends are faster and handle all the non-lane-crossing cases.
9056   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9057                                                 Subtarget, DAG))
9058     return Blend;
9059
9060   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9061   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9062
9063   // If either input operand is a zero vector, use VPERM2X128 because its mask
9064   // allows us to replace the zero input with an implicit zero.
9065   if (!IsV1Zero && !IsV2Zero) {
9066     // Check for patterns which can be matched with a single insert of a 128-bit
9067     // subvector.
9068     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9069     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9070       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9071                                    VT.getVectorNumElements() / 2);
9072       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9073                                 DAG.getIntPtrConstant(0));
9074       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9075                                 OnlyUsesV1 ? V1 : V2, DAG.getIntPtrConstant(0));
9076       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9077     }
9078   }
9079
9080   // Otherwise form a 128-bit permutation. After accounting for undefs,
9081   // convert the 64-bit shuffle mask selection values into 128-bit
9082   // selection bits by dividing the indexes by 2 and shifting into positions
9083   // defined by a vperm2*128 instruction's immediate control byte.
9084
9085   // The immediate permute control byte looks like this:
9086   //    [1:0] - select 128 bits from sources for low half of destination
9087   //    [2]   - ignore
9088   //    [3]   - zero low half of destination
9089   //    [5:4] - select 128 bits from sources for high half of destination
9090   //    [6]   - ignore
9091   //    [7]   - zero high half of destination
9092
9093   int MaskLO = Mask[0];
9094   if (MaskLO == SM_SentinelUndef)
9095     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9096
9097   int MaskHI = Mask[2];
9098   if (MaskHI == SM_SentinelUndef)
9099     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9100
9101   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9102
9103   // If either input is a zero vector, replace it with an undef input.
9104   // Shuffle mask values <  4 are selecting elements of V1.
9105   // Shuffle mask values >= 4 are selecting elements of V2.
9106   // Adjust each half of the permute mask by clearing the half that was
9107   // selecting the zero vector and setting the zero mask bit.
9108   if (IsV1Zero) {
9109     V1 = DAG.getUNDEF(VT);
9110     if (MaskLO < 4)
9111       PermMask = (PermMask & 0xf0) | 0x08;
9112     if (MaskHI < 4)
9113       PermMask = (PermMask & 0x0f) | 0x80;
9114   }
9115   if (IsV2Zero) {
9116     V2 = DAG.getUNDEF(VT);
9117     if (MaskLO >= 4)
9118       PermMask = (PermMask & 0xf0) | 0x08;
9119     if (MaskHI >= 4)
9120       PermMask = (PermMask & 0x0f) | 0x80;
9121   }
9122
9123   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9124                      DAG.getConstant(PermMask, MVT::i8));
9125 }
9126
9127 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9128 /// shuffling each lane.
9129 ///
9130 /// This will only succeed when the result of fixing the 128-bit lanes results
9131 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9132 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9133 /// the lane crosses early and then use simpler shuffles within each lane.
9134 ///
9135 /// FIXME: It might be worthwhile at some point to support this without
9136 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9137 /// in x86 only floating point has interesting non-repeating shuffles, and even
9138 /// those are still *marginally* more expensive.
9139 static SDValue lowerVectorShuffleByMerging128BitLanes(
9140     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9141     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9142   assert(!isSingleInputShuffleMask(Mask) &&
9143          "This is only useful with multiple inputs.");
9144
9145   int Size = Mask.size();
9146   int LaneSize = 128 / VT.getScalarSizeInBits();
9147   int NumLanes = Size / LaneSize;
9148   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9149
9150   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9151   // check whether the in-128-bit lane shuffles share a repeating pattern.
9152   SmallVector<int, 4> Lanes;
9153   Lanes.resize(NumLanes, -1);
9154   SmallVector<int, 4> InLaneMask;
9155   InLaneMask.resize(LaneSize, -1);
9156   for (int i = 0; i < Size; ++i) {
9157     if (Mask[i] < 0)
9158       continue;
9159
9160     int j = i / LaneSize;
9161
9162     if (Lanes[j] < 0) {
9163       // First entry we've seen for this lane.
9164       Lanes[j] = Mask[i] / LaneSize;
9165     } else if (Lanes[j] != Mask[i] / LaneSize) {
9166       // This doesn't match the lane selected previously!
9167       return SDValue();
9168     }
9169
9170     // Check that within each lane we have a consistent shuffle mask.
9171     int k = i % LaneSize;
9172     if (InLaneMask[k] < 0) {
9173       InLaneMask[k] = Mask[i] % LaneSize;
9174     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9175       // This doesn't fit a repeating in-lane mask.
9176       return SDValue();
9177     }
9178   }
9179
9180   // First shuffle the lanes into place.
9181   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9182                                 VT.getSizeInBits() / 64);
9183   SmallVector<int, 8> LaneMask;
9184   LaneMask.resize(NumLanes * 2, -1);
9185   for (int i = 0; i < NumLanes; ++i)
9186     if (Lanes[i] >= 0) {
9187       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9188       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9189     }
9190
9191   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9192   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9193   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9194
9195   // Cast it back to the type we actually want.
9196   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9197
9198   // Now do a simple shuffle that isn't lane crossing.
9199   SmallVector<int, 8> NewMask;
9200   NewMask.resize(Size, -1);
9201   for (int i = 0; i < Size; ++i)
9202     if (Mask[i] >= 0)
9203       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9204   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9205          "Must not introduce lane crosses at this point!");
9206
9207   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9208 }
9209
9210 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9211 /// given mask.
9212 ///
9213 /// This returns true if the elements from a particular input are already in the
9214 /// slot required by the given mask and require no permutation.
9215 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9216   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9217   int Size = Mask.size();
9218   for (int i = 0; i < Size; ++i)
9219     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9220       return false;
9221
9222   return true;
9223 }
9224
9225 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9226 ///
9227 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9228 /// isn't available.
9229 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9230                                        const X86Subtarget *Subtarget,
9231                                        SelectionDAG &DAG) {
9232   SDLoc DL(Op);
9233   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9234   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9235   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9236   ArrayRef<int> Mask = SVOp->getMask();
9237   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9238
9239   SmallVector<int, 4> WidenedMask;
9240   if (canWidenShuffleElements(Mask, WidenedMask))
9241     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9242                                     DAG);
9243
9244   if (isSingleInputShuffleMask(Mask)) {
9245     // Check for being able to broadcast a single element.
9246     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9247                                                           Mask, Subtarget, DAG))
9248       return Broadcast;
9249
9250     // Use low duplicate instructions for masks that match their pattern.
9251     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9252       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9253
9254     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9255       // Non-half-crossing single input shuffles can be lowerid with an
9256       // interleaved permutation.
9257       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9258                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9259       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9260                          DAG.getConstant(VPERMILPMask, MVT::i8));
9261     }
9262
9263     // With AVX2 we have direct support for this permutation.
9264     if (Subtarget->hasAVX2())
9265       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9266                          getV4X86ShuffleImm8ForMask(Mask, DAG));
9267
9268     // Otherwise, fall back.
9269     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9270                                                    DAG);
9271   }
9272
9273   // X86 has dedicated unpack instructions that can handle specific blend
9274   // operations: UNPCKH and UNPCKL.
9275   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9276     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9277   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9278     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9279   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9280     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9281   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9282     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9283
9284   // If we have a single input to the zero element, insert that into V1 if we
9285   // can do so cheaply.
9286   int NumV2Elements =
9287       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
9288   if (NumV2Elements == 1 && Mask[0] >= 4)
9289     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9290             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9291       return Insertion;
9292
9293   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9294                                                 Subtarget, DAG))
9295     return Blend;
9296
9297   // Check if the blend happens to exactly fit that of SHUFPD.
9298   if ((Mask[0] == -1 || Mask[0] < 2) &&
9299       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9300       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9301       (Mask[3] == -1 || Mask[3] >= 6)) {
9302     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9303                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9304     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9305                        DAG.getConstant(SHUFPDMask, MVT::i8));
9306   }
9307   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9308       (Mask[1] == -1 || Mask[1] < 2) &&
9309       (Mask[2] == -1 || Mask[2] >= 6) &&
9310       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9311     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9312                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9313     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9314                        DAG.getConstant(SHUFPDMask, MVT::i8));
9315   }
9316
9317   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9318   // shuffle. However, if we have AVX2 and either inputs are already in place,
9319   // we will be able to shuffle even across lanes the other input in a single
9320   // instruction so skip this pattern.
9321   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9322                                  isShuffleMaskInputInPlace(1, Mask))))
9323     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9324             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9325       return Result;
9326
9327   // If we have AVX2 then we always want to lower with a blend because an v4 we
9328   // can fully permute the elements.
9329   if (Subtarget->hasAVX2())
9330     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9331                                                       Mask, DAG);
9332
9333   // Otherwise fall back on generic lowering.
9334   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9335 }
9336
9337 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9338 ///
9339 /// This routine is only called when we have AVX2 and thus a reasonable
9340 /// instruction set for v4i64 shuffling..
9341 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9342                                        const X86Subtarget *Subtarget,
9343                                        SelectionDAG &DAG) {
9344   SDLoc DL(Op);
9345   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9346   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9347   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9348   ArrayRef<int> Mask = SVOp->getMask();
9349   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9350   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9351
9352   SmallVector<int, 4> WidenedMask;
9353   if (canWidenShuffleElements(Mask, WidenedMask))
9354     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9355                                     DAG);
9356
9357   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9358                                                 Subtarget, DAG))
9359     return Blend;
9360
9361   // Check for being able to broadcast a single element.
9362   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9363                                                         Mask, Subtarget, DAG))
9364     return Broadcast;
9365
9366   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9367   // use lower latency instructions that will operate on both 128-bit lanes.
9368   SmallVector<int, 2> RepeatedMask;
9369   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9370     if (isSingleInputShuffleMask(Mask)) {
9371       int PSHUFDMask[] = {-1, -1, -1, -1};
9372       for (int i = 0; i < 2; ++i)
9373         if (RepeatedMask[i] >= 0) {
9374           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9375           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9376         }
9377       return DAG.getNode(
9378           ISD::BITCAST, DL, MVT::v4i64,
9379           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9380                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9381                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9382     }
9383   }
9384
9385   // AVX2 provides a direct instruction for permuting a single input across
9386   // lanes.
9387   if (isSingleInputShuffleMask(Mask))
9388     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9389                        getV4X86ShuffleImm8ForMask(Mask, DAG));
9390
9391   // Try to use shift instructions.
9392   if (SDValue Shift =
9393           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9394     return Shift;
9395
9396   // Use dedicated unpack instructions for masks that match their pattern.
9397   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9398     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9399   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9400     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9401   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9402     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9403   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9404     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9405
9406   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9407   // shuffle. However, if we have AVX2 and either inputs are already in place,
9408   // we will be able to shuffle even across lanes the other input in a single
9409   // instruction so skip this pattern.
9410   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9411                                  isShuffleMaskInputInPlace(1, Mask))))
9412     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9413             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9414       return Result;
9415
9416   // Otherwise fall back on generic blend lowering.
9417   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9418                                                     Mask, DAG);
9419 }
9420
9421 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9422 ///
9423 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9424 /// isn't available.
9425 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9426                                        const X86Subtarget *Subtarget,
9427                                        SelectionDAG &DAG) {
9428   SDLoc DL(Op);
9429   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9430   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9431   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9432   ArrayRef<int> Mask = SVOp->getMask();
9433   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9434
9435   // If we have a single input to the zero element, insert that into V1 if we
9436   // can do so cheaply.
9437   int NumV2Elements =
9438       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 8; });
9439   if (NumV2Elements == 1 && Mask[0] >= 8)
9440     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9441             DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9442       return Insertion;
9443
9444   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9445                                                 Subtarget, DAG))
9446     return Blend;
9447
9448   // Check for being able to broadcast a single element.
9449   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9450                                                         Mask, Subtarget, DAG))
9451     return Broadcast;
9452
9453   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9454   // options to efficiently lower the shuffle.
9455   SmallVector<int, 4> RepeatedMask;
9456   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9457     assert(RepeatedMask.size() == 4 &&
9458            "Repeated masks must be half the mask width!");
9459
9460     // Use even/odd duplicate instructions for masks that match their pattern.
9461     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9462       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9463     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9464       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9465
9466     if (isSingleInputShuffleMask(Mask))
9467       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9468                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9469
9470     // Use dedicated unpack instructions for masks that match their pattern.
9471     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9472       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9473     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9474       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9475     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9476       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9477     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9478       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9479
9480     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9481     // have already handled any direct blends. We also need to squash the
9482     // repeated mask into a simulated v4f32 mask.
9483     for (int i = 0; i < 4; ++i)
9484       if (RepeatedMask[i] >= 8)
9485         RepeatedMask[i] -= 4;
9486     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9487   }
9488
9489   // If we have a single input shuffle with different shuffle patterns in the
9490   // two 128-bit lanes use the variable mask to VPERMILPS.
9491   if (isSingleInputShuffleMask(Mask)) {
9492     SDValue VPermMask[8];
9493     for (int i = 0; i < 8; ++i)
9494       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9495                                  : DAG.getConstant(Mask[i], MVT::i32);
9496     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9497       return DAG.getNode(
9498           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9499           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9500
9501     if (Subtarget->hasAVX2())
9502       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9503                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9504                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9505                                                  MVT::v8i32, VPermMask)),
9506                          V1);
9507
9508     // Otherwise, fall back.
9509     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9510                                                    DAG);
9511   }
9512
9513   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9514   // shuffle.
9515   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9516           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9517     return Result;
9518
9519   // If we have AVX2 then we always want to lower with a blend because at v8 we
9520   // can fully permute the elements.
9521   if (Subtarget->hasAVX2())
9522     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9523                                                       Mask, DAG);
9524
9525   // Otherwise fall back on generic lowering.
9526   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9527 }
9528
9529 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9530 ///
9531 /// This routine is only called when we have AVX2 and thus a reasonable
9532 /// instruction set for v8i32 shuffling..
9533 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9534                                        const X86Subtarget *Subtarget,
9535                                        SelectionDAG &DAG) {
9536   SDLoc DL(Op);
9537   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9538   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9539   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9540   ArrayRef<int> Mask = SVOp->getMask();
9541   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9542   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9543
9544   // Whenever we can lower this as a zext, that instruction is strictly faster
9545   // than any alternative. It also allows us to fold memory operands into the
9546   // shuffle in many cases.
9547   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9548                                                          Mask, Subtarget, DAG))
9549     return ZExt;
9550
9551   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9552                                                 Subtarget, DAG))
9553     return Blend;
9554
9555   // Check for being able to broadcast a single element.
9556   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9557                                                         Mask, Subtarget, DAG))
9558     return Broadcast;
9559
9560   // If the shuffle mask is repeated in each 128-bit lane we can use more
9561   // efficient instructions that mirror the shuffles across the two 128-bit
9562   // lanes.
9563   SmallVector<int, 4> RepeatedMask;
9564   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9565     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9566     if (isSingleInputShuffleMask(Mask))
9567       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9568                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9569
9570     // Use dedicated unpack instructions for masks that match their pattern.
9571     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9572       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9573     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9574       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9575     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9576       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9577     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9578       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9579   }
9580
9581   // Try to use shift instructions.
9582   if (SDValue Shift =
9583           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9584     return Shift;
9585
9586   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9587           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9588     return Rotate;
9589
9590   // If the shuffle patterns aren't repeated but it is a single input, directly
9591   // generate a cross-lane VPERMD instruction.
9592   if (isSingleInputShuffleMask(Mask)) {
9593     SDValue VPermMask[8];
9594     for (int i = 0; i < 8; ++i)
9595       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9596                                  : DAG.getConstant(Mask[i], MVT::i32);
9597     return DAG.getNode(
9598         X86ISD::VPERMV, DL, MVT::v8i32,
9599         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9600   }
9601
9602   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9603   // shuffle.
9604   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9605           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9606     return Result;
9607
9608   // Otherwise fall back on generic blend lowering.
9609   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9610                                                     Mask, DAG);
9611 }
9612
9613 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9614 ///
9615 /// This routine is only called when we have AVX2 and thus a reasonable
9616 /// instruction set for v16i16 shuffling..
9617 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9618                                         const X86Subtarget *Subtarget,
9619                                         SelectionDAG &DAG) {
9620   SDLoc DL(Op);
9621   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9622   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9623   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9624   ArrayRef<int> Mask = SVOp->getMask();
9625   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9626   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9627
9628   // Whenever we can lower this as a zext, that instruction is strictly faster
9629   // than any alternative. It also allows us to fold memory operands into the
9630   // shuffle in many cases.
9631   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9632                                                          Mask, Subtarget, DAG))
9633     return ZExt;
9634
9635   // Check for being able to broadcast a single element.
9636   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9637                                                         Mask, Subtarget, DAG))
9638     return Broadcast;
9639
9640   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9641                                                 Subtarget, DAG))
9642     return Blend;
9643
9644   // Use dedicated unpack instructions for masks that match their pattern.
9645   if (isShuffleEquivalent(V1, V2, Mask,
9646                           {// First 128-bit lane:
9647                            0, 16, 1, 17, 2, 18, 3, 19,
9648                            // Second 128-bit lane:
9649                            8, 24, 9, 25, 10, 26, 11, 27}))
9650     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9651   if (isShuffleEquivalent(V1, V2, Mask,
9652                           {// First 128-bit lane:
9653                            4, 20, 5, 21, 6, 22, 7, 23,
9654                            // Second 128-bit lane:
9655                            12, 28, 13, 29, 14, 30, 15, 31}))
9656     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9657
9658   // Try to use shift instructions.
9659   if (SDValue Shift =
9660           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9661     return Shift;
9662
9663   // Try to use byte rotation instructions.
9664   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9665           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9666     return Rotate;
9667
9668   if (isSingleInputShuffleMask(Mask)) {
9669     // There are no generalized cross-lane shuffle operations available on i16
9670     // element types.
9671     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9672       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9673                                                      Mask, DAG);
9674
9675     SmallVector<int, 8> RepeatedMask;
9676     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9677       // As this is a single-input shuffle, the repeated mask should be
9678       // a strictly valid v8i16 mask that we can pass through to the v8i16
9679       // lowering to handle even the v16 case.
9680       return lowerV8I16GeneralSingleInputVectorShuffle(
9681           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9682     }
9683
9684     SDValue PSHUFBMask[32];
9685     for (int i = 0; i < 16; ++i) {
9686       if (Mask[i] == -1) {
9687         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9688         continue;
9689       }
9690
9691       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9692       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9693       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
9694       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
9695     }
9696     return DAG.getNode(
9697         ISD::BITCAST, DL, MVT::v16i16,
9698         DAG.getNode(
9699             X86ISD::PSHUFB, DL, MVT::v32i8,
9700             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9701             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9702   }
9703
9704   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9705   // shuffle.
9706   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9707           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9708     return Result;
9709
9710   // Otherwise fall back on generic lowering.
9711   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9712 }
9713
9714 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9715 ///
9716 /// This routine is only called when we have AVX2 and thus a reasonable
9717 /// instruction set for v32i8 shuffling..
9718 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9719                                        const X86Subtarget *Subtarget,
9720                                        SelectionDAG &DAG) {
9721   SDLoc DL(Op);
9722   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9723   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9724   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9725   ArrayRef<int> Mask = SVOp->getMask();
9726   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9727   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9728
9729   // Whenever we can lower this as a zext, that instruction is strictly faster
9730   // than any alternative. It also allows us to fold memory operands into the
9731   // shuffle in many cases.
9732   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9733                                                          Mask, Subtarget, DAG))
9734     return ZExt;
9735
9736   // Check for being able to broadcast a single element.
9737   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9738                                                         Mask, Subtarget, DAG))
9739     return Broadcast;
9740
9741   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9742                                                 Subtarget, DAG))
9743     return Blend;
9744
9745   // Use dedicated unpack instructions for masks that match their pattern.
9746   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9747   // 256-bit lanes.
9748   if (isShuffleEquivalent(
9749           V1, V2, Mask,
9750           {// First 128-bit lane:
9751            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9752            // Second 128-bit lane:
9753            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9754     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9755   if (isShuffleEquivalent(
9756           V1, V2, Mask,
9757           {// First 128-bit lane:
9758            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9759            // Second 128-bit lane:
9760            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9761     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9762
9763   // Try to use shift instructions.
9764   if (SDValue Shift =
9765           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9766     return Shift;
9767
9768   // Try to use byte rotation instructions.
9769   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9770           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9771     return Rotate;
9772
9773   if (isSingleInputShuffleMask(Mask)) {
9774     // There are no generalized cross-lane shuffle operations available on i8
9775     // element types.
9776     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9777       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9778                                                      Mask, DAG);
9779
9780     SDValue PSHUFBMask[32];
9781     for (int i = 0; i < 32; ++i)
9782       PSHUFBMask[i] =
9783           Mask[i] < 0
9784               ? DAG.getUNDEF(MVT::i8)
9785               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
9786
9787     return DAG.getNode(
9788         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9789         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9790   }
9791
9792   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9793   // shuffle.
9794   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9795           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9796     return Result;
9797
9798   // Otherwise fall back on generic lowering.
9799   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9800 }
9801
9802 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9803 ///
9804 /// This routine either breaks down the specific type of a 256-bit x86 vector
9805 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9806 /// together based on the available instructions.
9807 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9808                                         MVT VT, const X86Subtarget *Subtarget,
9809                                         SelectionDAG &DAG) {
9810   SDLoc DL(Op);
9811   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9812   ArrayRef<int> Mask = SVOp->getMask();
9813
9814   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9815   // check for those subtargets here and avoid much of the subtarget querying in
9816   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9817   // ability to manipulate a 256-bit vector with integer types. Since we'll use
9818   // floating point types there eventually, just immediately cast everything to
9819   // a float and operate entirely in that domain.
9820   if (VT.isInteger() && !Subtarget->hasAVX2()) {
9821     int ElementBits = VT.getScalarSizeInBits();
9822     if (ElementBits < 32)
9823       // No floating point type available, decompose into 128-bit vectors.
9824       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9825
9826     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9827                                 VT.getVectorNumElements());
9828     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9829     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9830     return DAG.getNode(ISD::BITCAST, DL, VT,
9831                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9832   }
9833
9834   switch (VT.SimpleTy) {
9835   case MVT::v4f64:
9836     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9837   case MVT::v4i64:
9838     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9839   case MVT::v8f32:
9840     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9841   case MVT::v8i32:
9842     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9843   case MVT::v16i16:
9844     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9845   case MVT::v32i8:
9846     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9847
9848   default:
9849     llvm_unreachable("Not a valid 256-bit x86 vector type!");
9850   }
9851 }
9852
9853 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
9854 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9855                                        const X86Subtarget *Subtarget,
9856                                        SelectionDAG &DAG) {
9857   SDLoc DL(Op);
9858   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9859   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9860   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9861   ArrayRef<int> Mask = SVOp->getMask();
9862   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9863
9864   // X86 has dedicated unpack instructions that can handle specific blend
9865   // operations: UNPCKH and UNPCKL.
9866   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9867     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
9868   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9869     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
9870
9871   // FIXME: Implement direct support for this type!
9872   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
9873 }
9874
9875 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
9876 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9877                                        const X86Subtarget *Subtarget,
9878                                        SelectionDAG &DAG) {
9879   SDLoc DL(Op);
9880   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9881   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9882   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9883   ArrayRef<int> Mask = SVOp->getMask();
9884   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9885
9886   // Use dedicated unpack instructions for masks that match their pattern.
9887   if (isShuffleEquivalent(V1, V2, Mask,
9888                           {// First 128-bit lane.
9889                            0, 16, 1, 17, 4, 20, 5, 21,
9890                            // Second 128-bit lane.
9891                            8, 24, 9, 25, 12, 28, 13, 29}))
9892     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
9893   if (isShuffleEquivalent(V1, V2, Mask,
9894                           {// First 128-bit lane.
9895                            2, 18, 3, 19, 6, 22, 7, 23,
9896                            // Second 128-bit lane.
9897                            10, 26, 11, 27, 14, 30, 15, 31}))
9898     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
9899
9900   // FIXME: Implement direct support for this type!
9901   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
9902 }
9903
9904 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
9905 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9906                                        const X86Subtarget *Subtarget,
9907                                        SelectionDAG &DAG) {
9908   SDLoc DL(Op);
9909   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9910   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9911   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9912   ArrayRef<int> Mask = SVOp->getMask();
9913   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9914
9915   // X86 has dedicated unpack instructions that can handle specific blend
9916   // operations: UNPCKH and UNPCKL.
9917   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9918     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
9919   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9920     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
9921
9922   // FIXME: Implement direct support for this type!
9923   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
9924 }
9925
9926 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
9927 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9928                                        const X86Subtarget *Subtarget,
9929                                        SelectionDAG &DAG) {
9930   SDLoc DL(Op);
9931   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9932   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9933   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9934   ArrayRef<int> Mask = SVOp->getMask();
9935   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9936
9937   // Use dedicated unpack instructions for masks that match their pattern.
9938   if (isShuffleEquivalent(V1, V2, Mask,
9939                           {// First 128-bit lane.
9940                            0, 16, 1, 17, 4, 20, 5, 21,
9941                            // Second 128-bit lane.
9942                            8, 24, 9, 25, 12, 28, 13, 29}))
9943     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
9944   if (isShuffleEquivalent(V1, V2, Mask,
9945                           {// First 128-bit lane.
9946                            2, 18, 3, 19, 6, 22, 7, 23,
9947                            // Second 128-bit lane.
9948                            10, 26, 11, 27, 14, 30, 15, 31}))
9949     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
9950
9951   // FIXME: Implement direct support for this type!
9952   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
9953 }
9954
9955 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
9956 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9957                                         const X86Subtarget *Subtarget,
9958                                         SelectionDAG &DAG) {
9959   SDLoc DL(Op);
9960   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9961   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9962   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9963   ArrayRef<int> Mask = SVOp->getMask();
9964   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9965   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
9966
9967   // FIXME: Implement direct support for this type!
9968   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
9969 }
9970
9971 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
9972 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9973                                        const X86Subtarget *Subtarget,
9974                                        SelectionDAG &DAG) {
9975   SDLoc DL(Op);
9976   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9977   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9978   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9979   ArrayRef<int> Mask = SVOp->getMask();
9980   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
9981   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
9982
9983   // FIXME: Implement direct support for this type!
9984   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
9985 }
9986
9987 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
9988 ///
9989 /// This routine either breaks down the specific type of a 512-bit x86 vector
9990 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
9991 /// together based on the available instructions.
9992 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9993                                         MVT VT, const X86Subtarget *Subtarget,
9994                                         SelectionDAG &DAG) {
9995   SDLoc DL(Op);
9996   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9997   ArrayRef<int> Mask = SVOp->getMask();
9998   assert(Subtarget->hasAVX512() &&
9999          "Cannot lower 512-bit vectors w/ basic ISA!");
10000
10001   // Check for being able to broadcast a single element.
10002   if (SDValue Broadcast =
10003           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10004     return Broadcast;
10005
10006   // Dispatch to each element type for lowering. If we don't have supprot for
10007   // specific element type shuffles at 512 bits, immediately split them and
10008   // lower them. Each lowering routine of a given type is allowed to assume that
10009   // the requisite ISA extensions for that element type are available.
10010   switch (VT.SimpleTy) {
10011   case MVT::v8f64:
10012     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10013   case MVT::v16f32:
10014     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10015   case MVT::v8i64:
10016     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10017   case MVT::v16i32:
10018     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10019   case MVT::v32i16:
10020     if (Subtarget->hasBWI())
10021       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10022     break;
10023   case MVT::v64i8:
10024     if (Subtarget->hasBWI())
10025       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10026     break;
10027
10028   default:
10029     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10030   }
10031
10032   // Otherwise fall back on splitting.
10033   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10034 }
10035
10036 /// \brief Top-level lowering for x86 vector shuffles.
10037 ///
10038 /// This handles decomposition, canonicalization, and lowering of all x86
10039 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10040 /// above in helper routines. The canonicalization attempts to widen shuffles
10041 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10042 /// s.t. only one of the two inputs needs to be tested, etc.
10043 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10044                                   SelectionDAG &DAG) {
10045   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10046   ArrayRef<int> Mask = SVOp->getMask();
10047   SDValue V1 = Op.getOperand(0);
10048   SDValue V2 = Op.getOperand(1);
10049   MVT VT = Op.getSimpleValueType();
10050   int NumElements = VT.getVectorNumElements();
10051   SDLoc dl(Op);
10052
10053   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10054
10055   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10056   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10057   if (V1IsUndef && V2IsUndef)
10058     return DAG.getUNDEF(VT);
10059
10060   // When we create a shuffle node we put the UNDEF node to second operand,
10061   // but in some cases the first operand may be transformed to UNDEF.
10062   // In this case we should just commute the node.
10063   if (V1IsUndef)
10064     return DAG.getCommutedVectorShuffle(*SVOp);
10065
10066   // Check for non-undef masks pointing at an undef vector and make the masks
10067   // undef as well. This makes it easier to match the shuffle based solely on
10068   // the mask.
10069   if (V2IsUndef)
10070     for (int M : Mask)
10071       if (M >= NumElements) {
10072         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10073         for (int &M : NewMask)
10074           if (M >= NumElements)
10075             M = -1;
10076         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10077       }
10078
10079   // We actually see shuffles that are entirely re-arrangements of a set of
10080   // zero inputs. This mostly happens while decomposing complex shuffles into
10081   // simple ones. Directly lower these as a buildvector of zeros.
10082   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10083   if (Zeroable.all())
10084     return getZeroVector(VT, Subtarget, DAG, dl);
10085
10086   // Try to collapse shuffles into using a vector type with fewer elements but
10087   // wider element types. We cap this to not form integers or floating point
10088   // elements wider than 64 bits, but it might be interesting to form i128
10089   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10090   SmallVector<int, 16> WidenedMask;
10091   if (VT.getScalarSizeInBits() < 64 &&
10092       canWidenShuffleElements(Mask, WidenedMask)) {
10093     MVT NewEltVT = VT.isFloatingPoint()
10094                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10095                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10096     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10097     // Make sure that the new vector type is legal. For example, v2f64 isn't
10098     // legal on SSE1.
10099     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10100       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10101       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10102       return DAG.getNode(ISD::BITCAST, dl, VT,
10103                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10104     }
10105   }
10106
10107   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10108   for (int M : SVOp->getMask())
10109     if (M < 0)
10110       ++NumUndefElements;
10111     else if (M < NumElements)
10112       ++NumV1Elements;
10113     else
10114       ++NumV2Elements;
10115
10116   // Commute the shuffle as needed such that more elements come from V1 than
10117   // V2. This allows us to match the shuffle pattern strictly on how many
10118   // elements come from V1 without handling the symmetric cases.
10119   if (NumV2Elements > NumV1Elements)
10120     return DAG.getCommutedVectorShuffle(*SVOp);
10121
10122   // When the number of V1 and V2 elements are the same, try to minimize the
10123   // number of uses of V2 in the low half of the vector. When that is tied,
10124   // ensure that the sum of indices for V1 is equal to or lower than the sum
10125   // indices for V2. When those are equal, try to ensure that the number of odd
10126   // indices for V1 is lower than the number of odd indices for V2.
10127   if (NumV1Elements == NumV2Elements) {
10128     int LowV1Elements = 0, LowV2Elements = 0;
10129     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10130       if (M >= NumElements)
10131         ++LowV2Elements;
10132       else if (M >= 0)
10133         ++LowV1Elements;
10134     if (LowV2Elements > LowV1Elements) {
10135       return DAG.getCommutedVectorShuffle(*SVOp);
10136     } else if (LowV2Elements == LowV1Elements) {
10137       int SumV1Indices = 0, SumV2Indices = 0;
10138       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10139         if (SVOp->getMask()[i] >= NumElements)
10140           SumV2Indices += i;
10141         else if (SVOp->getMask()[i] >= 0)
10142           SumV1Indices += i;
10143       if (SumV2Indices < SumV1Indices) {
10144         return DAG.getCommutedVectorShuffle(*SVOp);
10145       } else if (SumV2Indices == SumV1Indices) {
10146         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10147         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10148           if (SVOp->getMask()[i] >= NumElements)
10149             NumV2OddIndices += i % 2;
10150           else if (SVOp->getMask()[i] >= 0)
10151             NumV1OddIndices += i % 2;
10152         if (NumV2OddIndices < NumV1OddIndices)
10153           return DAG.getCommutedVectorShuffle(*SVOp);
10154       }
10155     }
10156   }
10157
10158   // For each vector width, delegate to a specialized lowering routine.
10159   if (VT.getSizeInBits() == 128)
10160     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10161
10162   if (VT.getSizeInBits() == 256)
10163     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10164
10165   // Force AVX-512 vectors to be scalarized for now.
10166   // FIXME: Implement AVX-512 support!
10167   if (VT.getSizeInBits() == 512)
10168     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10169
10170   llvm_unreachable("Unimplemented!");
10171 }
10172
10173 // This function assumes its argument is a BUILD_VECTOR of constants or
10174 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10175 // true.
10176 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10177                                     unsigned &MaskValue) {
10178   MaskValue = 0;
10179   unsigned NumElems = BuildVector->getNumOperands();
10180   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10181   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10182   unsigned NumElemsInLane = NumElems / NumLanes;
10183
10184   // Blend for v16i16 should be symetric for the both lanes.
10185   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10186     SDValue EltCond = BuildVector->getOperand(i);
10187     SDValue SndLaneEltCond =
10188         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10189
10190     int Lane1Cond = -1, Lane2Cond = -1;
10191     if (isa<ConstantSDNode>(EltCond))
10192       Lane1Cond = !isZero(EltCond);
10193     if (isa<ConstantSDNode>(SndLaneEltCond))
10194       Lane2Cond = !isZero(SndLaneEltCond);
10195
10196     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10197       // Lane1Cond != 0, means we want the first argument.
10198       // Lane1Cond == 0, means we want the second argument.
10199       // The encoding of this argument is 0 for the first argument, 1
10200       // for the second. Therefore, invert the condition.
10201       MaskValue |= !Lane1Cond << i;
10202     else if (Lane1Cond < 0)
10203       MaskValue |= !Lane2Cond << i;
10204     else
10205       return false;
10206   }
10207   return true;
10208 }
10209
10210 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10211 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10212                                            const X86Subtarget *Subtarget,
10213                                            SelectionDAG &DAG) {
10214   SDValue Cond = Op.getOperand(0);
10215   SDValue LHS = Op.getOperand(1);
10216   SDValue RHS = Op.getOperand(2);
10217   SDLoc dl(Op);
10218   MVT VT = Op.getSimpleValueType();
10219
10220   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10221     return SDValue();
10222   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10223
10224   // Only non-legal VSELECTs reach this lowering, convert those into generic
10225   // shuffles and re-use the shuffle lowering path for blends.
10226   SmallVector<int, 32> Mask;
10227   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10228     SDValue CondElt = CondBV->getOperand(i);
10229     Mask.push_back(
10230         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10231   }
10232   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10233 }
10234
10235 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10236   // A vselect where all conditions and data are constants can be optimized into
10237   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10238   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10239       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10240       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10241     return SDValue();
10242
10243   // Try to lower this to a blend-style vector shuffle. This can handle all
10244   // constant condition cases.
10245   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10246     return BlendOp;
10247
10248   // Variable blends are only legal from SSE4.1 onward.
10249   if (!Subtarget->hasSSE41())
10250     return SDValue();
10251
10252   // Only some types will be legal on some subtargets. If we can emit a legal
10253   // VSELECT-matching blend, return Op, and but if we need to expand, return
10254   // a null value.
10255   switch (Op.getSimpleValueType().SimpleTy) {
10256   default:
10257     // Most of the vector types have blends past SSE4.1.
10258     return Op;
10259
10260   case MVT::v32i8:
10261     // The byte blends for AVX vectors were introduced only in AVX2.
10262     if (Subtarget->hasAVX2())
10263       return Op;
10264
10265     return SDValue();
10266
10267   case MVT::v8i16:
10268   case MVT::v16i16:
10269     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10270     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10271       return Op;
10272
10273     // FIXME: We should custom lower this by fixing the condition and using i8
10274     // blends.
10275     return SDValue();
10276   }
10277 }
10278
10279 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10280   MVT VT = Op.getSimpleValueType();
10281   SDLoc dl(Op);
10282
10283   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10284     return SDValue();
10285
10286   if (VT.getSizeInBits() == 8) {
10287     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10288                                   Op.getOperand(0), Op.getOperand(1));
10289     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10290                                   DAG.getValueType(VT));
10291     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10292   }
10293
10294   if (VT.getSizeInBits() == 16) {
10295     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10296     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10297     if (Idx == 0)
10298       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10299                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10300                                      DAG.getNode(ISD::BITCAST, dl,
10301                                                  MVT::v4i32,
10302                                                  Op.getOperand(0)),
10303                                      Op.getOperand(1)));
10304     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10305                                   Op.getOperand(0), Op.getOperand(1));
10306     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10307                                   DAG.getValueType(VT));
10308     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10309   }
10310
10311   if (VT == MVT::f32) {
10312     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10313     // the result back to FR32 register. It's only worth matching if the
10314     // result has a single use which is a store or a bitcast to i32.  And in
10315     // the case of a store, it's not worth it if the index is a constant 0,
10316     // because a MOVSSmr can be used instead, which is smaller and faster.
10317     if (!Op.hasOneUse())
10318       return SDValue();
10319     SDNode *User = *Op.getNode()->use_begin();
10320     if ((User->getOpcode() != ISD::STORE ||
10321          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10322           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10323         (User->getOpcode() != ISD::BITCAST ||
10324          User->getValueType(0) != MVT::i32))
10325       return SDValue();
10326     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10327                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10328                                               Op.getOperand(0)),
10329                                               Op.getOperand(1));
10330     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10331   }
10332
10333   if (VT == MVT::i32 || VT == MVT::i64) {
10334     // ExtractPS/pextrq works with constant index.
10335     if (isa<ConstantSDNode>(Op.getOperand(1)))
10336       return Op;
10337   }
10338   return SDValue();
10339 }
10340
10341 /// Extract one bit from mask vector, like v16i1 or v8i1.
10342 /// AVX-512 feature.
10343 SDValue
10344 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10345   SDValue Vec = Op.getOperand(0);
10346   SDLoc dl(Vec);
10347   MVT VecVT = Vec.getSimpleValueType();
10348   SDValue Idx = Op.getOperand(1);
10349   MVT EltVT = Op.getSimpleValueType();
10350
10351   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10352   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10353          "Unexpected vector type in ExtractBitFromMaskVector");
10354
10355   // variable index can't be handled in mask registers,
10356   // extend vector to VR512
10357   if (!isa<ConstantSDNode>(Idx)) {
10358     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10359     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10360     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10361                               ExtVT.getVectorElementType(), Ext, Idx);
10362     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10363   }
10364
10365   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10366   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10367   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10368     rc = getRegClassFor(MVT::v16i1);
10369   unsigned MaxSift = rc->getSize()*8 - 1;
10370   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10371                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10372   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10373                     DAG.getConstant(MaxSift, MVT::i8));
10374   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10375                        DAG.getIntPtrConstant(0));
10376 }
10377
10378 SDValue
10379 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10380                                            SelectionDAG &DAG) const {
10381   SDLoc dl(Op);
10382   SDValue Vec = Op.getOperand(0);
10383   MVT VecVT = Vec.getSimpleValueType();
10384   SDValue Idx = Op.getOperand(1);
10385
10386   if (Op.getSimpleValueType() == MVT::i1)
10387     return ExtractBitFromMaskVector(Op, DAG);
10388
10389   if (!isa<ConstantSDNode>(Idx)) {
10390     if (VecVT.is512BitVector() ||
10391         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10392          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10393
10394       MVT MaskEltVT =
10395         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10396       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10397                                     MaskEltVT.getSizeInBits());
10398
10399       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10400       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10401                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10402                                 Idx, DAG.getConstant(0, getPointerTy()));
10403       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10404       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10405                         Perm, DAG.getConstant(0, getPointerTy()));
10406     }
10407     return SDValue();
10408   }
10409
10410   // If this is a 256-bit vector result, first extract the 128-bit vector and
10411   // then extract the element from the 128-bit vector.
10412   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10413
10414     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10415     // Get the 128-bit vector.
10416     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10417     MVT EltVT = VecVT.getVectorElementType();
10418
10419     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10420
10421     //if (IdxVal >= NumElems/2)
10422     //  IdxVal -= NumElems/2;
10423     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10424     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10425                        DAG.getConstant(IdxVal, MVT::i32));
10426   }
10427
10428   assert(VecVT.is128BitVector() && "Unexpected vector length");
10429
10430   if (Subtarget->hasSSE41()) {
10431     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10432     if (Res.getNode())
10433       return Res;
10434   }
10435
10436   MVT VT = Op.getSimpleValueType();
10437   // TODO: handle v16i8.
10438   if (VT.getSizeInBits() == 16) {
10439     SDValue Vec = Op.getOperand(0);
10440     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10441     if (Idx == 0)
10442       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10443                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10444                                      DAG.getNode(ISD::BITCAST, dl,
10445                                                  MVT::v4i32, Vec),
10446                                      Op.getOperand(1)));
10447     // Transform it so it match pextrw which produces a 32-bit result.
10448     MVT EltVT = MVT::i32;
10449     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10450                                   Op.getOperand(0), Op.getOperand(1));
10451     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10452                                   DAG.getValueType(VT));
10453     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10454   }
10455
10456   if (VT.getSizeInBits() == 32) {
10457     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10458     if (Idx == 0)
10459       return Op;
10460
10461     // SHUFPS the element to the lowest double word, then movss.
10462     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10463     MVT VVT = Op.getOperand(0).getSimpleValueType();
10464     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10465                                        DAG.getUNDEF(VVT), Mask);
10466     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10467                        DAG.getIntPtrConstant(0));
10468   }
10469
10470   if (VT.getSizeInBits() == 64) {
10471     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10472     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10473     //        to match extract_elt for f64.
10474     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10475     if (Idx == 0)
10476       return Op;
10477
10478     // UNPCKHPD the element to the lowest double word, then movsd.
10479     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10480     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10481     int Mask[2] = { 1, -1 };
10482     MVT VVT = Op.getOperand(0).getSimpleValueType();
10483     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10484                                        DAG.getUNDEF(VVT), Mask);
10485     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10486                        DAG.getIntPtrConstant(0));
10487   }
10488
10489   return SDValue();
10490 }
10491
10492 /// Insert one bit to mask vector, like v16i1 or v8i1.
10493 /// AVX-512 feature.
10494 SDValue
10495 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10496   SDLoc dl(Op);
10497   SDValue Vec = Op.getOperand(0);
10498   SDValue Elt = Op.getOperand(1);
10499   SDValue Idx = Op.getOperand(2);
10500   MVT VecVT = Vec.getSimpleValueType();
10501
10502   if (!isa<ConstantSDNode>(Idx)) {
10503     // Non constant index. Extend source and destination,
10504     // insert element and then truncate the result.
10505     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10506     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10507     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10508       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10509       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10510     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10511   }
10512
10513   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10514   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10515   if (Vec.getOpcode() == ISD::UNDEF)
10516     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10517                        DAG.getConstant(IdxVal, MVT::i8));
10518   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10519   unsigned MaxSift = rc->getSize()*8 - 1;
10520   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10521                     DAG.getConstant(MaxSift, MVT::i8));
10522   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10523                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10524   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10525 }
10526
10527 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10528                                                   SelectionDAG &DAG) const {
10529   MVT VT = Op.getSimpleValueType();
10530   MVT EltVT = VT.getVectorElementType();
10531
10532   if (EltVT == MVT::i1)
10533     return InsertBitToMaskVector(Op, DAG);
10534
10535   SDLoc dl(Op);
10536   SDValue N0 = Op.getOperand(0);
10537   SDValue N1 = Op.getOperand(1);
10538   SDValue N2 = Op.getOperand(2);
10539   if (!isa<ConstantSDNode>(N2))
10540     return SDValue();
10541   auto *N2C = cast<ConstantSDNode>(N2);
10542   unsigned IdxVal = N2C->getZExtValue();
10543
10544   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10545   // into that, and then insert the subvector back into the result.
10546   if (VT.is256BitVector() || VT.is512BitVector()) {
10547     // With a 256-bit vector, we can insert into the zero element efficiently
10548     // using a blend if we have AVX or AVX2 and the right data type.
10549     if (VT.is256BitVector() && IdxVal == 0) {
10550       // TODO: It is worthwhile to cast integer to floating point and back
10551       // and incur a domain crossing penalty if that's what we'll end up
10552       // doing anyway after extracting to a 128-bit vector.
10553       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10554           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10555         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10556         N2 = DAG.getIntPtrConstant(1);
10557         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10558       }
10559     }
10560     
10561     // Get the desired 128-bit vector chunk.
10562     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10563
10564     // Insert the element into the desired chunk.
10565     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10566     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10567
10568     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10569                     DAG.getConstant(IdxIn128, MVT::i32));
10570
10571     // Insert the changed part back into the bigger vector
10572     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10573   }
10574   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10575
10576   if (Subtarget->hasSSE41()) {
10577     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10578       unsigned Opc;
10579       if (VT == MVT::v8i16) {
10580         Opc = X86ISD::PINSRW;
10581       } else {
10582         assert(VT == MVT::v16i8);
10583         Opc = X86ISD::PINSRB;
10584       }
10585
10586       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10587       // argument.
10588       if (N1.getValueType() != MVT::i32)
10589         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10590       if (N2.getValueType() != MVT::i32)
10591         N2 = DAG.getIntPtrConstant(IdxVal);
10592       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10593     }
10594
10595     if (EltVT == MVT::f32) {
10596       // Bits [7:6] of the constant are the source select. This will always be
10597       //   zero here. The DAG Combiner may combine an extract_elt index into
10598       //   these bits. For example (insert (extract, 3), 2) could be matched by
10599       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10600       // Bits [5:4] of the constant are the destination select. This is the
10601       //   value of the incoming immediate.
10602       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10603       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10604
10605       const Function *F = DAG.getMachineFunction().getFunction();
10606       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10607       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10608         // If this is an insertion of 32-bits into the low 32-bits of
10609         // a vector, we prefer to generate a blend with immediate rather
10610         // than an insertps. Blends are simpler operations in hardware and so
10611         // will always have equal or better performance than insertps.
10612         // But if optimizing for size and there's a load folding opportunity,
10613         // generate insertps because blendps does not have a 32-bit memory
10614         // operand form.
10615         N2 = DAG.getIntPtrConstant(1);
10616         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10617         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10618       }
10619       N2 = DAG.getIntPtrConstant(IdxVal << 4);
10620       // Create this as a scalar to vector..
10621       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10622       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10623     }
10624
10625     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10626       // PINSR* works with constant index.
10627       return Op;
10628     }
10629   }
10630
10631   if (EltVT == MVT::i8)
10632     return SDValue();
10633
10634   if (EltVT.getSizeInBits() == 16) {
10635     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10636     // as its second argument.
10637     if (N1.getValueType() != MVT::i32)
10638       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10639     if (N2.getValueType() != MVT::i32)
10640       N2 = DAG.getIntPtrConstant(IdxVal);
10641     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10642   }
10643   return SDValue();
10644 }
10645
10646 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10647   SDLoc dl(Op);
10648   MVT OpVT = Op.getSimpleValueType();
10649
10650   // If this is a 256-bit vector result, first insert into a 128-bit
10651   // vector and then insert into the 256-bit vector.
10652   if (!OpVT.is128BitVector()) {
10653     // Insert into a 128-bit vector.
10654     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10655     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10656                                  OpVT.getVectorNumElements() / SizeFactor);
10657
10658     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10659
10660     // Insert the 128-bit vector.
10661     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10662   }
10663
10664   if (OpVT == MVT::v1i64 &&
10665       Op.getOperand(0).getValueType() == MVT::i64)
10666     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10667
10668   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10669   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10670   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10671                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10672 }
10673
10674 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10675 // a simple subregister reference or explicit instructions to grab
10676 // upper bits of a vector.
10677 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10678                                       SelectionDAG &DAG) {
10679   SDLoc dl(Op);
10680   SDValue In =  Op.getOperand(0);
10681   SDValue Idx = Op.getOperand(1);
10682   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10683   MVT ResVT   = Op.getSimpleValueType();
10684   MVT InVT    = In.getSimpleValueType();
10685
10686   if (Subtarget->hasFp256()) {
10687     if (ResVT.is128BitVector() &&
10688         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10689         isa<ConstantSDNode>(Idx)) {
10690       return Extract128BitVector(In, IdxVal, DAG, dl);
10691     }
10692     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10693         isa<ConstantSDNode>(Idx)) {
10694       return Extract256BitVector(In, IdxVal, DAG, dl);
10695     }
10696   }
10697   return SDValue();
10698 }
10699
10700 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10701 // simple superregister reference or explicit instructions to insert
10702 // the upper bits of a vector.
10703 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10704                                      SelectionDAG &DAG) {
10705   if (!Subtarget->hasAVX())
10706     return SDValue();
10707
10708   SDLoc dl(Op);
10709   SDValue Vec = Op.getOperand(0);
10710   SDValue SubVec = Op.getOperand(1);
10711   SDValue Idx = Op.getOperand(2);
10712
10713   if (!isa<ConstantSDNode>(Idx))
10714     return SDValue();
10715
10716   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10717   MVT OpVT = Op.getSimpleValueType();
10718   MVT SubVecVT = SubVec.getSimpleValueType();
10719
10720   // Fold two 16-byte subvector loads into one 32-byte load:
10721   // (insert_subvector (insert_subvector undef, (load addr), 0),
10722   //                   (load addr + 16), Elts/2)
10723   // --> load32 addr
10724   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10725       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10726       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10727       !Subtarget->isUnalignedMem32Slow()) {
10728     SDValue SubVec2 = Vec.getOperand(1);
10729     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10730       if (Idx2->getZExtValue() == 0) {
10731         SDValue Ops[] = { SubVec2, SubVec };
10732         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10733         if (LD.getNode())
10734           return LD;
10735       }
10736     }
10737   }
10738
10739   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10740       SubVecVT.is128BitVector())
10741     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10742
10743   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10744     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10745
10746   if (OpVT.getVectorElementType() == MVT::i1) {
10747     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10748       return Op;
10749     SDValue ZeroIdx = DAG.getIntPtrConstant(0);
10750     SDValue Undef = DAG.getUNDEF(OpVT);
10751     unsigned NumElems = OpVT.getVectorNumElements();
10752     SDValue ShiftBits = DAG.getConstant(NumElems/2, MVT::i8);
10753
10754     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10755       // Zero upper bits of the Vec
10756       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10757       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10758
10759       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10760                                  SubVec, ZeroIdx);
10761       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10762       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10763     }
10764     if (IdxVal == 0) {
10765       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10766                                  SubVec, ZeroIdx);
10767       // Zero upper bits of the Vec2
10768       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10769       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10770       // Zero lower bits of the Vec
10771       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10772       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10773       // Merge them together
10774       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10775     }
10776   }
10777   return SDValue();
10778 }
10779
10780 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10781 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10782 // one of the above mentioned nodes. It has to be wrapped because otherwise
10783 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10784 // be used to form addressing mode. These wrapped nodes will be selected
10785 // into MOV32ri.
10786 SDValue
10787 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10788   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10789
10790   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10791   // global base reg.
10792   unsigned char OpFlag = 0;
10793   unsigned WrapperKind = X86ISD::Wrapper;
10794   CodeModel::Model M = DAG.getTarget().getCodeModel();
10795
10796   if (Subtarget->isPICStyleRIPRel() &&
10797       (M == CodeModel::Small || M == CodeModel::Kernel))
10798     WrapperKind = X86ISD::WrapperRIP;
10799   else if (Subtarget->isPICStyleGOT())
10800     OpFlag = X86II::MO_GOTOFF;
10801   else if (Subtarget->isPICStyleStubPIC())
10802     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10803
10804   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10805                                              CP->getAlignment(),
10806                                              CP->getOffset(), OpFlag);
10807   SDLoc DL(CP);
10808   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10809   // With PIC, the address is actually $g + Offset.
10810   if (OpFlag) {
10811     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10812                          DAG.getNode(X86ISD::GlobalBaseReg,
10813                                      SDLoc(), getPointerTy()),
10814                          Result);
10815   }
10816
10817   return Result;
10818 }
10819
10820 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10821   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10822
10823   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10824   // global base reg.
10825   unsigned char OpFlag = 0;
10826   unsigned WrapperKind = X86ISD::Wrapper;
10827   CodeModel::Model M = DAG.getTarget().getCodeModel();
10828
10829   if (Subtarget->isPICStyleRIPRel() &&
10830       (M == CodeModel::Small || M == CodeModel::Kernel))
10831     WrapperKind = X86ISD::WrapperRIP;
10832   else if (Subtarget->isPICStyleGOT())
10833     OpFlag = X86II::MO_GOTOFF;
10834   else if (Subtarget->isPICStyleStubPIC())
10835     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10836
10837   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10838                                           OpFlag);
10839   SDLoc DL(JT);
10840   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10841
10842   // With PIC, the address is actually $g + Offset.
10843   if (OpFlag)
10844     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10845                          DAG.getNode(X86ISD::GlobalBaseReg,
10846                                      SDLoc(), getPointerTy()),
10847                          Result);
10848
10849   return Result;
10850 }
10851
10852 SDValue
10853 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10854   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10855
10856   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10857   // global base reg.
10858   unsigned char OpFlag = 0;
10859   unsigned WrapperKind = X86ISD::Wrapper;
10860   CodeModel::Model M = DAG.getTarget().getCodeModel();
10861
10862   if (Subtarget->isPICStyleRIPRel() &&
10863       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10864     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10865       OpFlag = X86II::MO_GOTPCREL;
10866     WrapperKind = X86ISD::WrapperRIP;
10867   } else if (Subtarget->isPICStyleGOT()) {
10868     OpFlag = X86II::MO_GOT;
10869   } else if (Subtarget->isPICStyleStubPIC()) {
10870     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10871   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10872     OpFlag = X86II::MO_DARWIN_NONLAZY;
10873   }
10874
10875   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10876
10877   SDLoc DL(Op);
10878   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10879
10880   // With PIC, the address is actually $g + Offset.
10881   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10882       !Subtarget->is64Bit()) {
10883     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10884                          DAG.getNode(X86ISD::GlobalBaseReg,
10885                                      SDLoc(), getPointerTy()),
10886                          Result);
10887   }
10888
10889   // For symbols that require a load from a stub to get the address, emit the
10890   // load.
10891   if (isGlobalStubReference(OpFlag))
10892     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10893                          MachinePointerInfo::getGOT(), false, false, false, 0);
10894
10895   return Result;
10896 }
10897
10898 SDValue
10899 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10900   // Create the TargetBlockAddressAddress node.
10901   unsigned char OpFlags =
10902     Subtarget->ClassifyBlockAddressReference();
10903   CodeModel::Model M = DAG.getTarget().getCodeModel();
10904   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10905   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10906   SDLoc dl(Op);
10907   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10908                                              OpFlags);
10909
10910   if (Subtarget->isPICStyleRIPRel() &&
10911       (M == CodeModel::Small || M == CodeModel::Kernel))
10912     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10913   else
10914     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10915
10916   // With PIC, the address is actually $g + Offset.
10917   if (isGlobalRelativeToPICBase(OpFlags)) {
10918     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10919                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10920                          Result);
10921   }
10922
10923   return Result;
10924 }
10925
10926 SDValue
10927 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10928                                       int64_t Offset, SelectionDAG &DAG) const {
10929   // Create the TargetGlobalAddress node, folding in the constant
10930   // offset if it is legal.
10931   unsigned char OpFlags =
10932       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10933   CodeModel::Model M = DAG.getTarget().getCodeModel();
10934   SDValue Result;
10935   if (OpFlags == X86II::MO_NO_FLAG &&
10936       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10937     // A direct static reference to a global.
10938     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10939     Offset = 0;
10940   } else {
10941     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10942   }
10943
10944   if (Subtarget->isPICStyleRIPRel() &&
10945       (M == CodeModel::Small || M == CodeModel::Kernel))
10946     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10947   else
10948     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10949
10950   // With PIC, the address is actually $g + Offset.
10951   if (isGlobalRelativeToPICBase(OpFlags)) {
10952     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10953                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10954                          Result);
10955   }
10956
10957   // For globals that require a load from a stub to get the address, emit the
10958   // load.
10959   if (isGlobalStubReference(OpFlags))
10960     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10961                          MachinePointerInfo::getGOT(), false, false, false, 0);
10962
10963   // If there was a non-zero offset that we didn't fold, create an explicit
10964   // addition for it.
10965   if (Offset != 0)
10966     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10967                          DAG.getConstant(Offset, getPointerTy()));
10968
10969   return Result;
10970 }
10971
10972 SDValue
10973 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10974   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10975   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10976   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10977 }
10978
10979 static SDValue
10980 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10981            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10982            unsigned char OperandFlags, bool LocalDynamic = false) {
10983   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10984   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10985   SDLoc dl(GA);
10986   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10987                                            GA->getValueType(0),
10988                                            GA->getOffset(),
10989                                            OperandFlags);
10990
10991   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10992                                            : X86ISD::TLSADDR;
10993
10994   if (InFlag) {
10995     SDValue Ops[] = { Chain,  TGA, *InFlag };
10996     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10997   } else {
10998     SDValue Ops[]  = { Chain, TGA };
10999     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11000   }
11001
11002   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11003   MFI->setAdjustsStack(true);
11004   MFI->setHasCalls(true);
11005
11006   SDValue Flag = Chain.getValue(1);
11007   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11008 }
11009
11010 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11011 static SDValue
11012 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11013                                 const EVT PtrVT) {
11014   SDValue InFlag;
11015   SDLoc dl(GA);  // ? function entry point might be better
11016   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11017                                    DAG.getNode(X86ISD::GlobalBaseReg,
11018                                                SDLoc(), PtrVT), InFlag);
11019   InFlag = Chain.getValue(1);
11020
11021   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11022 }
11023
11024 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11025 static SDValue
11026 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11027                                 const EVT PtrVT) {
11028   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11029                     X86::RAX, X86II::MO_TLSGD);
11030 }
11031
11032 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11033                                            SelectionDAG &DAG,
11034                                            const EVT PtrVT,
11035                                            bool is64Bit) {
11036   SDLoc dl(GA);
11037
11038   // Get the start address of the TLS block for this module.
11039   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11040       .getInfo<X86MachineFunctionInfo>();
11041   MFI->incNumLocalDynamicTLSAccesses();
11042
11043   SDValue Base;
11044   if (is64Bit) {
11045     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11046                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11047   } else {
11048     SDValue InFlag;
11049     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11050         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11051     InFlag = Chain.getValue(1);
11052     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11053                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11054   }
11055
11056   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11057   // of Base.
11058
11059   // Build x@dtpoff.
11060   unsigned char OperandFlags = X86II::MO_DTPOFF;
11061   unsigned WrapperKind = X86ISD::Wrapper;
11062   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11063                                            GA->getValueType(0),
11064                                            GA->getOffset(), OperandFlags);
11065   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11066
11067   // Add x@dtpoff with the base.
11068   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11069 }
11070
11071 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11072 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11073                                    const EVT PtrVT, TLSModel::Model model,
11074                                    bool is64Bit, bool isPIC) {
11075   SDLoc dl(GA);
11076
11077   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11078   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11079                                                          is64Bit ? 257 : 256));
11080
11081   SDValue ThreadPointer =
11082       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
11083                   MachinePointerInfo(Ptr), false, false, false, 0);
11084
11085   unsigned char OperandFlags = 0;
11086   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11087   // initialexec.
11088   unsigned WrapperKind = X86ISD::Wrapper;
11089   if (model == TLSModel::LocalExec) {
11090     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11091   } else if (model == TLSModel::InitialExec) {
11092     if (is64Bit) {
11093       OperandFlags = X86II::MO_GOTTPOFF;
11094       WrapperKind = X86ISD::WrapperRIP;
11095     } else {
11096       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11097     }
11098   } else {
11099     llvm_unreachable("Unexpected model");
11100   }
11101
11102   // emit "addl x@ntpoff,%eax" (local exec)
11103   // or "addl x@indntpoff,%eax" (initial exec)
11104   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11105   SDValue TGA =
11106       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11107                                  GA->getOffset(), OperandFlags);
11108   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11109
11110   if (model == TLSModel::InitialExec) {
11111     if (isPIC && !is64Bit) {
11112       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11113                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11114                            Offset);
11115     }
11116
11117     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11118                          MachinePointerInfo::getGOT(), false, false, false, 0);
11119   }
11120
11121   // The address of the thread local variable is the add of the thread
11122   // pointer with the offset of the variable.
11123   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11124 }
11125
11126 SDValue
11127 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11128
11129   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11130   const GlobalValue *GV = GA->getGlobal();
11131
11132   if (Subtarget->isTargetELF()) {
11133     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11134
11135     switch (model) {
11136       case TLSModel::GeneralDynamic:
11137         if (Subtarget->is64Bit())
11138           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11139         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11140       case TLSModel::LocalDynamic:
11141         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11142                                            Subtarget->is64Bit());
11143       case TLSModel::InitialExec:
11144       case TLSModel::LocalExec:
11145         return LowerToTLSExecModel(
11146             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11147             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11148     }
11149     llvm_unreachable("Unknown TLS model.");
11150   }
11151
11152   if (Subtarget->isTargetDarwin()) {
11153     // Darwin only has one model of TLS.  Lower to that.
11154     unsigned char OpFlag = 0;
11155     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11156                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11157
11158     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11159     // global base reg.
11160     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11161                  !Subtarget->is64Bit();
11162     if (PIC32)
11163       OpFlag = X86II::MO_TLVP_PIC_BASE;
11164     else
11165       OpFlag = X86II::MO_TLVP;
11166     SDLoc DL(Op);
11167     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11168                                                 GA->getValueType(0),
11169                                                 GA->getOffset(), OpFlag);
11170     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11171
11172     // With PIC32, the address is actually $g + Offset.
11173     if (PIC32)
11174       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11175                            DAG.getNode(X86ISD::GlobalBaseReg,
11176                                        SDLoc(), getPointerTy()),
11177                            Offset);
11178
11179     // Lowering the machine isd will make sure everything is in the right
11180     // location.
11181     SDValue Chain = DAG.getEntryNode();
11182     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11183     SDValue Args[] = { Chain, Offset };
11184     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11185
11186     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11187     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11188     MFI->setAdjustsStack(true);
11189
11190     // And our return value (tls address) is in the standard call return value
11191     // location.
11192     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11193     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11194                               Chain.getValue(1));
11195   }
11196
11197   if (Subtarget->isTargetKnownWindowsMSVC() ||
11198       Subtarget->isTargetWindowsGNU()) {
11199     // Just use the implicit TLS architecture
11200     // Need to generate someting similar to:
11201     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11202     //                                  ; from TEB
11203     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11204     //   mov     rcx, qword [rdx+rcx*8]
11205     //   mov     eax, .tls$:tlsvar
11206     //   [rax+rcx] contains the address
11207     // Windows 64bit: gs:0x58
11208     // Windows 32bit: fs:__tls_array
11209
11210     SDLoc dl(GA);
11211     SDValue Chain = DAG.getEntryNode();
11212
11213     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11214     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11215     // use its literal value of 0x2C.
11216     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11217                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11218                                                              256)
11219                                         : Type::getInt32PtrTy(*DAG.getContext(),
11220                                                               257));
11221
11222     SDValue TlsArray =
11223         Subtarget->is64Bit()
11224             ? DAG.getIntPtrConstant(0x58)
11225             : (Subtarget->isTargetWindowsGNU()
11226                    ? DAG.getIntPtrConstant(0x2C)
11227                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11228
11229     SDValue ThreadPointer =
11230         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11231                     MachinePointerInfo(Ptr), false, false, false, 0);
11232
11233     // Load the _tls_index variable
11234     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11235     if (Subtarget->is64Bit())
11236       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11237                            IDX, MachinePointerInfo(), MVT::i32,
11238                            false, false, false, 0);
11239     else
11240       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11241                         false, false, false, 0);
11242
11243     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11244                                     getPointerTy());
11245     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11246
11247     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11248     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11249                       false, false, false, 0);
11250
11251     // Get the offset of start of .tls section
11252     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11253                                              GA->getValueType(0),
11254                                              GA->getOffset(), X86II::MO_SECREL);
11255     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11256
11257     // The address of the thread local variable is the add of the thread
11258     // pointer with the offset of the variable.
11259     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11260   }
11261
11262   llvm_unreachable("TLS not implemented for this target.");
11263 }
11264
11265 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11266 /// and take a 2 x i32 value to shift plus a shift amount.
11267 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11268   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11269   MVT VT = Op.getSimpleValueType();
11270   unsigned VTBits = VT.getSizeInBits();
11271   SDLoc dl(Op);
11272   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11273   SDValue ShOpLo = Op.getOperand(0);
11274   SDValue ShOpHi = Op.getOperand(1);
11275   SDValue ShAmt  = Op.getOperand(2);
11276   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11277   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11278   // during isel.
11279   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11280                                   DAG.getConstant(VTBits - 1, MVT::i8));
11281   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11282                                      DAG.getConstant(VTBits - 1, MVT::i8))
11283                        : DAG.getConstant(0, VT);
11284
11285   SDValue Tmp2, Tmp3;
11286   if (Op.getOpcode() == ISD::SHL_PARTS) {
11287     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11288     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11289   } else {
11290     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11291     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11292   }
11293
11294   // If the shift amount is larger or equal than the width of a part we can't
11295   // rely on the results of shld/shrd. Insert a test and select the appropriate
11296   // values for large shift amounts.
11297   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11298                                 DAG.getConstant(VTBits, MVT::i8));
11299   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11300                              AndNode, DAG.getConstant(0, MVT::i8));
11301
11302   SDValue Hi, Lo;
11303   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11304   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11305   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11306
11307   if (Op.getOpcode() == ISD::SHL_PARTS) {
11308     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11309     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11310   } else {
11311     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11312     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11313   }
11314
11315   SDValue Ops[2] = { Lo, Hi };
11316   return DAG.getMergeValues(Ops, dl);
11317 }
11318
11319 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11320                                            SelectionDAG &DAG) const {
11321   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11322   SDLoc dl(Op);
11323
11324   if (SrcVT.isVector()) {
11325     if (SrcVT.getVectorElementType() == MVT::i1) {
11326       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11327       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11328                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11329                                      Op.getOperand(0)));
11330     }
11331     return SDValue();
11332   }
11333
11334   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11335          "Unknown SINT_TO_FP to lower!");
11336
11337   // These are really Legal; return the operand so the caller accepts it as
11338   // Legal.
11339   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11340     return Op;
11341   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11342       Subtarget->is64Bit()) {
11343     return Op;
11344   }
11345
11346   unsigned Size = SrcVT.getSizeInBits()/8;
11347   MachineFunction &MF = DAG.getMachineFunction();
11348   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11349   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11350   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11351                                StackSlot,
11352                                MachinePointerInfo::getFixedStack(SSFI),
11353                                false, false, 0);
11354   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11355 }
11356
11357 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11358                                      SDValue StackSlot,
11359                                      SelectionDAG &DAG) const {
11360   // Build the FILD
11361   SDLoc DL(Op);
11362   SDVTList Tys;
11363   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11364   if (useSSE)
11365     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11366   else
11367     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11368
11369   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11370
11371   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11372   MachineMemOperand *MMO;
11373   if (FI) {
11374     int SSFI = FI->getIndex();
11375     MMO =
11376       DAG.getMachineFunction()
11377       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11378                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11379   } else {
11380     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11381     StackSlot = StackSlot.getOperand(1);
11382   }
11383   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11384   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11385                                            X86ISD::FILD, DL,
11386                                            Tys, Ops, SrcVT, MMO);
11387
11388   if (useSSE) {
11389     Chain = Result.getValue(1);
11390     SDValue InFlag = Result.getValue(2);
11391
11392     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11393     // shouldn't be necessary except that RFP cannot be live across
11394     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11395     MachineFunction &MF = DAG.getMachineFunction();
11396     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11397     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11398     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11399     Tys = DAG.getVTList(MVT::Other);
11400     SDValue Ops[] = {
11401       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11402     };
11403     MachineMemOperand *MMO =
11404       DAG.getMachineFunction()
11405       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11406                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11407
11408     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11409                                     Ops, Op.getValueType(), MMO);
11410     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11411                          MachinePointerInfo::getFixedStack(SSFI),
11412                          false, false, false, 0);
11413   }
11414
11415   return Result;
11416 }
11417
11418 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11419 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11420                                                SelectionDAG &DAG) const {
11421   // This algorithm is not obvious. Here it is what we're trying to output:
11422   /*
11423      movq       %rax,  %xmm0
11424      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11425      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11426      #ifdef __SSE3__
11427        haddpd   %xmm0, %xmm0
11428      #else
11429        pshufd   $0x4e, %xmm0, %xmm1
11430        addpd    %xmm1, %xmm0
11431      #endif
11432   */
11433
11434   SDLoc dl(Op);
11435   LLVMContext *Context = DAG.getContext();
11436
11437   // Build some magic constants.
11438   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11439   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11440   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11441
11442   SmallVector<Constant*,2> CV1;
11443   CV1.push_back(
11444     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11445                                       APInt(64, 0x4330000000000000ULL))));
11446   CV1.push_back(
11447     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11448                                       APInt(64, 0x4530000000000000ULL))));
11449   Constant *C1 = ConstantVector::get(CV1);
11450   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11451
11452   // Load the 64-bit value into an XMM register.
11453   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11454                             Op.getOperand(0));
11455   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11456                               MachinePointerInfo::getConstantPool(),
11457                               false, false, false, 16);
11458   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11459                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11460                               CLod0);
11461
11462   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11463                               MachinePointerInfo::getConstantPool(),
11464                               false, false, false, 16);
11465   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11466   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11467   SDValue Result;
11468
11469   if (Subtarget->hasSSE3()) {
11470     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11471     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11472   } else {
11473     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11474     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11475                                            S2F, 0x4E, DAG);
11476     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11477                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11478                          Sub);
11479   }
11480
11481   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11482                      DAG.getIntPtrConstant(0));
11483 }
11484
11485 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11486 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11487                                                SelectionDAG &DAG) const {
11488   SDLoc dl(Op);
11489   // FP constant to bias correct the final result.
11490   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11491                                    MVT::f64);
11492
11493   // Load the 32-bit value into an XMM register.
11494   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11495                              Op.getOperand(0));
11496
11497   // Zero out the upper parts of the register.
11498   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11499
11500   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11501                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11502                      DAG.getIntPtrConstant(0));
11503
11504   // Or the load with the bias.
11505   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11506                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11507                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11508                                                    MVT::v2f64, Load)),
11509                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11510                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11511                                                    MVT::v2f64, Bias)));
11512   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11513                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11514                    DAG.getIntPtrConstant(0));
11515
11516   // Subtract the bias.
11517   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11518
11519   // Handle final rounding.
11520   EVT DestVT = Op.getValueType();
11521
11522   if (DestVT.bitsLT(MVT::f64))
11523     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11524                        DAG.getIntPtrConstant(0));
11525   if (DestVT.bitsGT(MVT::f64))
11526     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11527
11528   // Handle final rounding.
11529   return Sub;
11530 }
11531
11532 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11533                                      const X86Subtarget &Subtarget) {
11534   // The algorithm is the following:
11535   // #ifdef __SSE4_1__
11536   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11537   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11538   //                                 (uint4) 0x53000000, 0xaa);
11539   // #else
11540   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11541   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11542   // #endif
11543   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11544   //     return (float4) lo + fhi;
11545
11546   SDLoc DL(Op);
11547   SDValue V = Op->getOperand(0);
11548   EVT VecIntVT = V.getValueType();
11549   bool Is128 = VecIntVT == MVT::v4i32;
11550   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11551   // If we convert to something else than the supported type, e.g., to v4f64,
11552   // abort early.
11553   if (VecFloatVT != Op->getValueType(0))
11554     return SDValue();
11555
11556   unsigned NumElts = VecIntVT.getVectorNumElements();
11557   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11558          "Unsupported custom type");
11559   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11560
11561   // In the #idef/#else code, we have in common:
11562   // - The vector of constants:
11563   // -- 0x4b000000
11564   // -- 0x53000000
11565   // - A shift:
11566   // -- v >> 16
11567
11568   // Create the splat vector for 0x4b000000.
11569   SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
11570   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11571                            CstLow, CstLow, CstLow, CstLow};
11572   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11573                                   makeArrayRef(&CstLowArray[0], NumElts));
11574   // Create the splat vector for 0x53000000.
11575   SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
11576   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11577                             CstHigh, CstHigh, CstHigh, CstHigh};
11578   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11579                                    makeArrayRef(&CstHighArray[0], NumElts));
11580
11581   // Create the right shift.
11582   SDValue CstShift = DAG.getConstant(16, MVT::i32);
11583   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11584                              CstShift, CstShift, CstShift, CstShift};
11585   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11586                                     makeArrayRef(&CstShiftArray[0], NumElts));
11587   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11588
11589   SDValue Low, High;
11590   if (Subtarget.hasSSE41()) {
11591     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11592     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11593     SDValue VecCstLowBitcast =
11594         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11595     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11596     // Low will be bitcasted right away, so do not bother bitcasting back to its
11597     // original type.
11598     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11599                       VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
11600     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11601     //                                 (uint4) 0x53000000, 0xaa);
11602     SDValue VecCstHighBitcast =
11603         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11604     SDValue VecShiftBitcast =
11605         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11606     // High will be bitcasted right away, so do not bother bitcasting back to
11607     // its original type.
11608     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11609                        VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
11610   } else {
11611     SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
11612     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11613                                      CstMask, CstMask, CstMask);
11614     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11615     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11616     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11617
11618     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11619     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11620   }
11621
11622   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11623   SDValue CstFAdd = DAG.getConstantFP(
11624       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
11625   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11626                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11627   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11628                                    makeArrayRef(&CstFAddArray[0], NumElts));
11629
11630   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11631   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11632   SDValue FHigh =
11633       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11634   //     return (float4) lo + fhi;
11635   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11636   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11637 }
11638
11639 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11640                                                SelectionDAG &DAG) const {
11641   SDValue N0 = Op.getOperand(0);
11642   MVT SVT = N0.getSimpleValueType();
11643   SDLoc dl(Op);
11644
11645   switch (SVT.SimpleTy) {
11646   default:
11647     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11648   case MVT::v4i8:
11649   case MVT::v4i16:
11650   case MVT::v8i8:
11651   case MVT::v8i16: {
11652     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11653     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11654                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11655   }
11656   case MVT::v4i32:
11657   case MVT::v8i32:
11658     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11659   }
11660   llvm_unreachable(nullptr);
11661 }
11662
11663 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11664                                            SelectionDAG &DAG) const {
11665   SDValue N0 = Op.getOperand(0);
11666   SDLoc dl(Op);
11667
11668   if (Op.getValueType().isVector())
11669     return lowerUINT_TO_FP_vec(Op, DAG);
11670
11671   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11672   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11673   // the optimization here.
11674   if (DAG.SignBitIsZero(N0))
11675     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11676
11677   MVT SrcVT = N0.getSimpleValueType();
11678   MVT DstVT = Op.getSimpleValueType();
11679   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11680     return LowerUINT_TO_FP_i64(Op, DAG);
11681   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11682     return LowerUINT_TO_FP_i32(Op, DAG);
11683   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11684     return SDValue();
11685
11686   // Make a 64-bit buffer, and use it to build an FILD.
11687   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11688   if (SrcVT == MVT::i32) {
11689     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11690     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11691                                      getPointerTy(), StackSlot, WordOff);
11692     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11693                                   StackSlot, MachinePointerInfo(),
11694                                   false, false, 0);
11695     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11696                                   OffsetSlot, MachinePointerInfo(),
11697                                   false, false, 0);
11698     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11699     return Fild;
11700   }
11701
11702   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11703   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11704                                StackSlot, MachinePointerInfo(),
11705                                false, false, 0);
11706   // For i64 source, we need to add the appropriate power of 2 if the input
11707   // was negative.  This is the same as the optimization in
11708   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11709   // we must be careful to do the computation in x87 extended precision, not
11710   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11711   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11712   MachineMemOperand *MMO =
11713     DAG.getMachineFunction()
11714     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11715                           MachineMemOperand::MOLoad, 8, 8);
11716
11717   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11718   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11719   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11720                                          MVT::i64, MMO);
11721
11722   APInt FF(32, 0x5F800000ULL);
11723
11724   // Check whether the sign bit is set.
11725   SDValue SignSet = DAG.getSetCC(dl,
11726                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11727                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11728                                  ISD::SETLT);
11729
11730   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11731   SDValue FudgePtr = DAG.getConstantPool(
11732                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11733                                          getPointerTy());
11734
11735   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11736   SDValue Zero = DAG.getIntPtrConstant(0);
11737   SDValue Four = DAG.getIntPtrConstant(4);
11738   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11739                                Zero, Four);
11740   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11741
11742   // Load the value out, extending it from f32 to f80.
11743   // FIXME: Avoid the extend by constructing the right constant pool?
11744   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11745                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11746                                  MVT::f32, false, false, false, 4);
11747   // Extend everything to 80 bits to force it to be done on x87.
11748   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11749   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11750 }
11751
11752 std::pair<SDValue,SDValue>
11753 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11754                                     bool IsSigned, bool IsReplace) const {
11755   SDLoc DL(Op);
11756
11757   EVT DstTy = Op.getValueType();
11758
11759   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11760     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11761     DstTy = MVT::i64;
11762   }
11763
11764   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11765          DstTy.getSimpleVT() >= MVT::i16 &&
11766          "Unknown FP_TO_INT to lower!");
11767
11768   // These are really Legal.
11769   if (DstTy == MVT::i32 &&
11770       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11771     return std::make_pair(SDValue(), SDValue());
11772   if (Subtarget->is64Bit() &&
11773       DstTy == MVT::i64 &&
11774       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11775     return std::make_pair(SDValue(), SDValue());
11776
11777   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11778   // stack slot, or into the FTOL runtime function.
11779   MachineFunction &MF = DAG.getMachineFunction();
11780   unsigned MemSize = DstTy.getSizeInBits()/8;
11781   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11782   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11783
11784   unsigned Opc;
11785   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11786     Opc = X86ISD::WIN_FTOL;
11787   else
11788     switch (DstTy.getSimpleVT().SimpleTy) {
11789     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11790     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11791     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11792     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11793     }
11794
11795   SDValue Chain = DAG.getEntryNode();
11796   SDValue Value = Op.getOperand(0);
11797   EVT TheVT = Op.getOperand(0).getValueType();
11798   // FIXME This causes a redundant load/store if the SSE-class value is already
11799   // in memory, such as if it is on the callstack.
11800   if (isScalarFPTypeInSSEReg(TheVT)) {
11801     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11802     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11803                          MachinePointerInfo::getFixedStack(SSFI),
11804                          false, false, 0);
11805     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11806     SDValue Ops[] = {
11807       Chain, StackSlot, DAG.getValueType(TheVT)
11808     };
11809
11810     MachineMemOperand *MMO =
11811       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11812                               MachineMemOperand::MOLoad, MemSize, MemSize);
11813     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11814     Chain = Value.getValue(1);
11815     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11816     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11817   }
11818
11819   MachineMemOperand *MMO =
11820     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11821                             MachineMemOperand::MOStore, MemSize, MemSize);
11822
11823   if (Opc != X86ISD::WIN_FTOL) {
11824     // Build the FP_TO_INT*_IN_MEM
11825     SDValue Ops[] = { Chain, Value, StackSlot };
11826     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11827                                            Ops, DstTy, MMO);
11828     return std::make_pair(FIST, StackSlot);
11829   } else {
11830     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11831       DAG.getVTList(MVT::Other, MVT::Glue),
11832       Chain, Value);
11833     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11834       MVT::i32, ftol.getValue(1));
11835     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11836       MVT::i32, eax.getValue(2));
11837     SDValue Ops[] = { eax, edx };
11838     SDValue pair = IsReplace
11839       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11840       : DAG.getMergeValues(Ops, DL);
11841     return std::make_pair(pair, SDValue());
11842   }
11843 }
11844
11845 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11846                               const X86Subtarget *Subtarget) {
11847   MVT VT = Op->getSimpleValueType(0);
11848   SDValue In = Op->getOperand(0);
11849   MVT InVT = In.getSimpleValueType();
11850   SDLoc dl(Op);
11851
11852   // Optimize vectors in AVX mode:
11853   //
11854   //   v8i16 -> v8i32
11855   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11856   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11857   //   Concat upper and lower parts.
11858   //
11859   //   v4i32 -> v4i64
11860   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11861   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11862   //   Concat upper and lower parts.
11863   //
11864
11865   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11866       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11867       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11868     return SDValue();
11869
11870   if (Subtarget->hasInt256())
11871     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11872
11873   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11874   SDValue Undef = DAG.getUNDEF(InVT);
11875   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11876   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11877   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11878
11879   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11880                              VT.getVectorNumElements()/2);
11881
11882   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11883   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11884
11885   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11886 }
11887
11888 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11889                                         SelectionDAG &DAG) {
11890   MVT VT = Op->getSimpleValueType(0);
11891   SDValue In = Op->getOperand(0);
11892   MVT InVT = In.getSimpleValueType();
11893   SDLoc DL(Op);
11894   unsigned int NumElts = VT.getVectorNumElements();
11895   if (NumElts != 8 && NumElts != 16)
11896     return SDValue();
11897
11898   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11899     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11900
11901   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11902   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11903   // Now we have only mask extension
11904   assert(InVT.getVectorElementType() == MVT::i1);
11905   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11906   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11907   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11908   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11909   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11910                            MachinePointerInfo::getConstantPool(),
11911                            false, false, false, Alignment);
11912
11913   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11914   if (VT.is512BitVector())
11915     return Brcst;
11916   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11917 }
11918
11919 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11920                                SelectionDAG &DAG) {
11921   if (Subtarget->hasFp256()) {
11922     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11923     if (Res.getNode())
11924       return Res;
11925   }
11926
11927   return SDValue();
11928 }
11929
11930 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11931                                 SelectionDAG &DAG) {
11932   SDLoc DL(Op);
11933   MVT VT = Op.getSimpleValueType();
11934   SDValue In = Op.getOperand(0);
11935   MVT SVT = In.getSimpleValueType();
11936
11937   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11938     return LowerZERO_EXTEND_AVX512(Op, DAG);
11939
11940   if (Subtarget->hasFp256()) {
11941     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11942     if (Res.getNode())
11943       return Res;
11944   }
11945
11946   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11947          VT.getVectorNumElements() != SVT.getVectorNumElements());
11948   return SDValue();
11949 }
11950
11951 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11952   SDLoc DL(Op);
11953   MVT VT = Op.getSimpleValueType();
11954   SDValue In = Op.getOperand(0);
11955   MVT InVT = In.getSimpleValueType();
11956
11957   if (VT == MVT::i1) {
11958     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11959            "Invalid scalar TRUNCATE operation");
11960     if (InVT.getSizeInBits() >= 32)
11961       return SDValue();
11962     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11963     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11964   }
11965   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11966          "Invalid TRUNCATE operation");
11967
11968   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11969     if (VT.getVectorElementType().getSizeInBits() >=8)
11970       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11971
11972     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11973     unsigned NumElts = InVT.getVectorNumElements();
11974     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11975     if (InVT.getSizeInBits() < 512) {
11976       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11977       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11978       InVT = ExtVT;
11979     }
11980
11981     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11982     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11983     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11984     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11985     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11986                            MachinePointerInfo::getConstantPool(),
11987                            false, false, false, Alignment);
11988     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11989     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11990     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11991   }
11992
11993   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11994     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11995     if (Subtarget->hasInt256()) {
11996       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11997       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11998       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11999                                 ShufMask);
12000       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12001                          DAG.getIntPtrConstant(0));
12002     }
12003
12004     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12005                                DAG.getIntPtrConstant(0));
12006     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12007                                DAG.getIntPtrConstant(2));
12008     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12009     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12010     static const int ShufMask[] = {0, 2, 4, 6};
12011     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12012   }
12013
12014   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12015     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12016     if (Subtarget->hasInt256()) {
12017       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12018
12019       SmallVector<SDValue,32> pshufbMask;
12020       for (unsigned i = 0; i < 2; ++i) {
12021         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
12022         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
12023         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
12024         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
12025         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
12026         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
12027         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
12028         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
12029         for (unsigned j = 0; j < 8; ++j)
12030           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
12031       }
12032       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12033       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12034       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12035
12036       static const int ShufMask[] = {0,  2,  -1,  -1};
12037       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12038                                 &ShufMask[0]);
12039       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12040                        DAG.getIntPtrConstant(0));
12041       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12042     }
12043
12044     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12045                                DAG.getIntPtrConstant(0));
12046
12047     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12048                                DAG.getIntPtrConstant(4));
12049
12050     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12051     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12052
12053     // The PSHUFB mask:
12054     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12055                                    -1, -1, -1, -1, -1, -1, -1, -1};
12056
12057     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12058     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12059     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12060
12061     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12062     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12063
12064     // The MOVLHPS Mask:
12065     static const int ShufMask2[] = {0, 1, 4, 5};
12066     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12067     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12068   }
12069
12070   // Handle truncation of V256 to V128 using shuffles.
12071   if (!VT.is128BitVector() || !InVT.is256BitVector())
12072     return SDValue();
12073
12074   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12075
12076   unsigned NumElems = VT.getVectorNumElements();
12077   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12078
12079   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12080   // Prepare truncation shuffle mask
12081   for (unsigned i = 0; i != NumElems; ++i)
12082     MaskVec[i] = i * 2;
12083   SDValue V = DAG.getVectorShuffle(NVT, DL,
12084                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12085                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12086   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12087                      DAG.getIntPtrConstant(0));
12088 }
12089
12090 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12091                                            SelectionDAG &DAG) const {
12092   assert(!Op.getSimpleValueType().isVector());
12093
12094   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12095     /*IsSigned=*/ true, /*IsReplace=*/ false);
12096   SDValue FIST = Vals.first, StackSlot = Vals.second;
12097   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12098   if (!FIST.getNode()) return Op;
12099
12100   if (StackSlot.getNode())
12101     // Load the result.
12102     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12103                        FIST, StackSlot, MachinePointerInfo(),
12104                        false, false, false, 0);
12105
12106   // The node is the result.
12107   return FIST;
12108 }
12109
12110 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12111                                            SelectionDAG &DAG) const {
12112   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12113     /*IsSigned=*/ false, /*IsReplace=*/ false);
12114   SDValue FIST = Vals.first, StackSlot = Vals.second;
12115   assert(FIST.getNode() && "Unexpected failure");
12116
12117   if (StackSlot.getNode())
12118     // Load the result.
12119     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12120                        FIST, StackSlot, MachinePointerInfo(),
12121                        false, false, false, 0);
12122
12123   // The node is the result.
12124   return FIST;
12125 }
12126
12127 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12128   SDLoc DL(Op);
12129   MVT VT = Op.getSimpleValueType();
12130   SDValue In = Op.getOperand(0);
12131   MVT SVT = In.getSimpleValueType();
12132
12133   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12134
12135   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12136                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12137                                  In, DAG.getUNDEF(SVT)));
12138 }
12139
12140 /// The only differences between FABS and FNEG are the mask and the logic op.
12141 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12142 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12143   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12144          "Wrong opcode for lowering FABS or FNEG.");
12145
12146   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12147
12148   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12149   // into an FNABS. We'll lower the FABS after that if it is still in use.
12150   if (IsFABS)
12151     for (SDNode *User : Op->uses())
12152       if (User->getOpcode() == ISD::FNEG)
12153         return Op;
12154
12155   SDValue Op0 = Op.getOperand(0);
12156   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12157
12158   SDLoc dl(Op);
12159   MVT VT = Op.getSimpleValueType();
12160   // Assume scalar op for initialization; update for vector if needed.
12161   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12162   // generate a 16-byte vector constant and logic op even for the scalar case.
12163   // Using a 16-byte mask allows folding the load of the mask with
12164   // the logic op, so it can save (~4 bytes) on code size.
12165   MVT EltVT = VT;
12166   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12167   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12168   // decide if we should generate a 16-byte constant mask when we only need 4 or
12169   // 8 bytes for the scalar case.
12170   if (VT.isVector()) {
12171     EltVT = VT.getVectorElementType();
12172     NumElts = VT.getVectorNumElements();
12173   }
12174
12175   unsigned EltBits = EltVT.getSizeInBits();
12176   LLVMContext *Context = DAG.getContext();
12177   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12178   APInt MaskElt =
12179     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12180   Constant *C = ConstantInt::get(*Context, MaskElt);
12181   C = ConstantVector::getSplat(NumElts, C);
12182   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12183   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12184   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12185   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12186                              MachinePointerInfo::getConstantPool(),
12187                              false, false, false, Alignment);
12188
12189   if (VT.isVector()) {
12190     // For a vector, cast operands to a vector type, perform the logic op,
12191     // and cast the result back to the original value type.
12192     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12193     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12194     SDValue Operand = IsFNABS ?
12195       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12196       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12197     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12198     return DAG.getNode(ISD::BITCAST, dl, VT,
12199                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12200   }
12201
12202   // If not vector, then scalar.
12203   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12204   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12205   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12206 }
12207
12208 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12209   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12210   LLVMContext *Context = DAG.getContext();
12211   SDValue Op0 = Op.getOperand(0);
12212   SDValue Op1 = Op.getOperand(1);
12213   SDLoc dl(Op);
12214   MVT VT = Op.getSimpleValueType();
12215   MVT SrcVT = Op1.getSimpleValueType();
12216
12217   // If second operand is smaller, extend it first.
12218   if (SrcVT.bitsLT(VT)) {
12219     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12220     SrcVT = VT;
12221   }
12222   // And if it is bigger, shrink it first.
12223   if (SrcVT.bitsGT(VT)) {
12224     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12225     SrcVT = VT;
12226   }
12227
12228   // At this point the operands and the result should have the same
12229   // type, and that won't be f80 since that is not custom lowered.
12230
12231   const fltSemantics &Sem =
12232       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12233   const unsigned SizeInBits = VT.getSizeInBits();
12234
12235   SmallVector<Constant *, 4> CV(
12236       VT == MVT::f64 ? 2 : 4,
12237       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12238
12239   // First, clear all bits but the sign bit from the second operand (sign).
12240   CV[0] = ConstantFP::get(*Context,
12241                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12242   Constant *C = ConstantVector::get(CV);
12243   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12244   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12245                               MachinePointerInfo::getConstantPool(),
12246                               false, false, false, 16);
12247   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12248
12249   // Next, clear the sign bit from the first operand (magnitude).
12250   // If it's a constant, we can clear it here.
12251   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12252     APFloat APF = Op0CN->getValueAPF();
12253     // If the magnitude is a positive zero, the sign bit alone is enough.
12254     if (APF.isPosZero())
12255       return SignBit;
12256     APF.clearSign();
12257     CV[0] = ConstantFP::get(*Context, APF);
12258   } else {
12259     CV[0] = ConstantFP::get(
12260         *Context,
12261         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12262   }
12263   C = ConstantVector::get(CV);
12264   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12265   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12266                             MachinePointerInfo::getConstantPool(),
12267                             false, false, false, 16);
12268   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12269   if (!isa<ConstantFPSDNode>(Op0))
12270     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12271
12272   // OR the magnitude value with the sign bit.
12273   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12274 }
12275
12276 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12277   SDValue N0 = Op.getOperand(0);
12278   SDLoc dl(Op);
12279   MVT VT = Op.getSimpleValueType();
12280
12281   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12282   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12283                                   DAG.getConstant(1, VT));
12284   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12285 }
12286
12287 // Check whether an OR'd tree is PTEST-able.
12288 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12289                                       SelectionDAG &DAG) {
12290   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12291
12292   if (!Subtarget->hasSSE41())
12293     return SDValue();
12294
12295   if (!Op->hasOneUse())
12296     return SDValue();
12297
12298   SDNode *N = Op.getNode();
12299   SDLoc DL(N);
12300
12301   SmallVector<SDValue, 8> Opnds;
12302   DenseMap<SDValue, unsigned> VecInMap;
12303   SmallVector<SDValue, 8> VecIns;
12304   EVT VT = MVT::Other;
12305
12306   // Recognize a special case where a vector is casted into wide integer to
12307   // test all 0s.
12308   Opnds.push_back(N->getOperand(0));
12309   Opnds.push_back(N->getOperand(1));
12310
12311   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12312     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12313     // BFS traverse all OR'd operands.
12314     if (I->getOpcode() == ISD::OR) {
12315       Opnds.push_back(I->getOperand(0));
12316       Opnds.push_back(I->getOperand(1));
12317       // Re-evaluate the number of nodes to be traversed.
12318       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12319       continue;
12320     }
12321
12322     // Quit if a non-EXTRACT_VECTOR_ELT
12323     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12324       return SDValue();
12325
12326     // Quit if without a constant index.
12327     SDValue Idx = I->getOperand(1);
12328     if (!isa<ConstantSDNode>(Idx))
12329       return SDValue();
12330
12331     SDValue ExtractedFromVec = I->getOperand(0);
12332     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12333     if (M == VecInMap.end()) {
12334       VT = ExtractedFromVec.getValueType();
12335       // Quit if not 128/256-bit vector.
12336       if (!VT.is128BitVector() && !VT.is256BitVector())
12337         return SDValue();
12338       // Quit if not the same type.
12339       if (VecInMap.begin() != VecInMap.end() &&
12340           VT != VecInMap.begin()->first.getValueType())
12341         return SDValue();
12342       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12343       VecIns.push_back(ExtractedFromVec);
12344     }
12345     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12346   }
12347
12348   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12349          "Not extracted from 128-/256-bit vector.");
12350
12351   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12352
12353   for (DenseMap<SDValue, unsigned>::const_iterator
12354         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12355     // Quit if not all elements are used.
12356     if (I->second != FullMask)
12357       return SDValue();
12358   }
12359
12360   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12361
12362   // Cast all vectors into TestVT for PTEST.
12363   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12364     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12365
12366   // If more than one full vectors are evaluated, OR them first before PTEST.
12367   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12368     // Each iteration will OR 2 nodes and append the result until there is only
12369     // 1 node left, i.e. the final OR'd value of all vectors.
12370     SDValue LHS = VecIns[Slot];
12371     SDValue RHS = VecIns[Slot + 1];
12372     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12373   }
12374
12375   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12376                      VecIns.back(), VecIns.back());
12377 }
12378
12379 /// \brief return true if \c Op has a use that doesn't just read flags.
12380 static bool hasNonFlagsUse(SDValue Op) {
12381   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12382        ++UI) {
12383     SDNode *User = *UI;
12384     unsigned UOpNo = UI.getOperandNo();
12385     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12386       // Look pass truncate.
12387       UOpNo = User->use_begin().getOperandNo();
12388       User = *User->use_begin();
12389     }
12390
12391     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12392         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12393       return true;
12394   }
12395   return false;
12396 }
12397
12398 /// Emit nodes that will be selected as "test Op0,Op0", or something
12399 /// equivalent.
12400 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12401                                     SelectionDAG &DAG) const {
12402   if (Op.getValueType() == MVT::i1) {
12403     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12404     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12405                        DAG.getConstant(0, MVT::i8));
12406   }
12407   // CF and OF aren't always set the way we want. Determine which
12408   // of these we need.
12409   bool NeedCF = false;
12410   bool NeedOF = false;
12411   switch (X86CC) {
12412   default: break;
12413   case X86::COND_A: case X86::COND_AE:
12414   case X86::COND_B: case X86::COND_BE:
12415     NeedCF = true;
12416     break;
12417   case X86::COND_G: case X86::COND_GE:
12418   case X86::COND_L: case X86::COND_LE:
12419   case X86::COND_O: case X86::COND_NO: {
12420     // Check if we really need to set the
12421     // Overflow flag. If NoSignedWrap is present
12422     // that is not actually needed.
12423     switch (Op->getOpcode()) {
12424     case ISD::ADD:
12425     case ISD::SUB:
12426     case ISD::MUL:
12427     case ISD::SHL: {
12428       const BinaryWithFlagsSDNode *BinNode =
12429           cast<BinaryWithFlagsSDNode>(Op.getNode());
12430       if (BinNode->hasNoSignedWrap())
12431         break;
12432     }
12433     default:
12434       NeedOF = true;
12435       break;
12436     }
12437     break;
12438   }
12439   }
12440   // See if we can use the EFLAGS value from the operand instead of
12441   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12442   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12443   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12444     // Emit a CMP with 0, which is the TEST pattern.
12445     //if (Op.getValueType() == MVT::i1)
12446     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12447     //                     DAG.getConstant(0, MVT::i1));
12448     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12449                        DAG.getConstant(0, Op.getValueType()));
12450   }
12451   unsigned Opcode = 0;
12452   unsigned NumOperands = 0;
12453
12454   // Truncate operations may prevent the merge of the SETCC instruction
12455   // and the arithmetic instruction before it. Attempt to truncate the operands
12456   // of the arithmetic instruction and use a reduced bit-width instruction.
12457   bool NeedTruncation = false;
12458   SDValue ArithOp = Op;
12459   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12460     SDValue Arith = Op->getOperand(0);
12461     // Both the trunc and the arithmetic op need to have one user each.
12462     if (Arith->hasOneUse())
12463       switch (Arith.getOpcode()) {
12464         default: break;
12465         case ISD::ADD:
12466         case ISD::SUB:
12467         case ISD::AND:
12468         case ISD::OR:
12469         case ISD::XOR: {
12470           NeedTruncation = true;
12471           ArithOp = Arith;
12472         }
12473       }
12474   }
12475
12476   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12477   // which may be the result of a CAST.  We use the variable 'Op', which is the
12478   // non-casted variable when we check for possible users.
12479   switch (ArithOp.getOpcode()) {
12480   case ISD::ADD:
12481     // Due to an isel shortcoming, be conservative if this add is likely to be
12482     // selected as part of a load-modify-store instruction. When the root node
12483     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12484     // uses of other nodes in the match, such as the ADD in this case. This
12485     // leads to the ADD being left around and reselected, with the result being
12486     // two adds in the output.  Alas, even if none our users are stores, that
12487     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12488     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12489     // climbing the DAG back to the root, and it doesn't seem to be worth the
12490     // effort.
12491     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12492          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12493       if (UI->getOpcode() != ISD::CopyToReg &&
12494           UI->getOpcode() != ISD::SETCC &&
12495           UI->getOpcode() != ISD::STORE)
12496         goto default_case;
12497
12498     if (ConstantSDNode *C =
12499         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12500       // An add of one will be selected as an INC.
12501       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12502         Opcode = X86ISD::INC;
12503         NumOperands = 1;
12504         break;
12505       }
12506
12507       // An add of negative one (subtract of one) will be selected as a DEC.
12508       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12509         Opcode = X86ISD::DEC;
12510         NumOperands = 1;
12511         break;
12512       }
12513     }
12514
12515     // Otherwise use a regular EFLAGS-setting add.
12516     Opcode = X86ISD::ADD;
12517     NumOperands = 2;
12518     break;
12519   case ISD::SHL:
12520   case ISD::SRL:
12521     // If we have a constant logical shift that's only used in a comparison
12522     // against zero turn it into an equivalent AND. This allows turning it into
12523     // a TEST instruction later.
12524     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12525         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12526       EVT VT = Op.getValueType();
12527       unsigned BitWidth = VT.getSizeInBits();
12528       unsigned ShAmt = Op->getConstantOperandVal(1);
12529       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12530         break;
12531       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12532                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12533                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12534       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12535         break;
12536       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12537                                 DAG.getConstant(Mask, VT));
12538       DAG.ReplaceAllUsesWith(Op, New);
12539       Op = New;
12540     }
12541     break;
12542
12543   case ISD::AND:
12544     // If the primary and result isn't used, don't bother using X86ISD::AND,
12545     // because a TEST instruction will be better.
12546     if (!hasNonFlagsUse(Op))
12547       break;
12548     // FALL THROUGH
12549   case ISD::SUB:
12550   case ISD::OR:
12551   case ISD::XOR:
12552     // Due to the ISEL shortcoming noted above, be conservative if this op is
12553     // likely to be selected as part of a load-modify-store instruction.
12554     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12555            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12556       if (UI->getOpcode() == ISD::STORE)
12557         goto default_case;
12558
12559     // Otherwise use a regular EFLAGS-setting instruction.
12560     switch (ArithOp.getOpcode()) {
12561     default: llvm_unreachable("unexpected operator!");
12562     case ISD::SUB: Opcode = X86ISD::SUB; break;
12563     case ISD::XOR: Opcode = X86ISD::XOR; break;
12564     case ISD::AND: Opcode = X86ISD::AND; break;
12565     case ISD::OR: {
12566       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12567         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12568         if (EFLAGS.getNode())
12569           return EFLAGS;
12570       }
12571       Opcode = X86ISD::OR;
12572       break;
12573     }
12574     }
12575
12576     NumOperands = 2;
12577     break;
12578   case X86ISD::ADD:
12579   case X86ISD::SUB:
12580   case X86ISD::INC:
12581   case X86ISD::DEC:
12582   case X86ISD::OR:
12583   case X86ISD::XOR:
12584   case X86ISD::AND:
12585     return SDValue(Op.getNode(), 1);
12586   default:
12587   default_case:
12588     break;
12589   }
12590
12591   // If we found that truncation is beneficial, perform the truncation and
12592   // update 'Op'.
12593   if (NeedTruncation) {
12594     EVT VT = Op.getValueType();
12595     SDValue WideVal = Op->getOperand(0);
12596     EVT WideVT = WideVal.getValueType();
12597     unsigned ConvertedOp = 0;
12598     // Use a target machine opcode to prevent further DAGCombine
12599     // optimizations that may separate the arithmetic operations
12600     // from the setcc node.
12601     switch (WideVal.getOpcode()) {
12602       default: break;
12603       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12604       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12605       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12606       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12607       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12608     }
12609
12610     if (ConvertedOp) {
12611       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12612       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12613         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12614         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12615         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12616       }
12617     }
12618   }
12619
12620   if (Opcode == 0)
12621     // Emit a CMP with 0, which is the TEST pattern.
12622     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12623                        DAG.getConstant(0, Op.getValueType()));
12624
12625   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12626   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12627
12628   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12629   DAG.ReplaceAllUsesWith(Op, New);
12630   return SDValue(New.getNode(), 1);
12631 }
12632
12633 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12634 /// equivalent.
12635 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12636                                    SDLoc dl, SelectionDAG &DAG) const {
12637   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12638     if (C->getAPIntValue() == 0)
12639       return EmitTest(Op0, X86CC, dl, DAG);
12640
12641      if (Op0.getValueType() == MVT::i1)
12642        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12643   }
12644
12645   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12646        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12647     // Do the comparison at i32 if it's smaller, besides the Atom case.
12648     // This avoids subregister aliasing issues. Keep the smaller reference
12649     // if we're optimizing for size, however, as that'll allow better folding
12650     // of memory operations.
12651     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12652         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12653             Attribute::MinSize) &&
12654         !Subtarget->isAtom()) {
12655       unsigned ExtendOp =
12656           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12657       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12658       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12659     }
12660     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12661     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12662     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12663                               Op0, Op1);
12664     return SDValue(Sub.getNode(), 1);
12665   }
12666   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12667 }
12668
12669 /// Convert a comparison if required by the subtarget.
12670 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12671                                                  SelectionDAG &DAG) const {
12672   // If the subtarget does not support the FUCOMI instruction, floating-point
12673   // comparisons have to be converted.
12674   if (Subtarget->hasCMov() ||
12675       Cmp.getOpcode() != X86ISD::CMP ||
12676       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12677       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12678     return Cmp;
12679
12680   // The instruction selector will select an FUCOM instruction instead of
12681   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12682   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12683   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12684   SDLoc dl(Cmp);
12685   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12686   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12687   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12688                             DAG.getConstant(8, MVT::i8));
12689   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12690   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12691 }
12692
12693 /// The minimum architected relative accuracy is 2^-12. We need one
12694 /// Newton-Raphson step to have a good float result (24 bits of precision).
12695 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12696                                             DAGCombinerInfo &DCI,
12697                                             unsigned &RefinementSteps,
12698                                             bool &UseOneConstNR) const {
12699   // FIXME: We should use instruction latency models to calculate the cost of
12700   // each potential sequence, but this is very hard to do reliably because
12701   // at least Intel's Core* chips have variable timing based on the number of
12702   // significant digits in the divisor and/or sqrt operand.
12703   if (!Subtarget->useSqrtEst())
12704     return SDValue();
12705
12706   EVT VT = Op.getValueType();
12707
12708   // SSE1 has rsqrtss and rsqrtps.
12709   // TODO: Add support for AVX512 (v16f32).
12710   // It is likely not profitable to do this for f64 because a double-precision
12711   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12712   // instructions: convert to single, rsqrtss, convert back to double, refine
12713   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12714   // along with FMA, this could be a throughput win.
12715   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12716       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12717     RefinementSteps = 1;
12718     UseOneConstNR = false;
12719     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12720   }
12721   return SDValue();
12722 }
12723
12724 /// The minimum architected relative accuracy is 2^-12. We need one
12725 /// Newton-Raphson step to have a good float result (24 bits of precision).
12726 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12727                                             DAGCombinerInfo &DCI,
12728                                             unsigned &RefinementSteps) const {
12729   // FIXME: We should use instruction latency models to calculate the cost of
12730   // each potential sequence, but this is very hard to do reliably because
12731   // at least Intel's Core* chips have variable timing based on the number of
12732   // significant digits in the divisor.
12733   if (!Subtarget->useReciprocalEst())
12734     return SDValue();
12735
12736   EVT VT = Op.getValueType();
12737
12738   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12739   // TODO: Add support for AVX512 (v16f32).
12740   // It is likely not profitable to do this for f64 because a double-precision
12741   // reciprocal estimate with refinement on x86 prior to FMA requires
12742   // 15 instructions: convert to single, rcpss, convert back to double, refine
12743   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12744   // along with FMA, this could be a throughput win.
12745   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12746       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12747     RefinementSteps = ReciprocalEstimateRefinementSteps;
12748     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12749   }
12750   return SDValue();
12751 }
12752
12753 static bool isAllOnes(SDValue V) {
12754   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12755   return C && C->isAllOnesValue();
12756 }
12757
12758 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12759 /// if it's possible.
12760 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12761                                      SDLoc dl, SelectionDAG &DAG) const {
12762   SDValue Op0 = And.getOperand(0);
12763   SDValue Op1 = And.getOperand(1);
12764   if (Op0.getOpcode() == ISD::TRUNCATE)
12765     Op0 = Op0.getOperand(0);
12766   if (Op1.getOpcode() == ISD::TRUNCATE)
12767     Op1 = Op1.getOperand(0);
12768
12769   SDValue LHS, RHS;
12770   if (Op1.getOpcode() == ISD::SHL)
12771     std::swap(Op0, Op1);
12772   if (Op0.getOpcode() == ISD::SHL) {
12773     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12774       if (And00C->getZExtValue() == 1) {
12775         // If we looked past a truncate, check that it's only truncating away
12776         // known zeros.
12777         unsigned BitWidth = Op0.getValueSizeInBits();
12778         unsigned AndBitWidth = And.getValueSizeInBits();
12779         if (BitWidth > AndBitWidth) {
12780           APInt Zeros, Ones;
12781           DAG.computeKnownBits(Op0, Zeros, Ones);
12782           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12783             return SDValue();
12784         }
12785         LHS = Op1;
12786         RHS = Op0.getOperand(1);
12787       }
12788   } else if (Op1.getOpcode() == ISD::Constant) {
12789     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12790     uint64_t AndRHSVal = AndRHS->getZExtValue();
12791     SDValue AndLHS = Op0;
12792
12793     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12794       LHS = AndLHS.getOperand(0);
12795       RHS = AndLHS.getOperand(1);
12796     }
12797
12798     // Use BT if the immediate can't be encoded in a TEST instruction.
12799     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12800       LHS = AndLHS;
12801       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12802     }
12803   }
12804
12805   if (LHS.getNode()) {
12806     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12807     // instruction.  Since the shift amount is in-range-or-undefined, we know
12808     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12809     // the encoding for the i16 version is larger than the i32 version.
12810     // Also promote i16 to i32 for performance / code size reason.
12811     if (LHS.getValueType() == MVT::i8 ||
12812         LHS.getValueType() == MVT::i16)
12813       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12814
12815     // If the operand types disagree, extend the shift amount to match.  Since
12816     // BT ignores high bits (like shifts) we can use anyextend.
12817     if (LHS.getValueType() != RHS.getValueType())
12818       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12819
12820     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12821     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12822     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12823                        DAG.getConstant(Cond, MVT::i8), BT);
12824   }
12825
12826   return SDValue();
12827 }
12828
12829 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12830 /// mask CMPs.
12831 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12832                               SDValue &Op1) {
12833   unsigned SSECC;
12834   bool Swap = false;
12835
12836   // SSE Condition code mapping:
12837   //  0 - EQ
12838   //  1 - LT
12839   //  2 - LE
12840   //  3 - UNORD
12841   //  4 - NEQ
12842   //  5 - NLT
12843   //  6 - NLE
12844   //  7 - ORD
12845   switch (SetCCOpcode) {
12846   default: llvm_unreachable("Unexpected SETCC condition");
12847   case ISD::SETOEQ:
12848   case ISD::SETEQ:  SSECC = 0; break;
12849   case ISD::SETOGT:
12850   case ISD::SETGT:  Swap = true; // Fallthrough
12851   case ISD::SETLT:
12852   case ISD::SETOLT: SSECC = 1; break;
12853   case ISD::SETOGE:
12854   case ISD::SETGE:  Swap = true; // Fallthrough
12855   case ISD::SETLE:
12856   case ISD::SETOLE: SSECC = 2; break;
12857   case ISD::SETUO:  SSECC = 3; break;
12858   case ISD::SETUNE:
12859   case ISD::SETNE:  SSECC = 4; break;
12860   case ISD::SETULE: Swap = true; // Fallthrough
12861   case ISD::SETUGE: SSECC = 5; break;
12862   case ISD::SETULT: Swap = true; // Fallthrough
12863   case ISD::SETUGT: SSECC = 6; break;
12864   case ISD::SETO:   SSECC = 7; break;
12865   case ISD::SETUEQ:
12866   case ISD::SETONE: SSECC = 8; break;
12867   }
12868   if (Swap)
12869     std::swap(Op0, Op1);
12870
12871   return SSECC;
12872 }
12873
12874 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12875 // ones, and then concatenate the result back.
12876 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12877   MVT VT = Op.getSimpleValueType();
12878
12879   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12880          "Unsupported value type for operation");
12881
12882   unsigned NumElems = VT.getVectorNumElements();
12883   SDLoc dl(Op);
12884   SDValue CC = Op.getOperand(2);
12885
12886   // Extract the LHS vectors
12887   SDValue LHS = Op.getOperand(0);
12888   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12889   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12890
12891   // Extract the RHS vectors
12892   SDValue RHS = Op.getOperand(1);
12893   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12894   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12895
12896   // Issue the operation on the smaller types and concatenate the result back
12897   MVT EltVT = VT.getVectorElementType();
12898   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12899   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12900                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12901                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12902 }
12903
12904 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12905                                      const X86Subtarget *Subtarget) {
12906   SDValue Op0 = Op.getOperand(0);
12907   SDValue Op1 = Op.getOperand(1);
12908   SDValue CC = Op.getOperand(2);
12909   MVT VT = Op.getSimpleValueType();
12910   SDLoc dl(Op);
12911
12912   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
12913          Op.getValueType().getScalarType() == MVT::i1 &&
12914          "Cannot set masked compare for this operation");
12915
12916   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12917   unsigned  Opc = 0;
12918   bool Unsigned = false;
12919   bool Swap = false;
12920   unsigned SSECC;
12921   switch (SetCCOpcode) {
12922   default: llvm_unreachable("Unexpected SETCC condition");
12923   case ISD::SETNE:  SSECC = 4; break;
12924   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12925   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12926   case ISD::SETLT:  Swap = true; //fall-through
12927   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12928   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12929   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12930   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12931   case ISD::SETULE: Unsigned = true; //fall-through
12932   case ISD::SETLE:  SSECC = 2; break;
12933   }
12934
12935   if (Swap)
12936     std::swap(Op0, Op1);
12937   if (Opc)
12938     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12939   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12940   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12941                      DAG.getConstant(SSECC, MVT::i8));
12942 }
12943
12944 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12945 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12946 /// return an empty value.
12947 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12948 {
12949   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12950   if (!BV)
12951     return SDValue();
12952
12953   MVT VT = Op1.getSimpleValueType();
12954   MVT EVT = VT.getVectorElementType();
12955   unsigned n = VT.getVectorNumElements();
12956   SmallVector<SDValue, 8> ULTOp1;
12957
12958   for (unsigned i = 0; i < n; ++i) {
12959     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12960     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12961       return SDValue();
12962
12963     // Avoid underflow.
12964     APInt Val = Elt->getAPIntValue();
12965     if (Val == 0)
12966       return SDValue();
12967
12968     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12969   }
12970
12971   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12972 }
12973
12974 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12975                            SelectionDAG &DAG) {
12976   SDValue Op0 = Op.getOperand(0);
12977   SDValue Op1 = Op.getOperand(1);
12978   SDValue CC = Op.getOperand(2);
12979   MVT VT = Op.getSimpleValueType();
12980   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12981   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12982   SDLoc dl(Op);
12983
12984   if (isFP) {
12985 #ifndef NDEBUG
12986     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12987     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12988 #endif
12989
12990     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12991     unsigned Opc = X86ISD::CMPP;
12992     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12993       assert(VT.getVectorNumElements() <= 16);
12994       Opc = X86ISD::CMPM;
12995     }
12996     // In the two special cases we can't handle, emit two comparisons.
12997     if (SSECC == 8) {
12998       unsigned CC0, CC1;
12999       unsigned CombineOpc;
13000       if (SetCCOpcode == ISD::SETUEQ) {
13001         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13002       } else {
13003         assert(SetCCOpcode == ISD::SETONE);
13004         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13005       }
13006
13007       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13008                                  DAG.getConstant(CC0, MVT::i8));
13009       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13010                                  DAG.getConstant(CC1, MVT::i8));
13011       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13012     }
13013     // Handle all other FP comparisons here.
13014     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13015                        DAG.getConstant(SSECC, MVT::i8));
13016   }
13017
13018   // Break 256-bit integer vector compare into smaller ones.
13019   if (VT.is256BitVector() && !Subtarget->hasInt256())
13020     return Lower256IntVSETCC(Op, DAG);
13021
13022   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13023   EVT OpVT = Op1.getValueType();
13024   if (Subtarget->hasAVX512()) {
13025     if (Op1.getValueType().is512BitVector() ||
13026         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13027         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13028       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13029
13030     // In AVX-512 architecture setcc returns mask with i1 elements,
13031     // But there is no compare instruction for i8 and i16 elements in KNL.
13032     // We are not talking about 512-bit operands in this case, these
13033     // types are illegal.
13034     if (MaskResult &&
13035         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13036          OpVT.getVectorElementType().getSizeInBits() >= 8))
13037       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13038                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13039   }
13040
13041   // We are handling one of the integer comparisons here.  Since SSE only has
13042   // GT and EQ comparisons for integer, swapping operands and multiple
13043   // operations may be required for some comparisons.
13044   unsigned Opc;
13045   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13046   bool Subus = false;
13047
13048   switch (SetCCOpcode) {
13049   default: llvm_unreachable("Unexpected SETCC condition");
13050   case ISD::SETNE:  Invert = true;
13051   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13052   case ISD::SETLT:  Swap = true;
13053   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13054   case ISD::SETGE:  Swap = true;
13055   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13056                     Invert = true; break;
13057   case ISD::SETULT: Swap = true;
13058   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13059                     FlipSigns = true; break;
13060   case ISD::SETUGE: Swap = true;
13061   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13062                     FlipSigns = true; Invert = true; break;
13063   }
13064
13065   // Special case: Use min/max operations for SETULE/SETUGE
13066   MVT VET = VT.getVectorElementType();
13067   bool hasMinMax =
13068        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13069     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13070
13071   if (hasMinMax) {
13072     switch (SetCCOpcode) {
13073     default: break;
13074     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13075     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13076     }
13077
13078     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13079   }
13080
13081   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13082   if (!MinMax && hasSubus) {
13083     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13084     // Op0 u<= Op1:
13085     //   t = psubus Op0, Op1
13086     //   pcmpeq t, <0..0>
13087     switch (SetCCOpcode) {
13088     default: break;
13089     case ISD::SETULT: {
13090       // If the comparison is against a constant we can turn this into a
13091       // setule.  With psubus, setule does not require a swap.  This is
13092       // beneficial because the constant in the register is no longer
13093       // destructed as the destination so it can be hoisted out of a loop.
13094       // Only do this pre-AVX since vpcmp* is no longer destructive.
13095       if (Subtarget->hasAVX())
13096         break;
13097       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13098       if (ULEOp1.getNode()) {
13099         Op1 = ULEOp1;
13100         Subus = true; Invert = false; Swap = false;
13101       }
13102       break;
13103     }
13104     // Psubus is better than flip-sign because it requires no inversion.
13105     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13106     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13107     }
13108
13109     if (Subus) {
13110       Opc = X86ISD::SUBUS;
13111       FlipSigns = false;
13112     }
13113   }
13114
13115   if (Swap)
13116     std::swap(Op0, Op1);
13117
13118   // Check that the operation in question is available (most are plain SSE2,
13119   // but PCMPGTQ and PCMPEQQ have different requirements).
13120   if (VT == MVT::v2i64) {
13121     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13122       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13123
13124       // First cast everything to the right type.
13125       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13126       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13127
13128       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13129       // bits of the inputs before performing those operations. The lower
13130       // compare is always unsigned.
13131       SDValue SB;
13132       if (FlipSigns) {
13133         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13134       } else {
13135         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13136         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13137         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13138                          Sign, Zero, Sign, Zero);
13139       }
13140       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13141       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13142
13143       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13144       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13145       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13146
13147       // Create masks for only the low parts/high parts of the 64 bit integers.
13148       static const int MaskHi[] = { 1, 1, 3, 3 };
13149       static const int MaskLo[] = { 0, 0, 2, 2 };
13150       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13151       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13152       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13153
13154       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13155       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13156
13157       if (Invert)
13158         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13159
13160       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13161     }
13162
13163     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13164       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13165       // pcmpeqd + pshufd + pand.
13166       assert(Subtarget->hasSSE2() && !FlipSigns && "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       // Do the compare.
13173       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13174
13175       // Make sure the lower and upper halves are both all-ones.
13176       static const int Mask[] = { 1, 0, 3, 2 };
13177       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13178       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13179
13180       if (Invert)
13181         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13182
13183       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13184     }
13185   }
13186
13187   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13188   // bits of the inputs before performing those operations.
13189   if (FlipSigns) {
13190     EVT EltVT = VT.getVectorElementType();
13191     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13192     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13193     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13194   }
13195
13196   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13197
13198   // If the logical-not of the result is required, perform that now.
13199   if (Invert)
13200     Result = DAG.getNOT(dl, Result, VT);
13201
13202   if (MinMax)
13203     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13204
13205   if (Subus)
13206     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13207                          getZeroVector(VT, Subtarget, DAG, dl));
13208
13209   return Result;
13210 }
13211
13212 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13213
13214   MVT VT = Op.getSimpleValueType();
13215
13216   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13217
13218   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13219          && "SetCC type must be 8-bit or 1-bit integer");
13220   SDValue Op0 = Op.getOperand(0);
13221   SDValue Op1 = Op.getOperand(1);
13222   SDLoc dl(Op);
13223   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13224
13225   // Optimize to BT if possible.
13226   // Lower (X & (1 << N)) == 0 to BT(X, N).
13227   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13228   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13229   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13230       Op1.getOpcode() == ISD::Constant &&
13231       cast<ConstantSDNode>(Op1)->isNullValue() &&
13232       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13233     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13234     if (NewSetCC.getNode()) {
13235       if (VT == MVT::i1)
13236         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13237       return NewSetCC;
13238     }
13239   }
13240
13241   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13242   // these.
13243   if (Op1.getOpcode() == ISD::Constant &&
13244       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13245        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13246       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13247
13248     // If the input is a setcc, then reuse the input setcc or use a new one with
13249     // the inverted condition.
13250     if (Op0.getOpcode() == X86ISD::SETCC) {
13251       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13252       bool Invert = (CC == ISD::SETNE) ^
13253         cast<ConstantSDNode>(Op1)->isNullValue();
13254       if (!Invert)
13255         return Op0;
13256
13257       CCode = X86::GetOppositeBranchCondition(CCode);
13258       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13259                                   DAG.getConstant(CCode, MVT::i8),
13260                                   Op0.getOperand(1));
13261       if (VT == MVT::i1)
13262         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13263       return SetCC;
13264     }
13265   }
13266   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13267       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13268       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13269
13270     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13271     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13272   }
13273
13274   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13275   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13276   if (X86CC == X86::COND_INVALID)
13277     return SDValue();
13278
13279   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13280   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13281   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13282                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13283   if (VT == MVT::i1)
13284     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13285   return SetCC;
13286 }
13287
13288 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13289 static bool isX86LogicalCmp(SDValue Op) {
13290   unsigned Opc = Op.getNode()->getOpcode();
13291   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13292       Opc == X86ISD::SAHF)
13293     return true;
13294   if (Op.getResNo() == 1 &&
13295       (Opc == X86ISD::ADD ||
13296        Opc == X86ISD::SUB ||
13297        Opc == X86ISD::ADC ||
13298        Opc == X86ISD::SBB ||
13299        Opc == X86ISD::SMUL ||
13300        Opc == X86ISD::UMUL ||
13301        Opc == X86ISD::INC ||
13302        Opc == X86ISD::DEC ||
13303        Opc == X86ISD::OR ||
13304        Opc == X86ISD::XOR ||
13305        Opc == X86ISD::AND))
13306     return true;
13307
13308   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13309     return true;
13310
13311   return false;
13312 }
13313
13314 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13315   if (V.getOpcode() != ISD::TRUNCATE)
13316     return false;
13317
13318   SDValue VOp0 = V.getOperand(0);
13319   unsigned InBits = VOp0.getValueSizeInBits();
13320   unsigned Bits = V.getValueSizeInBits();
13321   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13322 }
13323
13324 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13325   bool addTest = true;
13326   SDValue Cond  = Op.getOperand(0);
13327   SDValue Op1 = Op.getOperand(1);
13328   SDValue Op2 = Op.getOperand(2);
13329   SDLoc DL(Op);
13330   EVT VT = Op1.getValueType();
13331   SDValue CC;
13332
13333   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13334   // are available or VBLENDV if AVX is available.
13335   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13336   if (Cond.getOpcode() == ISD::SETCC &&
13337       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13338        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13339       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13340     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13341     int SSECC = translateX86FSETCC(
13342         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13343
13344     if (SSECC != 8) {
13345       if (Subtarget->hasAVX512()) {
13346         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13347                                   DAG.getConstant(SSECC, MVT::i8));
13348         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13349       }
13350
13351       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13352                                 DAG.getConstant(SSECC, MVT::i8));
13353
13354       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13355       // of 3 logic instructions for size savings and potentially speed.
13356       // Unfortunately, there is no scalar form of VBLENDV.
13357
13358       // If either operand is a constant, don't try this. We can expect to
13359       // optimize away at least one of the logic instructions later in that
13360       // case, so that sequence would be faster than a variable blend.
13361
13362       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13363       // uses XMM0 as the selection register. That may need just as many
13364       // instructions as the AND/ANDN/OR sequence due to register moves, so
13365       // don't bother.
13366
13367       if (Subtarget->hasAVX() &&
13368           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13369
13370         // Convert to vectors, do a VSELECT, and convert back to scalar.
13371         // All of the conversions should be optimized away.
13372
13373         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13374         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13375         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13376         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13377
13378         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13379         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13380
13381         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13382
13383         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13384                            VSel, DAG.getIntPtrConstant(0));
13385       }
13386       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13387       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13388       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13389     }
13390   }
13391
13392   if (Cond.getOpcode() == ISD::SETCC) {
13393     SDValue NewCond = LowerSETCC(Cond, DAG);
13394     if (NewCond.getNode())
13395       Cond = NewCond;
13396   }
13397
13398   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13399   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13400   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13401   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13402   if (Cond.getOpcode() == X86ISD::SETCC &&
13403       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13404       isZero(Cond.getOperand(1).getOperand(1))) {
13405     SDValue Cmp = Cond.getOperand(1);
13406
13407     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13408
13409     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13410         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13411       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13412
13413       SDValue CmpOp0 = Cmp.getOperand(0);
13414       // Apply further optimizations for special cases
13415       // (select (x != 0), -1, 0) -> neg & sbb
13416       // (select (x == 0), 0, -1) -> neg & sbb
13417       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13418         if (YC->isNullValue() &&
13419             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13420           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13421           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13422                                     DAG.getConstant(0, CmpOp0.getValueType()),
13423                                     CmpOp0);
13424           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13425                                     DAG.getConstant(X86::COND_B, MVT::i8),
13426                                     SDValue(Neg.getNode(), 1));
13427           return Res;
13428         }
13429
13430       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13431                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13432       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13433
13434       SDValue Res =   // Res = 0 or -1.
13435         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13436                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13437
13438       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13439         Res = DAG.getNOT(DL, Res, Res.getValueType());
13440
13441       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13442       if (!N2C || !N2C->isNullValue())
13443         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13444       return Res;
13445     }
13446   }
13447
13448   // Look past (and (setcc_carry (cmp ...)), 1).
13449   if (Cond.getOpcode() == ISD::AND &&
13450       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13451     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13452     if (C && C->getAPIntValue() == 1)
13453       Cond = Cond.getOperand(0);
13454   }
13455
13456   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13457   // setting operand in place of the X86ISD::SETCC.
13458   unsigned CondOpcode = Cond.getOpcode();
13459   if (CondOpcode == X86ISD::SETCC ||
13460       CondOpcode == X86ISD::SETCC_CARRY) {
13461     CC = Cond.getOperand(0);
13462
13463     SDValue Cmp = Cond.getOperand(1);
13464     unsigned Opc = Cmp.getOpcode();
13465     MVT VT = Op.getSimpleValueType();
13466
13467     bool IllegalFPCMov = false;
13468     if (VT.isFloatingPoint() && !VT.isVector() &&
13469         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13470       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13471
13472     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13473         Opc == X86ISD::BT) { // FIXME
13474       Cond = Cmp;
13475       addTest = false;
13476     }
13477   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13478              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13479              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13480               Cond.getOperand(0).getValueType() != MVT::i8)) {
13481     SDValue LHS = Cond.getOperand(0);
13482     SDValue RHS = Cond.getOperand(1);
13483     unsigned X86Opcode;
13484     unsigned X86Cond;
13485     SDVTList VTs;
13486     switch (CondOpcode) {
13487     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13488     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13489     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13490     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13491     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13492     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13493     default: llvm_unreachable("unexpected overflowing operator");
13494     }
13495     if (CondOpcode == ISD::UMULO)
13496       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13497                           MVT::i32);
13498     else
13499       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13500
13501     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13502
13503     if (CondOpcode == ISD::UMULO)
13504       Cond = X86Op.getValue(2);
13505     else
13506       Cond = X86Op.getValue(1);
13507
13508     CC = DAG.getConstant(X86Cond, MVT::i8);
13509     addTest = false;
13510   }
13511
13512   if (addTest) {
13513     // Look pass the truncate if the high bits are known zero.
13514     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13515         Cond = Cond.getOperand(0);
13516
13517     // We know the result of AND is compared against zero. Try to match
13518     // it to BT.
13519     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13520       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13521       if (NewSetCC.getNode()) {
13522         CC = NewSetCC.getOperand(0);
13523         Cond = NewSetCC.getOperand(1);
13524         addTest = false;
13525       }
13526     }
13527   }
13528
13529   if (addTest) {
13530     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13531     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13532   }
13533
13534   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13535   // a <  b ?  0 : -1 -> RES = setcc_carry
13536   // a >= b ? -1 :  0 -> RES = setcc_carry
13537   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13538   if (Cond.getOpcode() == X86ISD::SUB) {
13539     Cond = ConvertCmpIfNecessary(Cond, DAG);
13540     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13541
13542     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13543         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13544       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13545                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13546       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13547         return DAG.getNOT(DL, Res, Res.getValueType());
13548       return Res;
13549     }
13550   }
13551
13552   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13553   // widen the cmov and push the truncate through. This avoids introducing a new
13554   // branch during isel and doesn't add any extensions.
13555   if (Op.getValueType() == MVT::i8 &&
13556       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13557     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13558     if (T1.getValueType() == T2.getValueType() &&
13559         // Blacklist CopyFromReg to avoid partial register stalls.
13560         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13561       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13562       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13563       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13564     }
13565   }
13566
13567   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13568   // condition is true.
13569   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13570   SDValue Ops[] = { Op2, Op1, CC, Cond };
13571   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13572 }
13573
13574 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13575                                        SelectionDAG &DAG) {
13576   MVT VT = Op->getSimpleValueType(0);
13577   SDValue In = Op->getOperand(0);
13578   MVT InVT = In.getSimpleValueType();
13579   MVT VTElt = VT.getVectorElementType();
13580   MVT InVTElt = InVT.getVectorElementType();
13581   SDLoc dl(Op);
13582
13583   // SKX processor
13584   if ((InVTElt == MVT::i1) &&
13585       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13586         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13587
13588        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13589         VTElt.getSizeInBits() <= 16)) ||
13590
13591        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13592         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13593
13594        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13595         VTElt.getSizeInBits() >= 32))))
13596     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13597
13598   unsigned int NumElts = VT.getVectorNumElements();
13599
13600   if (NumElts != 8 && NumElts != 16)
13601     return SDValue();
13602
13603   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13604     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13605       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13606     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13607   }
13608
13609   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13610   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13611
13612   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13613   Constant *C = ConstantInt::get(*DAG.getContext(),
13614     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13615
13616   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13617   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13618   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13619                           MachinePointerInfo::getConstantPool(),
13620                           false, false, false, Alignment);
13621   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13622   if (VT.is512BitVector())
13623     return Brcst;
13624   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13625 }
13626
13627 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13628                                 SelectionDAG &DAG) {
13629   MVT VT = Op->getSimpleValueType(0);
13630   SDValue In = Op->getOperand(0);
13631   MVT InVT = In.getSimpleValueType();
13632   SDLoc dl(Op);
13633
13634   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13635     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13636
13637   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13638       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13639       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13640     return SDValue();
13641
13642   if (Subtarget->hasInt256())
13643     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13644
13645   // Optimize vectors in AVX mode
13646   // Sign extend  v8i16 to v8i32 and
13647   //              v4i32 to v4i64
13648   //
13649   // Divide input vector into two parts
13650   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13651   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13652   // concat the vectors to original VT
13653
13654   unsigned NumElems = InVT.getVectorNumElements();
13655   SDValue Undef = DAG.getUNDEF(InVT);
13656
13657   SmallVector<int,8> ShufMask1(NumElems, -1);
13658   for (unsigned i = 0; i != NumElems/2; ++i)
13659     ShufMask1[i] = i;
13660
13661   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13662
13663   SmallVector<int,8> ShufMask2(NumElems, -1);
13664   for (unsigned i = 0; i != NumElems/2; ++i)
13665     ShufMask2[i] = i + NumElems/2;
13666
13667   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13668
13669   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13670                                 VT.getVectorNumElements()/2);
13671
13672   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13673   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13674
13675   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13676 }
13677
13678 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13679 // may emit an illegal shuffle but the expansion is still better than scalar
13680 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13681 // we'll emit a shuffle and a arithmetic shift.
13682 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13683 // TODO: It is possible to support ZExt by zeroing the undef values during
13684 // the shuffle phase or after the shuffle.
13685 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13686                                  SelectionDAG &DAG) {
13687   MVT RegVT = Op.getSimpleValueType();
13688   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13689   assert(RegVT.isInteger() &&
13690          "We only custom lower integer vector sext loads.");
13691
13692   // Nothing useful we can do without SSE2 shuffles.
13693   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13694
13695   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13696   SDLoc dl(Ld);
13697   EVT MemVT = Ld->getMemoryVT();
13698   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13699   unsigned RegSz = RegVT.getSizeInBits();
13700
13701   ISD::LoadExtType Ext = Ld->getExtensionType();
13702
13703   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13704          && "Only anyext and sext are currently implemented.");
13705   assert(MemVT != RegVT && "Cannot extend to the same type");
13706   assert(MemVT.isVector() && "Must load a vector from memory");
13707
13708   unsigned NumElems = RegVT.getVectorNumElements();
13709   unsigned MemSz = MemVT.getSizeInBits();
13710   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13711
13712   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13713     // The only way in which we have a legal 256-bit vector result but not the
13714     // integer 256-bit operations needed to directly lower a sextload is if we
13715     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13716     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13717     // correctly legalized. We do this late to allow the canonical form of
13718     // sextload to persist throughout the rest of the DAG combiner -- it wants
13719     // to fold together any extensions it can, and so will fuse a sign_extend
13720     // of an sextload into a sextload targeting a wider value.
13721     SDValue Load;
13722     if (MemSz == 128) {
13723       // Just switch this to a normal load.
13724       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13725                                        "it must be a legal 128-bit vector "
13726                                        "type!");
13727       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13728                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13729                   Ld->isInvariant(), Ld->getAlignment());
13730     } else {
13731       assert(MemSz < 128 &&
13732              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13733       // Do an sext load to a 128-bit vector type. We want to use the same
13734       // number of elements, but elements half as wide. This will end up being
13735       // recursively lowered by this routine, but will succeed as we definitely
13736       // have all the necessary features if we're using AVX1.
13737       EVT HalfEltVT =
13738           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13739       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13740       Load =
13741           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13742                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13743                          Ld->isNonTemporal(), Ld->isInvariant(),
13744                          Ld->getAlignment());
13745     }
13746
13747     // Replace chain users with the new chain.
13748     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13749     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13750
13751     // Finally, do a normal sign-extend to the desired register.
13752     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13753   }
13754
13755   // All sizes must be a power of two.
13756   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13757          "Non-power-of-two elements are not custom lowered!");
13758
13759   // Attempt to load the original value using scalar loads.
13760   // Find the largest scalar type that divides the total loaded size.
13761   MVT SclrLoadTy = MVT::i8;
13762   for (MVT Tp : MVT::integer_valuetypes()) {
13763     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13764       SclrLoadTy = Tp;
13765     }
13766   }
13767
13768   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13769   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13770       (64 <= MemSz))
13771     SclrLoadTy = MVT::f64;
13772
13773   // Calculate the number of scalar loads that we need to perform
13774   // in order to load our vector from memory.
13775   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13776
13777   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13778          "Can only lower sext loads with a single scalar load!");
13779
13780   unsigned loadRegZize = RegSz;
13781   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13782     loadRegZize /= 2;
13783
13784   // Represent our vector as a sequence of elements which are the
13785   // largest scalar that we can load.
13786   EVT LoadUnitVecVT = EVT::getVectorVT(
13787       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13788
13789   // Represent the data using the same element type that is stored in
13790   // memory. In practice, we ''widen'' MemVT.
13791   EVT WideVecVT =
13792       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13793                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13794
13795   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13796          "Invalid vector type");
13797
13798   // We can't shuffle using an illegal type.
13799   assert(TLI.isTypeLegal(WideVecVT) &&
13800          "We only lower types that form legal widened vector types");
13801
13802   SmallVector<SDValue, 8> Chains;
13803   SDValue Ptr = Ld->getBasePtr();
13804   SDValue Increment =
13805       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13806   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13807
13808   for (unsigned i = 0; i < NumLoads; ++i) {
13809     // Perform a single load.
13810     SDValue ScalarLoad =
13811         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13812                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13813                     Ld->getAlignment());
13814     Chains.push_back(ScalarLoad.getValue(1));
13815     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13816     // another round of DAGCombining.
13817     if (i == 0)
13818       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13819     else
13820       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13821                         ScalarLoad, DAG.getIntPtrConstant(i));
13822
13823     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13824   }
13825
13826   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13827
13828   // Bitcast the loaded value to a vector of the original element type, in
13829   // the size of the target vector type.
13830   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13831   unsigned SizeRatio = RegSz / MemSz;
13832
13833   if (Ext == ISD::SEXTLOAD) {
13834     // If we have SSE4.1, we can directly emit a VSEXT node.
13835     if (Subtarget->hasSSE41()) {
13836       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13837       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13838       return Sext;
13839     }
13840
13841     // Otherwise we'll shuffle the small elements in the high bits of the
13842     // larger type and perform an arithmetic shift. If the shift is not legal
13843     // it's better to scalarize.
13844     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13845            "We can't implement a sext load without an arithmetic right shift!");
13846
13847     // Redistribute the loaded elements into the different locations.
13848     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13849     for (unsigned i = 0; i != NumElems; ++i)
13850       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13851
13852     SDValue Shuff = DAG.getVectorShuffle(
13853         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13854
13855     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13856
13857     // Build the arithmetic shift.
13858     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13859                    MemVT.getVectorElementType().getSizeInBits();
13860     Shuff =
13861         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13862
13863     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13864     return Shuff;
13865   }
13866
13867   // Redistribute the loaded elements into the different locations.
13868   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13869   for (unsigned i = 0; i != NumElems; ++i)
13870     ShuffleVec[i * SizeRatio] = i;
13871
13872   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13873                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13874
13875   // Bitcast to the requested type.
13876   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13877   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13878   return Shuff;
13879 }
13880
13881 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13882 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13883 // from the AND / OR.
13884 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13885   Opc = Op.getOpcode();
13886   if (Opc != ISD::OR && Opc != ISD::AND)
13887     return false;
13888   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13889           Op.getOperand(0).hasOneUse() &&
13890           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13891           Op.getOperand(1).hasOneUse());
13892 }
13893
13894 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13895 // 1 and that the SETCC node has a single use.
13896 static bool isXor1OfSetCC(SDValue Op) {
13897   if (Op.getOpcode() != ISD::XOR)
13898     return false;
13899   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13900   if (N1C && N1C->getAPIntValue() == 1) {
13901     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13902       Op.getOperand(0).hasOneUse();
13903   }
13904   return false;
13905 }
13906
13907 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13908   bool addTest = true;
13909   SDValue Chain = Op.getOperand(0);
13910   SDValue Cond  = Op.getOperand(1);
13911   SDValue Dest  = Op.getOperand(2);
13912   SDLoc dl(Op);
13913   SDValue CC;
13914   bool Inverted = false;
13915
13916   if (Cond.getOpcode() == ISD::SETCC) {
13917     // Check for setcc([su]{add,sub,mul}o == 0).
13918     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13919         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13920         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13921         Cond.getOperand(0).getResNo() == 1 &&
13922         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13923          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13924          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13925          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13926          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13927          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13928       Inverted = true;
13929       Cond = Cond.getOperand(0);
13930     } else {
13931       SDValue NewCond = LowerSETCC(Cond, DAG);
13932       if (NewCond.getNode())
13933         Cond = NewCond;
13934     }
13935   }
13936 #if 0
13937   // FIXME: LowerXALUO doesn't handle these!!
13938   else if (Cond.getOpcode() == X86ISD::ADD  ||
13939            Cond.getOpcode() == X86ISD::SUB  ||
13940            Cond.getOpcode() == X86ISD::SMUL ||
13941            Cond.getOpcode() == X86ISD::UMUL)
13942     Cond = LowerXALUO(Cond, DAG);
13943 #endif
13944
13945   // Look pass (and (setcc_carry (cmp ...)), 1).
13946   if (Cond.getOpcode() == ISD::AND &&
13947       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13948     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13949     if (C && C->getAPIntValue() == 1)
13950       Cond = Cond.getOperand(0);
13951   }
13952
13953   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13954   // setting operand in place of the X86ISD::SETCC.
13955   unsigned CondOpcode = Cond.getOpcode();
13956   if (CondOpcode == X86ISD::SETCC ||
13957       CondOpcode == X86ISD::SETCC_CARRY) {
13958     CC = Cond.getOperand(0);
13959
13960     SDValue Cmp = Cond.getOperand(1);
13961     unsigned Opc = Cmp.getOpcode();
13962     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13963     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13964       Cond = Cmp;
13965       addTest = false;
13966     } else {
13967       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13968       default: break;
13969       case X86::COND_O:
13970       case X86::COND_B:
13971         // These can only come from an arithmetic instruction with overflow,
13972         // e.g. SADDO, UADDO.
13973         Cond = Cond.getNode()->getOperand(1);
13974         addTest = false;
13975         break;
13976       }
13977     }
13978   }
13979   CondOpcode = Cond.getOpcode();
13980   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13981       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13982       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13983        Cond.getOperand(0).getValueType() != MVT::i8)) {
13984     SDValue LHS = Cond.getOperand(0);
13985     SDValue RHS = Cond.getOperand(1);
13986     unsigned X86Opcode;
13987     unsigned X86Cond;
13988     SDVTList VTs;
13989     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13990     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13991     // X86ISD::INC).
13992     switch (CondOpcode) {
13993     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13994     case ISD::SADDO:
13995       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13996         if (C->isOne()) {
13997           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13998           break;
13999         }
14000       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14001     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14002     case ISD::SSUBO:
14003       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14004         if (C->isOne()) {
14005           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14006           break;
14007         }
14008       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14009     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14010     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14011     default: llvm_unreachable("unexpected overflowing operator");
14012     }
14013     if (Inverted)
14014       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14015     if (CondOpcode == ISD::UMULO)
14016       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14017                           MVT::i32);
14018     else
14019       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14020
14021     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14022
14023     if (CondOpcode == ISD::UMULO)
14024       Cond = X86Op.getValue(2);
14025     else
14026       Cond = X86Op.getValue(1);
14027
14028     CC = DAG.getConstant(X86Cond, MVT::i8);
14029     addTest = false;
14030   } else {
14031     unsigned CondOpc;
14032     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14033       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14034       if (CondOpc == ISD::OR) {
14035         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14036         // two branches instead of an explicit OR instruction with a
14037         // separate test.
14038         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14039             isX86LogicalCmp(Cmp)) {
14040           CC = Cond.getOperand(0).getOperand(0);
14041           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14042                               Chain, Dest, CC, Cmp);
14043           CC = Cond.getOperand(1).getOperand(0);
14044           Cond = Cmp;
14045           addTest = false;
14046         }
14047       } else { // ISD::AND
14048         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14049         // two branches instead of an explicit AND instruction with a
14050         // separate test. However, we only do this if this block doesn't
14051         // have a fall-through edge, because this requires an explicit
14052         // jmp when the condition is false.
14053         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14054             isX86LogicalCmp(Cmp) &&
14055             Op.getNode()->hasOneUse()) {
14056           X86::CondCode CCode =
14057             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14058           CCode = X86::GetOppositeBranchCondition(CCode);
14059           CC = DAG.getConstant(CCode, MVT::i8);
14060           SDNode *User = *Op.getNode()->use_begin();
14061           // Look for an unconditional branch following this conditional branch.
14062           // We need this because we need to reverse the successors in order
14063           // to implement FCMP_OEQ.
14064           if (User->getOpcode() == ISD::BR) {
14065             SDValue FalseBB = User->getOperand(1);
14066             SDNode *NewBR =
14067               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14068             assert(NewBR == User);
14069             (void)NewBR;
14070             Dest = FalseBB;
14071
14072             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14073                                 Chain, Dest, CC, Cmp);
14074             X86::CondCode CCode =
14075               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14076             CCode = X86::GetOppositeBranchCondition(CCode);
14077             CC = DAG.getConstant(CCode, MVT::i8);
14078             Cond = Cmp;
14079             addTest = false;
14080           }
14081         }
14082       }
14083     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14084       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14085       // It should be transformed during dag combiner except when the condition
14086       // is set by a arithmetics with overflow node.
14087       X86::CondCode CCode =
14088         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14089       CCode = X86::GetOppositeBranchCondition(CCode);
14090       CC = DAG.getConstant(CCode, MVT::i8);
14091       Cond = Cond.getOperand(0).getOperand(1);
14092       addTest = false;
14093     } else if (Cond.getOpcode() == ISD::SETCC &&
14094                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14095       // For FCMP_OEQ, we can emit
14096       // two branches instead of an explicit AND instruction with a
14097       // separate test. However, we only do this if this block doesn't
14098       // have a fall-through edge, because this requires an explicit
14099       // jmp when the condition is false.
14100       if (Op.getNode()->hasOneUse()) {
14101         SDNode *User = *Op.getNode()->use_begin();
14102         // Look for an unconditional branch following this conditional branch.
14103         // We need this because we need to reverse the successors in order
14104         // to implement FCMP_OEQ.
14105         if (User->getOpcode() == ISD::BR) {
14106           SDValue FalseBB = User->getOperand(1);
14107           SDNode *NewBR =
14108             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14109           assert(NewBR == User);
14110           (void)NewBR;
14111           Dest = FalseBB;
14112
14113           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14114                                     Cond.getOperand(0), Cond.getOperand(1));
14115           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14116           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14117           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14118                               Chain, Dest, CC, Cmp);
14119           CC = DAG.getConstant(X86::COND_P, MVT::i8);
14120           Cond = Cmp;
14121           addTest = false;
14122         }
14123       }
14124     } else if (Cond.getOpcode() == ISD::SETCC &&
14125                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14126       // For FCMP_UNE, we can emit
14127       // two branches instead of an explicit AND instruction with a
14128       // separate test. However, we only do this if this block doesn't
14129       // have a fall-through edge, because this requires an explicit
14130       // jmp when the condition is false.
14131       if (Op.getNode()->hasOneUse()) {
14132         SDNode *User = *Op.getNode()->use_begin();
14133         // Look for an unconditional branch following this conditional branch.
14134         // We need this because we need to reverse the successors in order
14135         // to implement FCMP_UNE.
14136         if (User->getOpcode() == ISD::BR) {
14137           SDValue FalseBB = User->getOperand(1);
14138           SDNode *NewBR =
14139             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14140           assert(NewBR == User);
14141           (void)NewBR;
14142
14143           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14144                                     Cond.getOperand(0), Cond.getOperand(1));
14145           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14146           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14147           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14148                               Chain, Dest, CC, Cmp);
14149           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14150           Cond = Cmp;
14151           addTest = false;
14152           Dest = FalseBB;
14153         }
14154       }
14155     }
14156   }
14157
14158   if (addTest) {
14159     // Look pass the truncate if the high bits are known zero.
14160     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14161         Cond = Cond.getOperand(0);
14162
14163     // We know the result of AND is compared against zero. Try to match
14164     // it to BT.
14165     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14166       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14167       if (NewSetCC.getNode()) {
14168         CC = NewSetCC.getOperand(0);
14169         Cond = NewSetCC.getOperand(1);
14170         addTest = false;
14171       }
14172     }
14173   }
14174
14175   if (addTest) {
14176     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14177     CC = DAG.getConstant(X86Cond, MVT::i8);
14178     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14179   }
14180   Cond = ConvertCmpIfNecessary(Cond, DAG);
14181   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14182                      Chain, Dest, CC, Cond);
14183 }
14184
14185 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14186 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14187 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14188 // that the guard pages used by the OS virtual memory manager are allocated in
14189 // correct sequence.
14190 SDValue
14191 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14192                                            SelectionDAG &DAG) const {
14193   MachineFunction &MF = DAG.getMachineFunction();
14194   bool SplitStack = MF.shouldSplitStack();
14195   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14196                SplitStack;
14197   SDLoc dl(Op);
14198
14199   if (!Lower) {
14200     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14201     SDNode* Node = Op.getNode();
14202
14203     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14204     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14205         " not tell us which reg is the stack pointer!");
14206     EVT VT = Node->getValueType(0);
14207     SDValue Tmp1 = SDValue(Node, 0);
14208     SDValue Tmp2 = SDValue(Node, 1);
14209     SDValue Tmp3 = Node->getOperand(2);
14210     SDValue Chain = Tmp1.getOperand(0);
14211
14212     // Chain the dynamic stack allocation so that it doesn't modify the stack
14213     // pointer when other instructions are using the stack.
14214     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14215         SDLoc(Node));
14216
14217     SDValue Size = Tmp2.getOperand(1);
14218     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14219     Chain = SP.getValue(1);
14220     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14221     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14222     unsigned StackAlign = TFI.getStackAlignment();
14223     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14224     if (Align > StackAlign)
14225       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14226           DAG.getConstant(-(uint64_t)Align, VT));
14227     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14228
14229     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14230         DAG.getIntPtrConstant(0, true), SDValue(),
14231         SDLoc(Node));
14232
14233     SDValue Ops[2] = { Tmp1, Tmp2 };
14234     return DAG.getMergeValues(Ops, dl);
14235   }
14236
14237   // Get the inputs.
14238   SDValue Chain = Op.getOperand(0);
14239   SDValue Size  = Op.getOperand(1);
14240   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14241   EVT VT = Op.getNode()->getValueType(0);
14242
14243   bool Is64Bit = Subtarget->is64Bit();
14244   EVT SPTy = getPointerTy();
14245
14246   if (SplitStack) {
14247     MachineRegisterInfo &MRI = MF.getRegInfo();
14248
14249     if (Is64Bit) {
14250       // The 64 bit implementation of segmented stacks needs to clobber both r10
14251       // r11. This makes it impossible to use it along with nested parameters.
14252       const Function *F = MF.getFunction();
14253
14254       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14255            I != E; ++I)
14256         if (I->hasNestAttr())
14257           report_fatal_error("Cannot use segmented stacks with functions that "
14258                              "have nested arguments.");
14259     }
14260
14261     const TargetRegisterClass *AddrRegClass =
14262       getRegClassFor(getPointerTy());
14263     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14264     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14265     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14266                                 DAG.getRegister(Vreg, SPTy));
14267     SDValue Ops1[2] = { Value, Chain };
14268     return DAG.getMergeValues(Ops1, dl);
14269   } else {
14270     SDValue Flag;
14271     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14272
14273     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14274     Flag = Chain.getValue(1);
14275     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14276
14277     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14278
14279     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14280     unsigned SPReg = RegInfo->getStackRegister();
14281     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14282     Chain = SP.getValue(1);
14283
14284     if (Align) {
14285       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14286                        DAG.getConstant(-(uint64_t)Align, VT));
14287       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14288     }
14289
14290     SDValue Ops1[2] = { SP, Chain };
14291     return DAG.getMergeValues(Ops1, dl);
14292   }
14293 }
14294
14295 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14296   MachineFunction &MF = DAG.getMachineFunction();
14297   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14298
14299   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14300   SDLoc DL(Op);
14301
14302   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14303     // vastart just stores the address of the VarArgsFrameIndex slot into the
14304     // memory location argument.
14305     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14306                                    getPointerTy());
14307     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14308                         MachinePointerInfo(SV), false, false, 0);
14309   }
14310
14311   // __va_list_tag:
14312   //   gp_offset         (0 - 6 * 8)
14313   //   fp_offset         (48 - 48 + 8 * 16)
14314   //   overflow_arg_area (point to parameters coming in memory).
14315   //   reg_save_area
14316   SmallVector<SDValue, 8> MemOps;
14317   SDValue FIN = Op.getOperand(1);
14318   // Store gp_offset
14319   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14320                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14321                                                MVT::i32),
14322                                FIN, MachinePointerInfo(SV), false, false, 0);
14323   MemOps.push_back(Store);
14324
14325   // Store fp_offset
14326   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14327                     FIN, DAG.getIntPtrConstant(4));
14328   Store = DAG.getStore(Op.getOperand(0), DL,
14329                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14330                                        MVT::i32),
14331                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14332   MemOps.push_back(Store);
14333
14334   // Store ptr to overflow_arg_area
14335   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14336                     FIN, DAG.getIntPtrConstant(4));
14337   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14338                                     getPointerTy());
14339   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14340                        MachinePointerInfo(SV, 8),
14341                        false, false, 0);
14342   MemOps.push_back(Store);
14343
14344   // Store ptr to reg_save_area.
14345   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14346                     FIN, DAG.getIntPtrConstant(8));
14347   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14348                                     getPointerTy());
14349   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14350                        MachinePointerInfo(SV, 16), false, false, 0);
14351   MemOps.push_back(Store);
14352   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14353 }
14354
14355 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14356   assert(Subtarget->is64Bit() &&
14357          "LowerVAARG only handles 64-bit va_arg!");
14358   assert((Subtarget->isTargetLinux() ||
14359           Subtarget->isTargetDarwin()) &&
14360           "Unhandled target in LowerVAARG");
14361   assert(Op.getNode()->getNumOperands() == 4);
14362   SDValue Chain = Op.getOperand(0);
14363   SDValue SrcPtr = Op.getOperand(1);
14364   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14365   unsigned Align = Op.getConstantOperandVal(3);
14366   SDLoc dl(Op);
14367
14368   EVT ArgVT = Op.getNode()->getValueType(0);
14369   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14370   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14371   uint8_t ArgMode;
14372
14373   // Decide which area this value should be read from.
14374   // TODO: Implement the AMD64 ABI in its entirety. This simple
14375   // selection mechanism works only for the basic types.
14376   if (ArgVT == MVT::f80) {
14377     llvm_unreachable("va_arg for f80 not yet implemented");
14378   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14379     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14380   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14381     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14382   } else {
14383     llvm_unreachable("Unhandled argument type in LowerVAARG");
14384   }
14385
14386   if (ArgMode == 2) {
14387     // Sanity Check: Make sure using fp_offset makes sense.
14388     assert(!DAG.getTarget().Options.UseSoftFloat &&
14389            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14390                Attribute::NoImplicitFloat)) &&
14391            Subtarget->hasSSE1());
14392   }
14393
14394   // Insert VAARG_64 node into the DAG
14395   // VAARG_64 returns two values: Variable Argument Address, Chain
14396   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, MVT::i32),
14397                        DAG.getConstant(ArgMode, MVT::i8),
14398                        DAG.getConstant(Align, MVT::i32)};
14399   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14400   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14401                                           VTs, InstOps, MVT::i64,
14402                                           MachinePointerInfo(SV),
14403                                           /*Align=*/0,
14404                                           /*Volatile=*/false,
14405                                           /*ReadMem=*/true,
14406                                           /*WriteMem=*/true);
14407   Chain = VAARG.getValue(1);
14408
14409   // Load the next argument and return it
14410   return DAG.getLoad(ArgVT, dl,
14411                      Chain,
14412                      VAARG,
14413                      MachinePointerInfo(),
14414                      false, false, false, 0);
14415 }
14416
14417 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14418                            SelectionDAG &DAG) {
14419   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14420   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14421   SDValue Chain = Op.getOperand(0);
14422   SDValue DstPtr = Op.getOperand(1);
14423   SDValue SrcPtr = Op.getOperand(2);
14424   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14425   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14426   SDLoc DL(Op);
14427
14428   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14429                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14430                        false,
14431                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14432 }
14433
14434 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14435 // amount is a constant. Takes immediate version of shift as input.
14436 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14437                                           SDValue SrcOp, uint64_t ShiftAmt,
14438                                           SelectionDAG &DAG) {
14439   MVT ElementType = VT.getVectorElementType();
14440
14441   // Fold this packed shift into its first operand if ShiftAmt is 0.
14442   if (ShiftAmt == 0)
14443     return SrcOp;
14444
14445   // Check for ShiftAmt >= element width
14446   if (ShiftAmt >= ElementType.getSizeInBits()) {
14447     if (Opc == X86ISD::VSRAI)
14448       ShiftAmt = ElementType.getSizeInBits() - 1;
14449     else
14450       return DAG.getConstant(0, VT);
14451   }
14452
14453   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14454          && "Unknown target vector shift-by-constant node");
14455
14456   // Fold this packed vector shift into a build vector if SrcOp is a
14457   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14458   if (VT == SrcOp.getSimpleValueType() &&
14459       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14460     SmallVector<SDValue, 8> Elts;
14461     unsigned NumElts = SrcOp->getNumOperands();
14462     ConstantSDNode *ND;
14463
14464     switch(Opc) {
14465     default: llvm_unreachable(nullptr);
14466     case X86ISD::VSHLI:
14467       for (unsigned i=0; i!=NumElts; ++i) {
14468         SDValue CurrentOp = SrcOp->getOperand(i);
14469         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14470           Elts.push_back(CurrentOp);
14471           continue;
14472         }
14473         ND = cast<ConstantSDNode>(CurrentOp);
14474         const APInt &C = ND->getAPIntValue();
14475         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14476       }
14477       break;
14478     case X86ISD::VSRLI:
14479       for (unsigned i=0; i!=NumElts; ++i) {
14480         SDValue CurrentOp = SrcOp->getOperand(i);
14481         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14482           Elts.push_back(CurrentOp);
14483           continue;
14484         }
14485         ND = cast<ConstantSDNode>(CurrentOp);
14486         const APInt &C = ND->getAPIntValue();
14487         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14488       }
14489       break;
14490     case X86ISD::VSRAI:
14491       for (unsigned i=0; i!=NumElts; ++i) {
14492         SDValue CurrentOp = SrcOp->getOperand(i);
14493         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14494           Elts.push_back(CurrentOp);
14495           continue;
14496         }
14497         ND = cast<ConstantSDNode>(CurrentOp);
14498         const APInt &C = ND->getAPIntValue();
14499         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14500       }
14501       break;
14502     }
14503
14504     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14505   }
14506
14507   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14508 }
14509
14510 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14511 // may or may not be a constant. Takes immediate version of shift as input.
14512 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14513                                    SDValue SrcOp, SDValue ShAmt,
14514                                    SelectionDAG &DAG) {
14515   MVT SVT = ShAmt.getSimpleValueType();
14516   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14517
14518   // Catch shift-by-constant.
14519   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14520     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14521                                       CShAmt->getZExtValue(), DAG);
14522
14523   // Change opcode to non-immediate version
14524   switch (Opc) {
14525     default: llvm_unreachable("Unknown target vector shift node");
14526     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14527     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14528     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14529   }
14530
14531   const X86Subtarget &Subtarget =
14532       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14533   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14534       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14535     // Let the shuffle legalizer expand this shift amount node.
14536     SDValue Op0 = ShAmt.getOperand(0);
14537     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14538     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14539   } else {
14540     // Need to build a vector containing shift amount.
14541     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14542     SmallVector<SDValue, 4> ShOps;
14543     ShOps.push_back(ShAmt);
14544     if (SVT == MVT::i32) {
14545       ShOps.push_back(DAG.getConstant(0, SVT));
14546       ShOps.push_back(DAG.getUNDEF(SVT));
14547     }
14548     ShOps.push_back(DAG.getUNDEF(SVT));
14549
14550     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14551     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14552   }
14553
14554   // The return type has to be a 128-bit type with the same element
14555   // type as the input type.
14556   MVT EltVT = VT.getVectorElementType();
14557   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14558
14559   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14560   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14561 }
14562
14563 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14564 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14565 /// necessary casting for \p Mask when lowering masking intrinsics.
14566 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14567                                     SDValue PreservedSrc,
14568                                     const X86Subtarget *Subtarget,
14569                                     SelectionDAG &DAG) {
14570     EVT VT = Op.getValueType();
14571     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14572                                   MVT::i1, VT.getVectorNumElements());
14573     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14574                                      Mask.getValueType().getSizeInBits());
14575     SDLoc dl(Op);
14576
14577     assert(MaskVT.isSimple() && "invalid mask type");
14578
14579     if (isAllOnes(Mask))
14580       return Op;
14581
14582     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14583     // are extracted by EXTRACT_SUBVECTOR.
14584     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14585                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14586                               DAG.getIntPtrConstant(0));
14587
14588     switch (Op.getOpcode()) {
14589       default: break;
14590       case X86ISD::PCMPEQM:
14591       case X86ISD::PCMPGTM:
14592       case X86ISD::CMPM:
14593       case X86ISD::CMPMU:
14594         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14595     }
14596     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14597       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14598     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14599 }
14600
14601 /// \brief Creates an SDNode for a predicated scalar operation.
14602 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14603 /// The mask is comming as MVT::i8 and it should be truncated
14604 /// to MVT::i1 while lowering masking intrinsics.
14605 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14606 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14607 /// a scalar instruction.
14608 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14609                                     SDValue PreservedSrc,
14610                                     const X86Subtarget *Subtarget,
14611                                     SelectionDAG &DAG) {
14612     if (isAllOnes(Mask))
14613       return Op;
14614
14615     EVT VT = Op.getValueType();
14616     SDLoc dl(Op);
14617     // The mask should be of type MVT::i1
14618     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14619
14620     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14621       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14622     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14623 }
14624
14625 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14626                                        SelectionDAG &DAG) {
14627   SDLoc dl(Op);
14628   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14629   EVT VT = Op.getValueType();
14630   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14631   if (IntrData) {
14632     switch(IntrData->Type) {
14633     case INTR_TYPE_1OP:
14634       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14635     case INTR_TYPE_2OP:
14636       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14637         Op.getOperand(2));
14638     case INTR_TYPE_3OP:
14639       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14640         Op.getOperand(2), Op.getOperand(3));
14641     case INTR_TYPE_1OP_MASK_RM: {
14642       SDValue Src = Op.getOperand(1);
14643       SDValue Src0 = Op.getOperand(2);
14644       SDValue Mask = Op.getOperand(3);
14645       SDValue RoundingMode = Op.getOperand(4);
14646       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14647                                               RoundingMode),
14648                                   Mask, Src0, Subtarget, DAG);
14649     }
14650     case INTR_TYPE_SCALAR_MASK_RM: {
14651       SDValue Src1 = Op.getOperand(1);
14652       SDValue Src2 = Op.getOperand(2);
14653       SDValue Src0 = Op.getOperand(3);
14654       SDValue Mask = Op.getOperand(4);
14655       // There are 2 kinds of intrinsics in this group:
14656       // (1) With supress-all-exceptions (sae) - 6 operands
14657       // (2) With rounding mode and sae - 7 operands.
14658       if (Op.getNumOperands() == 6) {
14659         SDValue Sae  = Op.getOperand(5);
14660         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14661                                                 Sae),
14662                                     Mask, Src0, Subtarget, DAG);
14663       }
14664       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14665       SDValue RoundingMode  = Op.getOperand(5);
14666       SDValue Sae  = Op.getOperand(6);
14667       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14668                                               RoundingMode, Sae),
14669                                   Mask, Src0, Subtarget, DAG);
14670     }
14671     case INTR_TYPE_2OP_MASK: {
14672       SDValue Src1 = Op.getOperand(1);
14673       SDValue Src2 = Op.getOperand(2);
14674       SDValue PassThru = Op.getOperand(3);
14675       SDValue Mask = Op.getOperand(4);
14676       // We specify 2 possible opcodes for intrinsics with rounding modes.
14677       // First, we check if the intrinsic may have non-default rounding mode,
14678       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14679       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14680       if (IntrWithRoundingModeOpcode != 0) {
14681         SDValue Rnd = Op.getOperand(5);
14682         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14683         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14684           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14685                                       dl, Op.getValueType(),
14686                                       Src1, Src2, Rnd),
14687                                       Mask, PassThru, Subtarget, DAG);
14688         }
14689       }
14690       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14691                                               Src1,Src2),
14692                                   Mask, PassThru, Subtarget, DAG);
14693     }
14694     case FMA_OP_MASK: {
14695       SDValue Src1 = Op.getOperand(1);
14696       SDValue Src2 = Op.getOperand(2);
14697       SDValue Src3 = Op.getOperand(3);
14698       SDValue Mask = Op.getOperand(4);
14699       // We specify 2 possible opcodes for intrinsics with rounding modes.
14700       // First, we check if the intrinsic may have non-default rounding mode,
14701       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14702       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14703       if (IntrWithRoundingModeOpcode != 0) {
14704         SDValue Rnd = Op.getOperand(5);
14705         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14706             X86::STATIC_ROUNDING::CUR_DIRECTION)
14707           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14708                                                   dl, Op.getValueType(),
14709                                                   Src1, Src2, Src3, Rnd),
14710                                       Mask, Src1, Subtarget, DAG);
14711       }
14712       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14713                                               dl, Op.getValueType(),
14714                                               Src1, Src2, Src3),
14715                                   Mask, Src1, Subtarget, DAG);
14716     }
14717     case CMP_MASK:
14718     case CMP_MASK_CC: {
14719       // Comparison intrinsics with masks.
14720       // Example of transformation:
14721       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14722       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14723       // (i8 (bitcast
14724       //   (v8i1 (insert_subvector undef,
14725       //           (v2i1 (and (PCMPEQM %a, %b),
14726       //                      (extract_subvector
14727       //                         (v8i1 (bitcast %mask)), 0))), 0))))
14728       EVT VT = Op.getOperand(1).getValueType();
14729       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14730                                     VT.getVectorNumElements());
14731       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14732       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14733                                        Mask.getValueType().getSizeInBits());
14734       SDValue Cmp;
14735       if (IntrData->Type == CMP_MASK_CC) {
14736         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14737                     Op.getOperand(2), Op.getOperand(3));
14738       } else {
14739         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14740         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14741                     Op.getOperand(2));
14742       }
14743       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14744                                              DAG.getTargetConstant(0, MaskVT),
14745                                              Subtarget, DAG);
14746       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14747                                 DAG.getUNDEF(BitcastVT), CmpMask,
14748                                 DAG.getIntPtrConstant(0));
14749       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14750     }
14751     case COMI: { // Comparison intrinsics
14752       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14753       SDValue LHS = Op.getOperand(1);
14754       SDValue RHS = Op.getOperand(2);
14755       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14756       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14757       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14758       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14759                                   DAG.getConstant(X86CC, MVT::i8), Cond);
14760       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14761     }
14762     case VSHIFT:
14763       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14764                                  Op.getOperand(1), Op.getOperand(2), DAG);
14765     case VSHIFT_MASK:
14766       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
14767                                                       Op.getSimpleValueType(),
14768                                                       Op.getOperand(1),
14769                                                       Op.getOperand(2), DAG),
14770                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
14771                                   DAG);
14772     case COMPRESS_EXPAND_IN_REG: {
14773       SDValue Mask = Op.getOperand(3);
14774       SDValue DataToCompress = Op.getOperand(1);
14775       SDValue PassThru = Op.getOperand(2);
14776       if (isAllOnes(Mask)) // return data as is
14777         return Op.getOperand(1);
14778       EVT VT = Op.getValueType();
14779       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14780                                     VT.getVectorNumElements());
14781       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14782                                        Mask.getValueType().getSizeInBits());
14783       SDLoc dl(Op);
14784       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14785                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14786                                   DAG.getIntPtrConstant(0));
14787
14788       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
14789                          PassThru);
14790     }
14791     case BLEND: {
14792       SDValue Mask = Op.getOperand(3);
14793       EVT VT = Op.getValueType();
14794       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14795                                     VT.getVectorNumElements());
14796       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14797                                        Mask.getValueType().getSizeInBits());
14798       SDLoc dl(Op);
14799       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14800                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14801                                   DAG.getIntPtrConstant(0));
14802       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
14803                          Op.getOperand(2));
14804     }
14805     default:
14806       break;
14807     }
14808   }
14809
14810   switch (IntNo) {
14811   default: return SDValue();    // Don't custom lower most intrinsics.
14812
14813   case Intrinsic::x86_avx2_permd:
14814   case Intrinsic::x86_avx2_permps:
14815     // Operands intentionally swapped. Mask is last operand to intrinsic,
14816     // but second operand for node/instruction.
14817     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14818                        Op.getOperand(2), Op.getOperand(1));
14819
14820   case Intrinsic::x86_avx512_mask_valign_q_512:
14821   case Intrinsic::x86_avx512_mask_valign_d_512:
14822     // Vector source operands are swapped.
14823     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14824                                             Op.getValueType(), Op.getOperand(2),
14825                                             Op.getOperand(1),
14826                                             Op.getOperand(3)),
14827                                 Op.getOperand(5), Op.getOperand(4),
14828                                 Subtarget, DAG);
14829
14830   // ptest and testp intrinsics. The intrinsic these come from are designed to
14831   // return an integer value, not just an instruction so lower it to the ptest
14832   // or testp pattern and a setcc for the result.
14833   case Intrinsic::x86_sse41_ptestz:
14834   case Intrinsic::x86_sse41_ptestc:
14835   case Intrinsic::x86_sse41_ptestnzc:
14836   case Intrinsic::x86_avx_ptestz_256:
14837   case Intrinsic::x86_avx_ptestc_256:
14838   case Intrinsic::x86_avx_ptestnzc_256:
14839   case Intrinsic::x86_avx_vtestz_ps:
14840   case Intrinsic::x86_avx_vtestc_ps:
14841   case Intrinsic::x86_avx_vtestnzc_ps:
14842   case Intrinsic::x86_avx_vtestz_pd:
14843   case Intrinsic::x86_avx_vtestc_pd:
14844   case Intrinsic::x86_avx_vtestnzc_pd:
14845   case Intrinsic::x86_avx_vtestz_ps_256:
14846   case Intrinsic::x86_avx_vtestc_ps_256:
14847   case Intrinsic::x86_avx_vtestnzc_ps_256:
14848   case Intrinsic::x86_avx_vtestz_pd_256:
14849   case Intrinsic::x86_avx_vtestc_pd_256:
14850   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14851     bool IsTestPacked = false;
14852     unsigned X86CC;
14853     switch (IntNo) {
14854     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14855     case Intrinsic::x86_avx_vtestz_ps:
14856     case Intrinsic::x86_avx_vtestz_pd:
14857     case Intrinsic::x86_avx_vtestz_ps_256:
14858     case Intrinsic::x86_avx_vtestz_pd_256:
14859       IsTestPacked = true; // Fallthrough
14860     case Intrinsic::x86_sse41_ptestz:
14861     case Intrinsic::x86_avx_ptestz_256:
14862       // ZF = 1
14863       X86CC = X86::COND_E;
14864       break;
14865     case Intrinsic::x86_avx_vtestc_ps:
14866     case Intrinsic::x86_avx_vtestc_pd:
14867     case Intrinsic::x86_avx_vtestc_ps_256:
14868     case Intrinsic::x86_avx_vtestc_pd_256:
14869       IsTestPacked = true; // Fallthrough
14870     case Intrinsic::x86_sse41_ptestc:
14871     case Intrinsic::x86_avx_ptestc_256:
14872       // CF = 1
14873       X86CC = X86::COND_B;
14874       break;
14875     case Intrinsic::x86_avx_vtestnzc_ps:
14876     case Intrinsic::x86_avx_vtestnzc_pd:
14877     case Intrinsic::x86_avx_vtestnzc_ps_256:
14878     case Intrinsic::x86_avx_vtestnzc_pd_256:
14879       IsTestPacked = true; // Fallthrough
14880     case Intrinsic::x86_sse41_ptestnzc:
14881     case Intrinsic::x86_avx_ptestnzc_256:
14882       // ZF and CF = 0
14883       X86CC = X86::COND_A;
14884       break;
14885     }
14886
14887     SDValue LHS = Op.getOperand(1);
14888     SDValue RHS = Op.getOperand(2);
14889     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14890     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14891     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14892     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14893     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14894   }
14895   case Intrinsic::x86_avx512_kortestz_w:
14896   case Intrinsic::x86_avx512_kortestc_w: {
14897     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14898     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14899     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14900     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14901     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14902     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14903     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14904   }
14905
14906   case Intrinsic::x86_sse42_pcmpistria128:
14907   case Intrinsic::x86_sse42_pcmpestria128:
14908   case Intrinsic::x86_sse42_pcmpistric128:
14909   case Intrinsic::x86_sse42_pcmpestric128:
14910   case Intrinsic::x86_sse42_pcmpistrio128:
14911   case Intrinsic::x86_sse42_pcmpestrio128:
14912   case Intrinsic::x86_sse42_pcmpistris128:
14913   case Intrinsic::x86_sse42_pcmpestris128:
14914   case Intrinsic::x86_sse42_pcmpistriz128:
14915   case Intrinsic::x86_sse42_pcmpestriz128: {
14916     unsigned Opcode;
14917     unsigned X86CC;
14918     switch (IntNo) {
14919     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14920     case Intrinsic::x86_sse42_pcmpistria128:
14921       Opcode = X86ISD::PCMPISTRI;
14922       X86CC = X86::COND_A;
14923       break;
14924     case Intrinsic::x86_sse42_pcmpestria128:
14925       Opcode = X86ISD::PCMPESTRI;
14926       X86CC = X86::COND_A;
14927       break;
14928     case Intrinsic::x86_sse42_pcmpistric128:
14929       Opcode = X86ISD::PCMPISTRI;
14930       X86CC = X86::COND_B;
14931       break;
14932     case Intrinsic::x86_sse42_pcmpestric128:
14933       Opcode = X86ISD::PCMPESTRI;
14934       X86CC = X86::COND_B;
14935       break;
14936     case Intrinsic::x86_sse42_pcmpistrio128:
14937       Opcode = X86ISD::PCMPISTRI;
14938       X86CC = X86::COND_O;
14939       break;
14940     case Intrinsic::x86_sse42_pcmpestrio128:
14941       Opcode = X86ISD::PCMPESTRI;
14942       X86CC = X86::COND_O;
14943       break;
14944     case Intrinsic::x86_sse42_pcmpistris128:
14945       Opcode = X86ISD::PCMPISTRI;
14946       X86CC = X86::COND_S;
14947       break;
14948     case Intrinsic::x86_sse42_pcmpestris128:
14949       Opcode = X86ISD::PCMPESTRI;
14950       X86CC = X86::COND_S;
14951       break;
14952     case Intrinsic::x86_sse42_pcmpistriz128:
14953       Opcode = X86ISD::PCMPISTRI;
14954       X86CC = X86::COND_E;
14955       break;
14956     case Intrinsic::x86_sse42_pcmpestriz128:
14957       Opcode = X86ISD::PCMPESTRI;
14958       X86CC = X86::COND_E;
14959       break;
14960     }
14961     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14962     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14963     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14964     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14965                                 DAG.getConstant(X86CC, MVT::i8),
14966                                 SDValue(PCMP.getNode(), 1));
14967     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14968   }
14969
14970   case Intrinsic::x86_sse42_pcmpistri128:
14971   case Intrinsic::x86_sse42_pcmpestri128: {
14972     unsigned Opcode;
14973     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14974       Opcode = X86ISD::PCMPISTRI;
14975     else
14976       Opcode = X86ISD::PCMPESTRI;
14977
14978     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14979     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14980     return DAG.getNode(Opcode, dl, VTs, NewOps);
14981   }
14982   }
14983 }
14984
14985 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14986                               SDValue Src, SDValue Mask, SDValue Base,
14987                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14988                               const X86Subtarget * Subtarget) {
14989   SDLoc dl(Op);
14990   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14991   assert(C && "Invalid scale type");
14992   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14993   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14994                              Index.getSimpleValueType().getVectorNumElements());
14995   SDValue MaskInReg;
14996   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14997   if (MaskC)
14998     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14999   else
15000     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15001   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15002   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15003   SDValue Segment = DAG.getRegister(0, MVT::i32);
15004   if (Src.getOpcode() == ISD::UNDEF)
15005     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15006   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15007   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15008   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15009   return DAG.getMergeValues(RetOps, dl);
15010 }
15011
15012 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15013                                SDValue Src, SDValue Mask, SDValue Base,
15014                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15015   SDLoc dl(Op);
15016   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15017   assert(C && "Invalid scale type");
15018   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15019   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15020   SDValue Segment = DAG.getRegister(0, MVT::i32);
15021   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15022                              Index.getSimpleValueType().getVectorNumElements());
15023   SDValue MaskInReg;
15024   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15025   if (MaskC)
15026     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15027   else
15028     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15029   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15030   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15031   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15032   return SDValue(Res, 1);
15033 }
15034
15035 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15036                                SDValue Mask, SDValue Base, SDValue Index,
15037                                SDValue ScaleOp, SDValue Chain) {
15038   SDLoc dl(Op);
15039   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15040   assert(C && "Invalid scale type");
15041   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15042   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15043   SDValue Segment = DAG.getRegister(0, MVT::i32);
15044   EVT MaskVT =
15045     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15046   SDValue MaskInReg;
15047   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15048   if (MaskC)
15049     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15050   else
15051     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15052   //SDVTList VTs = DAG.getVTList(MVT::Other);
15053   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15054   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15055   return SDValue(Res, 0);
15056 }
15057
15058 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15059 // read performance monitor counters (x86_rdpmc).
15060 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15061                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15062                               SmallVectorImpl<SDValue> &Results) {
15063   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15064   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15065   SDValue LO, HI;
15066
15067   // The ECX register is used to select the index of the performance counter
15068   // to read.
15069   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15070                                    N->getOperand(2));
15071   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15072
15073   // Reads the content of a 64-bit performance counter and returns it in the
15074   // registers EDX:EAX.
15075   if (Subtarget->is64Bit()) {
15076     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15077     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15078                             LO.getValue(2));
15079   } else {
15080     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15081     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15082                             LO.getValue(2));
15083   }
15084   Chain = HI.getValue(1);
15085
15086   if (Subtarget->is64Bit()) {
15087     // The EAX register is loaded with the low-order 32 bits. The EDX register
15088     // is loaded with the supported high-order bits of the counter.
15089     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15090                               DAG.getConstant(32, MVT::i8));
15091     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15092     Results.push_back(Chain);
15093     return;
15094   }
15095
15096   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15097   SDValue Ops[] = { LO, HI };
15098   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15099   Results.push_back(Pair);
15100   Results.push_back(Chain);
15101 }
15102
15103 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15104 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15105 // also used to custom lower READCYCLECOUNTER nodes.
15106 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15107                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15108                               SmallVectorImpl<SDValue> &Results) {
15109   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15110   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15111   SDValue LO, HI;
15112
15113   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15114   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15115   // and the EAX register is loaded with the low-order 32 bits.
15116   if (Subtarget->is64Bit()) {
15117     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15118     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15119                             LO.getValue(2));
15120   } else {
15121     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15122     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15123                             LO.getValue(2));
15124   }
15125   SDValue Chain = HI.getValue(1);
15126
15127   if (Opcode == X86ISD::RDTSCP_DAG) {
15128     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15129
15130     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15131     // the ECX register. Add 'ecx' explicitly to the chain.
15132     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15133                                      HI.getValue(2));
15134     // Explicitly store the content of ECX at the location passed in input
15135     // to the 'rdtscp' intrinsic.
15136     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15137                          MachinePointerInfo(), false, false, 0);
15138   }
15139
15140   if (Subtarget->is64Bit()) {
15141     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15142     // the EAX register is loaded with the low-order 32 bits.
15143     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15144                               DAG.getConstant(32, MVT::i8));
15145     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15146     Results.push_back(Chain);
15147     return;
15148   }
15149
15150   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15151   SDValue Ops[] = { LO, HI };
15152   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15153   Results.push_back(Pair);
15154   Results.push_back(Chain);
15155 }
15156
15157 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15158                                      SelectionDAG &DAG) {
15159   SmallVector<SDValue, 2> Results;
15160   SDLoc DL(Op);
15161   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15162                           Results);
15163   return DAG.getMergeValues(Results, DL);
15164 }
15165
15166
15167 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15168                                       SelectionDAG &DAG) {
15169   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15170
15171   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15172   if (!IntrData)
15173     return SDValue();
15174
15175   SDLoc dl(Op);
15176   switch(IntrData->Type) {
15177   default:
15178     llvm_unreachable("Unknown Intrinsic Type");
15179     break;
15180   case RDSEED:
15181   case RDRAND: {
15182     // Emit the node with the right value type.
15183     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15184     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15185
15186     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15187     // Otherwise return the value from Rand, which is always 0, casted to i32.
15188     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15189                       DAG.getConstant(1, Op->getValueType(1)),
15190                       DAG.getConstant(X86::COND_B, MVT::i32),
15191                       SDValue(Result.getNode(), 1) };
15192     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15193                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15194                                   Ops);
15195
15196     // Return { result, isValid, chain }.
15197     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15198                        SDValue(Result.getNode(), 2));
15199   }
15200   case GATHER: {
15201   //gather(v1, mask, index, base, scale);
15202     SDValue Chain = Op.getOperand(0);
15203     SDValue Src   = Op.getOperand(2);
15204     SDValue Base  = Op.getOperand(3);
15205     SDValue Index = Op.getOperand(4);
15206     SDValue Mask  = Op.getOperand(5);
15207     SDValue Scale = Op.getOperand(6);
15208     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15209                           Subtarget);
15210   }
15211   case SCATTER: {
15212   //scatter(base, mask, index, v1, scale);
15213     SDValue Chain = Op.getOperand(0);
15214     SDValue Base  = Op.getOperand(2);
15215     SDValue Mask  = Op.getOperand(3);
15216     SDValue Index = Op.getOperand(4);
15217     SDValue Src   = Op.getOperand(5);
15218     SDValue Scale = Op.getOperand(6);
15219     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15220   }
15221   case PREFETCH: {
15222     SDValue Hint = Op.getOperand(6);
15223     unsigned HintVal;
15224     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15225         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15226       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15227     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15228     SDValue Chain = Op.getOperand(0);
15229     SDValue Mask  = Op.getOperand(2);
15230     SDValue Index = Op.getOperand(3);
15231     SDValue Base  = Op.getOperand(4);
15232     SDValue Scale = Op.getOperand(5);
15233     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15234   }
15235   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15236   case RDTSC: {
15237     SmallVector<SDValue, 2> Results;
15238     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15239     return DAG.getMergeValues(Results, dl);
15240   }
15241   // Read Performance Monitoring Counters.
15242   case RDPMC: {
15243     SmallVector<SDValue, 2> Results;
15244     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15245     return DAG.getMergeValues(Results, dl);
15246   }
15247   // XTEST intrinsics.
15248   case XTEST: {
15249     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15250     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15251     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15252                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15253                                 InTrans);
15254     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15255     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15256                        Ret, SDValue(InTrans.getNode(), 1));
15257   }
15258   // ADC/ADCX/SBB
15259   case ADX: {
15260     SmallVector<SDValue, 2> Results;
15261     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15262     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15263     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15264                                 DAG.getConstant(-1, MVT::i8));
15265     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15266                               Op.getOperand(4), GenCF.getValue(1));
15267     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15268                                  Op.getOperand(5), MachinePointerInfo(),
15269                                  false, false, 0);
15270     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15271                                 DAG.getConstant(X86::COND_B, MVT::i8),
15272                                 Res.getValue(1));
15273     Results.push_back(SetCC);
15274     Results.push_back(Store);
15275     return DAG.getMergeValues(Results, dl);
15276   }
15277   case COMPRESS_TO_MEM: {
15278     SDLoc dl(Op);
15279     SDValue Mask = Op.getOperand(4);
15280     SDValue DataToCompress = Op.getOperand(3);
15281     SDValue Addr = Op.getOperand(2);
15282     SDValue Chain = Op.getOperand(0);
15283
15284     if (isAllOnes(Mask)) // return just a store
15285       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15286                           MachinePointerInfo(), false, false, 0);
15287
15288     EVT VT = DataToCompress.getValueType();
15289     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15290                                   VT.getVectorNumElements());
15291     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15292                                      Mask.getValueType().getSizeInBits());
15293     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15294                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15295                                 DAG.getIntPtrConstant(0));
15296
15297     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15298                                       DataToCompress, DAG.getUNDEF(VT));
15299     return DAG.getStore(Chain, dl, Compressed, Addr,
15300                         MachinePointerInfo(), false, false, 0);
15301   }
15302   case EXPAND_FROM_MEM: {
15303     SDLoc dl(Op);
15304     SDValue Mask = Op.getOperand(4);
15305     SDValue PathThru = Op.getOperand(3);
15306     SDValue Addr = Op.getOperand(2);
15307     SDValue Chain = Op.getOperand(0);
15308     EVT VT = Op.getValueType();
15309
15310     if (isAllOnes(Mask)) // return just a load
15311       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15312                          false, 0);
15313     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15314                                   VT.getVectorNumElements());
15315     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15316                                      Mask.getValueType().getSizeInBits());
15317     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15318                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15319                                 DAG.getIntPtrConstant(0));
15320
15321     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15322                                    false, false, false, 0);
15323
15324     SDValue Results[] = {
15325         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15326         Chain};
15327     return DAG.getMergeValues(Results, dl);
15328   }
15329   }
15330 }
15331
15332 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15333                                            SelectionDAG &DAG) const {
15334   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15335   MFI->setReturnAddressIsTaken(true);
15336
15337   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15338     return SDValue();
15339
15340   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15341   SDLoc dl(Op);
15342   EVT PtrVT = getPointerTy();
15343
15344   if (Depth > 0) {
15345     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15346     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15347     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15348     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15349                        DAG.getNode(ISD::ADD, dl, PtrVT,
15350                                    FrameAddr, Offset),
15351                        MachinePointerInfo(), false, false, false, 0);
15352   }
15353
15354   // Just load the return address.
15355   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15356   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15357                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15358 }
15359
15360 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15361   MachineFunction &MF = DAG.getMachineFunction();
15362   MachineFrameInfo *MFI = MF.getFrameInfo();
15363   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15364   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15365   EVT VT = Op.getValueType();
15366
15367   MFI->setFrameAddressIsTaken(true);
15368
15369   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15370     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15371     // is not possible to crawl up the stack without looking at the unwind codes
15372     // simultaneously.
15373     int FrameAddrIndex = FuncInfo->getFAIndex();
15374     if (!FrameAddrIndex) {
15375       // Set up a frame object for the return address.
15376       unsigned SlotSize = RegInfo->getSlotSize();
15377       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15378           SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15379       FuncInfo->setFAIndex(FrameAddrIndex);
15380     }
15381     return DAG.getFrameIndex(FrameAddrIndex, VT);
15382   }
15383
15384   unsigned FrameReg =
15385       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15386   SDLoc dl(Op);  // FIXME probably not meaningful
15387   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15388   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15389           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15390          "Invalid Frame Register!");
15391   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15392   while (Depth--)
15393     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15394                             MachinePointerInfo(),
15395                             false, false, false, 0);
15396   return FrameAddr;
15397 }
15398
15399 // FIXME? Maybe this could be a TableGen attribute on some registers and
15400 // this table could be generated automatically from RegInfo.
15401 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15402                                               EVT VT) const {
15403   unsigned Reg = StringSwitch<unsigned>(RegName)
15404                        .Case("esp", X86::ESP)
15405                        .Case("rsp", X86::RSP)
15406                        .Default(0);
15407   if (Reg)
15408     return Reg;
15409   report_fatal_error("Invalid register name global variable");
15410 }
15411
15412 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15413                                                      SelectionDAG &DAG) const {
15414   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15415   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15416 }
15417
15418 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15419   SDValue Chain     = Op.getOperand(0);
15420   SDValue Offset    = Op.getOperand(1);
15421   SDValue Handler   = Op.getOperand(2);
15422   SDLoc dl      (Op);
15423
15424   EVT PtrVT = getPointerTy();
15425   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15426   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15427   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15428           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15429          "Invalid Frame Register!");
15430   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15431   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15432
15433   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15434                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15435   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15436   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15437                        false, false, 0);
15438   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15439
15440   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15441                      DAG.getRegister(StoreAddrReg, PtrVT));
15442 }
15443
15444 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15445                                                SelectionDAG &DAG) const {
15446   SDLoc DL(Op);
15447   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15448                      DAG.getVTList(MVT::i32, MVT::Other),
15449                      Op.getOperand(0), Op.getOperand(1));
15450 }
15451
15452 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15453                                                 SelectionDAG &DAG) const {
15454   SDLoc DL(Op);
15455   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15456                      Op.getOperand(0), Op.getOperand(1));
15457 }
15458
15459 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15460   return Op.getOperand(0);
15461 }
15462
15463 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15464                                                 SelectionDAG &DAG) const {
15465   SDValue Root = Op.getOperand(0);
15466   SDValue Trmp = Op.getOperand(1); // trampoline
15467   SDValue FPtr = Op.getOperand(2); // nested function
15468   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15469   SDLoc dl (Op);
15470
15471   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15472   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15473
15474   if (Subtarget->is64Bit()) {
15475     SDValue OutChains[6];
15476
15477     // Large code-model.
15478     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15479     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15480
15481     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15482     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15483
15484     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15485
15486     // Load the pointer to the nested function into R11.
15487     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15488     SDValue Addr = Trmp;
15489     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15490                                 Addr, MachinePointerInfo(TrmpAddr),
15491                                 false, false, 0);
15492
15493     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15494                        DAG.getConstant(2, MVT::i64));
15495     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15496                                 MachinePointerInfo(TrmpAddr, 2),
15497                                 false, false, 2);
15498
15499     // Load the 'nest' parameter value into R10.
15500     // R10 is specified in X86CallingConv.td
15501     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15502     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15503                        DAG.getConstant(10, MVT::i64));
15504     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15505                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15506                                 false, false, 0);
15507
15508     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15509                        DAG.getConstant(12, MVT::i64));
15510     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15511                                 MachinePointerInfo(TrmpAddr, 12),
15512                                 false, false, 2);
15513
15514     // Jump to the nested function.
15515     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15516     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15517                        DAG.getConstant(20, MVT::i64));
15518     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15519                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15520                                 false, false, 0);
15521
15522     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15523     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15524                        DAG.getConstant(22, MVT::i64));
15525     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15526                                 MachinePointerInfo(TrmpAddr, 22),
15527                                 false, false, 0);
15528
15529     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15530   } else {
15531     const Function *Func =
15532       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15533     CallingConv::ID CC = Func->getCallingConv();
15534     unsigned NestReg;
15535
15536     switch (CC) {
15537     default:
15538       llvm_unreachable("Unsupported calling convention");
15539     case CallingConv::C:
15540     case CallingConv::X86_StdCall: {
15541       // Pass 'nest' parameter in ECX.
15542       // Must be kept in sync with X86CallingConv.td
15543       NestReg = X86::ECX;
15544
15545       // Check that ECX wasn't needed by an 'inreg' parameter.
15546       FunctionType *FTy = Func->getFunctionType();
15547       const AttributeSet &Attrs = Func->getAttributes();
15548
15549       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15550         unsigned InRegCount = 0;
15551         unsigned Idx = 1;
15552
15553         for (FunctionType::param_iterator I = FTy->param_begin(),
15554              E = FTy->param_end(); I != E; ++I, ++Idx)
15555           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15556             // FIXME: should only count parameters that are lowered to integers.
15557             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15558
15559         if (InRegCount > 2) {
15560           report_fatal_error("Nest register in use - reduce number of inreg"
15561                              " parameters!");
15562         }
15563       }
15564       break;
15565     }
15566     case CallingConv::X86_FastCall:
15567     case CallingConv::X86_ThisCall:
15568     case CallingConv::Fast:
15569       // Pass 'nest' parameter in EAX.
15570       // Must be kept in sync with X86CallingConv.td
15571       NestReg = X86::EAX;
15572       break;
15573     }
15574
15575     SDValue OutChains[4];
15576     SDValue Addr, Disp;
15577
15578     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15579                        DAG.getConstant(10, MVT::i32));
15580     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15581
15582     // This is storing the opcode for MOV32ri.
15583     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15584     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15585     OutChains[0] = DAG.getStore(Root, dl,
15586                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15587                                 Trmp, MachinePointerInfo(TrmpAddr),
15588                                 false, false, 0);
15589
15590     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15591                        DAG.getConstant(1, MVT::i32));
15592     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15593                                 MachinePointerInfo(TrmpAddr, 1),
15594                                 false, false, 1);
15595
15596     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15597     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15598                        DAG.getConstant(5, MVT::i32));
15599     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15600                                 MachinePointerInfo(TrmpAddr, 5),
15601                                 false, false, 1);
15602
15603     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15604                        DAG.getConstant(6, MVT::i32));
15605     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15606                                 MachinePointerInfo(TrmpAddr, 6),
15607                                 false, false, 1);
15608
15609     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15610   }
15611 }
15612
15613 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15614                                             SelectionDAG &DAG) const {
15615   /*
15616    The rounding mode is in bits 11:10 of FPSR, and has the following
15617    settings:
15618      00 Round to nearest
15619      01 Round to -inf
15620      10 Round to +inf
15621      11 Round to 0
15622
15623   FLT_ROUNDS, on the other hand, expects the following:
15624     -1 Undefined
15625      0 Round to 0
15626      1 Round to nearest
15627      2 Round to +inf
15628      3 Round to -inf
15629
15630   To perform the conversion, we do:
15631     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15632   */
15633
15634   MachineFunction &MF = DAG.getMachineFunction();
15635   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15636   unsigned StackAlignment = TFI.getStackAlignment();
15637   MVT VT = Op.getSimpleValueType();
15638   SDLoc DL(Op);
15639
15640   // Save FP Control Word to stack slot
15641   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15642   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15643
15644   MachineMemOperand *MMO =
15645    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15646                            MachineMemOperand::MOStore, 2, 2);
15647
15648   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15649   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15650                                           DAG.getVTList(MVT::Other),
15651                                           Ops, MVT::i16, MMO);
15652
15653   // Load FP Control Word from stack slot
15654   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15655                             MachinePointerInfo(), false, false, false, 0);
15656
15657   // Transform as necessary
15658   SDValue CWD1 =
15659     DAG.getNode(ISD::SRL, DL, MVT::i16,
15660                 DAG.getNode(ISD::AND, DL, MVT::i16,
15661                             CWD, DAG.getConstant(0x800, MVT::i16)),
15662                 DAG.getConstant(11, MVT::i8));
15663   SDValue CWD2 =
15664     DAG.getNode(ISD::SRL, DL, MVT::i16,
15665                 DAG.getNode(ISD::AND, DL, MVT::i16,
15666                             CWD, DAG.getConstant(0x400, MVT::i16)),
15667                 DAG.getConstant(9, MVT::i8));
15668
15669   SDValue RetVal =
15670     DAG.getNode(ISD::AND, DL, MVT::i16,
15671                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15672                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15673                             DAG.getConstant(1, MVT::i16)),
15674                 DAG.getConstant(3, MVT::i16));
15675
15676   return DAG.getNode((VT.getSizeInBits() < 16 ?
15677                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15678 }
15679
15680 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15681   MVT VT = Op.getSimpleValueType();
15682   EVT OpVT = VT;
15683   unsigned NumBits = VT.getSizeInBits();
15684   SDLoc dl(Op);
15685
15686   Op = Op.getOperand(0);
15687   if (VT == MVT::i8) {
15688     // Zero extend to i32 since there is not an i8 bsr.
15689     OpVT = MVT::i32;
15690     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15691   }
15692
15693   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15694   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15695   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15696
15697   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15698   SDValue Ops[] = {
15699     Op,
15700     DAG.getConstant(NumBits+NumBits-1, OpVT),
15701     DAG.getConstant(X86::COND_E, MVT::i8),
15702     Op.getValue(1)
15703   };
15704   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15705
15706   // Finally xor with NumBits-1.
15707   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15708
15709   if (VT == MVT::i8)
15710     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15711   return Op;
15712 }
15713
15714 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15715   MVT VT = Op.getSimpleValueType();
15716   EVT OpVT = VT;
15717   unsigned NumBits = VT.getSizeInBits();
15718   SDLoc dl(Op);
15719
15720   Op = Op.getOperand(0);
15721   if (VT == MVT::i8) {
15722     // Zero extend to i32 since there is not an i8 bsr.
15723     OpVT = MVT::i32;
15724     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15725   }
15726
15727   // Issue a bsr (scan bits in reverse).
15728   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15729   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15730
15731   // And xor with NumBits-1.
15732   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15733
15734   if (VT == MVT::i8)
15735     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15736   return Op;
15737 }
15738
15739 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15740   MVT VT = Op.getSimpleValueType();
15741   unsigned NumBits = VT.getSizeInBits();
15742   SDLoc dl(Op);
15743   Op = Op.getOperand(0);
15744
15745   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15746   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15747   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15748
15749   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15750   SDValue Ops[] = {
15751     Op,
15752     DAG.getConstant(NumBits, VT),
15753     DAG.getConstant(X86::COND_E, MVT::i8),
15754     Op.getValue(1)
15755   };
15756   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15757 }
15758
15759 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15760 // ones, and then concatenate the result back.
15761 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15762   MVT VT = Op.getSimpleValueType();
15763
15764   assert(VT.is256BitVector() && VT.isInteger() &&
15765          "Unsupported value type for operation");
15766
15767   unsigned NumElems = VT.getVectorNumElements();
15768   SDLoc dl(Op);
15769
15770   // Extract the LHS vectors
15771   SDValue LHS = Op.getOperand(0);
15772   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15773   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15774
15775   // Extract the RHS vectors
15776   SDValue RHS = Op.getOperand(1);
15777   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15778   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15779
15780   MVT EltVT = VT.getVectorElementType();
15781   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15782
15783   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15784                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15785                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15786 }
15787
15788 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15789   assert(Op.getSimpleValueType().is256BitVector() &&
15790          Op.getSimpleValueType().isInteger() &&
15791          "Only handle AVX 256-bit vector integer operation");
15792   return Lower256IntArith(Op, DAG);
15793 }
15794
15795 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15796   assert(Op.getSimpleValueType().is256BitVector() &&
15797          Op.getSimpleValueType().isInteger() &&
15798          "Only handle AVX 256-bit vector integer operation");
15799   return Lower256IntArith(Op, DAG);
15800 }
15801
15802 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15803                         SelectionDAG &DAG) {
15804   SDLoc dl(Op);
15805   MVT VT = Op.getSimpleValueType();
15806
15807   // Decompose 256-bit ops into smaller 128-bit ops.
15808   if (VT.is256BitVector() && !Subtarget->hasInt256())
15809     return Lower256IntArith(Op, DAG);
15810
15811   SDValue A = Op.getOperand(0);
15812   SDValue B = Op.getOperand(1);
15813
15814   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15815   if (VT == MVT::v4i32) {
15816     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15817            "Should not custom lower when pmuldq is available!");
15818
15819     // Extract the odd parts.
15820     static const int UnpackMask[] = { 1, -1, 3, -1 };
15821     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15822     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15823
15824     // Multiply the even parts.
15825     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15826     // Now multiply odd parts.
15827     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15828
15829     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15830     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15831
15832     // Merge the two vectors back together with a shuffle. This expands into 2
15833     // shuffles.
15834     static const int ShufMask[] = { 0, 4, 2, 6 };
15835     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15836   }
15837
15838   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15839          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15840
15841   //  Ahi = psrlqi(a, 32);
15842   //  Bhi = psrlqi(b, 32);
15843   //
15844   //  AloBlo = pmuludq(a, b);
15845   //  AloBhi = pmuludq(a, Bhi);
15846   //  AhiBlo = pmuludq(Ahi, b);
15847
15848   //  AloBhi = psllqi(AloBhi, 32);
15849   //  AhiBlo = psllqi(AhiBlo, 32);
15850   //  return AloBlo + AloBhi + AhiBlo;
15851
15852   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15853   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15854
15855   // Bit cast to 32-bit vectors for MULUDQ
15856   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15857                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15858   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15859   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15860   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15861   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15862
15863   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15864   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15865   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15866
15867   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15868   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15869
15870   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15871   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15872 }
15873
15874 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15875   assert(Subtarget->isTargetWin64() && "Unexpected target");
15876   EVT VT = Op.getValueType();
15877   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15878          "Unexpected return type for lowering");
15879
15880   RTLIB::Libcall LC;
15881   bool isSigned;
15882   switch (Op->getOpcode()) {
15883   default: llvm_unreachable("Unexpected request for libcall!");
15884   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15885   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15886   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15887   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15888   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15889   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15890   }
15891
15892   SDLoc dl(Op);
15893   SDValue InChain = DAG.getEntryNode();
15894
15895   TargetLowering::ArgListTy Args;
15896   TargetLowering::ArgListEntry Entry;
15897   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15898     EVT ArgVT = Op->getOperand(i).getValueType();
15899     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15900            "Unexpected argument type for lowering");
15901     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15902     Entry.Node = StackPtr;
15903     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15904                            false, false, 16);
15905     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15906     Entry.Ty = PointerType::get(ArgTy,0);
15907     Entry.isSExt = false;
15908     Entry.isZExt = false;
15909     Args.push_back(Entry);
15910   }
15911
15912   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15913                                          getPointerTy());
15914
15915   TargetLowering::CallLoweringInfo CLI(DAG);
15916   CLI.setDebugLoc(dl).setChain(InChain)
15917     .setCallee(getLibcallCallingConv(LC),
15918                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15919                Callee, std::move(Args), 0)
15920     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15921
15922   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15923   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15924 }
15925
15926 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15927                              SelectionDAG &DAG) {
15928   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15929   EVT VT = Op0.getValueType();
15930   SDLoc dl(Op);
15931
15932   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15933          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15934
15935   // PMULxD operations multiply each even value (starting at 0) of LHS with
15936   // the related value of RHS and produce a widen result.
15937   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15938   // => <2 x i64> <ae|cg>
15939   //
15940   // In other word, to have all the results, we need to perform two PMULxD:
15941   // 1. one with the even values.
15942   // 2. one with the odd values.
15943   // To achieve #2, with need to place the odd values at an even position.
15944   //
15945   // Place the odd value at an even position (basically, shift all values 1
15946   // step to the left):
15947   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15948   // <a|b|c|d> => <b|undef|d|undef>
15949   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15950   // <e|f|g|h> => <f|undef|h|undef>
15951   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15952
15953   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15954   // ints.
15955   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15956   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15957   unsigned Opcode =
15958       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15959   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15960   // => <2 x i64> <ae|cg>
15961   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15962                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15963   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15964   // => <2 x i64> <bf|dh>
15965   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15966                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15967
15968   // Shuffle it back into the right order.
15969   SDValue Highs, Lows;
15970   if (VT == MVT::v8i32) {
15971     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15972     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15973     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15974     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15975   } else {
15976     const int HighMask[] = {1, 5, 3, 7};
15977     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15978     const int LowMask[] = {0, 4, 2, 6};
15979     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15980   }
15981
15982   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15983   // unsigned multiply.
15984   if (IsSigned && !Subtarget->hasSSE41()) {
15985     SDValue ShAmt =
15986         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15987     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15988                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15989     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15990                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15991
15992     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15993     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15994   }
15995
15996   // The first result of MUL_LOHI is actually the low value, followed by the
15997   // high value.
15998   SDValue Ops[] = {Lows, Highs};
15999   return DAG.getMergeValues(Ops, dl);
16000 }
16001
16002 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16003                                          const X86Subtarget *Subtarget) {
16004   MVT VT = Op.getSimpleValueType();
16005   SDLoc dl(Op);
16006   SDValue R = Op.getOperand(0);
16007   SDValue Amt = Op.getOperand(1);
16008
16009   // Optimize shl/srl/sra with constant shift amount.
16010   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16011     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16012       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16013
16014       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16015           (Subtarget->hasInt256() &&
16016            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16017           (Subtarget->hasAVX512() &&
16018            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16019         if (Op.getOpcode() == ISD::SHL)
16020           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16021                                             DAG);
16022         if (Op.getOpcode() == ISD::SRL)
16023           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16024                                             DAG);
16025         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16026           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16027                                             DAG);
16028       }
16029
16030       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16031         unsigned NumElts = VT.getVectorNumElements();
16032         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16033
16034         if (Op.getOpcode() == ISD::SHL) {
16035           // Make a large shift.
16036           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16037                                                    R, ShiftAmt, DAG);
16038           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16039           // Zero out the rightmost bits.
16040           SmallVector<SDValue, 32> V(
16041               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), MVT::i8));
16042           return DAG.getNode(ISD::AND, dl, VT, SHL,
16043                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16044         }
16045         if (Op.getOpcode() == ISD::SRL) {
16046           // Make a large shift.
16047           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16048                                                    R, ShiftAmt, DAG);
16049           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16050           // Zero out the leftmost bits.
16051           SmallVector<SDValue, 32> V(
16052               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, MVT::i8));
16053           return DAG.getNode(ISD::AND, dl, VT, SRL,
16054                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16055         }
16056         if (Op.getOpcode() == ISD::SRA) {
16057           if (ShiftAmt == 7) {
16058             // R s>> 7  ===  R s< 0
16059             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16060             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16061           }
16062
16063           // R s>> a === ((R u>> a) ^ m) - m
16064           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16065           SmallVector<SDValue, 32> V(NumElts,
16066                                      DAG.getConstant(128 >> ShiftAmt, MVT::i8));
16067           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16068           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16069           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16070           return Res;
16071         }
16072         llvm_unreachable("Unknown shift opcode.");
16073       }
16074     }
16075   }
16076
16077   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16078   if (!Subtarget->is64Bit() &&
16079       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16080       Amt.getOpcode() == ISD::BITCAST &&
16081       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16082     Amt = Amt.getOperand(0);
16083     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16084                      VT.getVectorNumElements();
16085     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16086     uint64_t ShiftAmt = 0;
16087     for (unsigned i = 0; i != Ratio; ++i) {
16088       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16089       if (!C)
16090         return SDValue();
16091       // 6 == Log2(64)
16092       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16093     }
16094     // Check remaining shift amounts.
16095     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16096       uint64_t ShAmt = 0;
16097       for (unsigned j = 0; j != Ratio; ++j) {
16098         ConstantSDNode *C =
16099           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16100         if (!C)
16101           return SDValue();
16102         // 6 == Log2(64)
16103         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16104       }
16105       if (ShAmt != ShiftAmt)
16106         return SDValue();
16107     }
16108     switch (Op.getOpcode()) {
16109     default:
16110       llvm_unreachable("Unknown shift opcode!");
16111     case ISD::SHL:
16112       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16113                                         DAG);
16114     case ISD::SRL:
16115       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16116                                         DAG);
16117     case ISD::SRA:
16118       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16119                                         DAG);
16120     }
16121   }
16122
16123   return SDValue();
16124 }
16125
16126 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16127                                         const X86Subtarget* Subtarget) {
16128   MVT VT = Op.getSimpleValueType();
16129   SDLoc dl(Op);
16130   SDValue R = Op.getOperand(0);
16131   SDValue Amt = Op.getOperand(1);
16132
16133   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16134       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16135       (Subtarget->hasInt256() &&
16136        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16137         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16138        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16139     SDValue BaseShAmt;
16140     EVT EltVT = VT.getVectorElementType();
16141
16142     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16143       // Check if this build_vector node is doing a splat.
16144       // If so, then set BaseShAmt equal to the splat value.
16145       BaseShAmt = BV->getSplatValue();
16146       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16147         BaseShAmt = SDValue();
16148     } else {
16149       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16150         Amt = Amt.getOperand(0);
16151
16152       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16153       if (SVN && SVN->isSplat()) {
16154         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16155         SDValue InVec = Amt.getOperand(0);
16156         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16157           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16158                  "Unexpected shuffle index found!");
16159           BaseShAmt = InVec.getOperand(SplatIdx);
16160         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16161            if (ConstantSDNode *C =
16162                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16163              if (C->getZExtValue() == SplatIdx)
16164                BaseShAmt = InVec.getOperand(1);
16165            }
16166         }
16167
16168         if (!BaseShAmt)
16169           // Avoid introducing an extract element from a shuffle.
16170           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16171                                     DAG.getIntPtrConstant(SplatIdx));
16172       }
16173     }
16174
16175     if (BaseShAmt.getNode()) {
16176       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16177       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16178         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16179       else if (EltVT.bitsLT(MVT::i32))
16180         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16181
16182       switch (Op.getOpcode()) {
16183       default:
16184         llvm_unreachable("Unknown shift opcode!");
16185       case ISD::SHL:
16186         switch (VT.SimpleTy) {
16187         default: return SDValue();
16188         case MVT::v2i64:
16189         case MVT::v4i32:
16190         case MVT::v8i16:
16191         case MVT::v4i64:
16192         case MVT::v8i32:
16193         case MVT::v16i16:
16194         case MVT::v16i32:
16195         case MVT::v8i64:
16196           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16197         }
16198       case ISD::SRA:
16199         switch (VT.SimpleTy) {
16200         default: return SDValue();
16201         case MVT::v4i32:
16202         case MVT::v8i16:
16203         case MVT::v8i32:
16204         case MVT::v16i16:
16205         case MVT::v16i32:
16206         case MVT::v8i64:
16207           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16208         }
16209       case ISD::SRL:
16210         switch (VT.SimpleTy) {
16211         default: return SDValue();
16212         case MVT::v2i64:
16213         case MVT::v4i32:
16214         case MVT::v8i16:
16215         case MVT::v4i64:
16216         case MVT::v8i32:
16217         case MVT::v16i16:
16218         case MVT::v16i32:
16219         case MVT::v8i64:
16220           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16221         }
16222       }
16223     }
16224   }
16225
16226   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16227   if (!Subtarget->is64Bit() &&
16228       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16229       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16230       Amt.getOpcode() == ISD::BITCAST &&
16231       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16232     Amt = Amt.getOperand(0);
16233     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16234                      VT.getVectorNumElements();
16235     std::vector<SDValue> Vals(Ratio);
16236     for (unsigned i = 0; i != Ratio; ++i)
16237       Vals[i] = Amt.getOperand(i);
16238     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16239       for (unsigned j = 0; j != Ratio; ++j)
16240         if (Vals[j] != Amt.getOperand(i + j))
16241           return SDValue();
16242     }
16243     switch (Op.getOpcode()) {
16244     default:
16245       llvm_unreachable("Unknown shift opcode!");
16246     case ISD::SHL:
16247       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16248     case ISD::SRL:
16249       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16250     case ISD::SRA:
16251       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16252     }
16253   }
16254
16255   return SDValue();
16256 }
16257
16258 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16259                           SelectionDAG &DAG) {
16260   MVT VT = Op.getSimpleValueType();
16261   SDLoc dl(Op);
16262   SDValue R = Op.getOperand(0);
16263   SDValue Amt = Op.getOperand(1);
16264
16265   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16266   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16267
16268   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16269     return V;
16270
16271   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16272       return V;
16273
16274   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16275     return Op;
16276
16277   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16278   if (Subtarget->hasInt256()) {
16279     if (Op.getOpcode() == ISD::SRL &&
16280         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16281          VT == MVT::v4i64 || VT == MVT::v8i32))
16282       return Op;
16283     if (Op.getOpcode() == ISD::SHL &&
16284         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16285          VT == MVT::v4i64 || VT == MVT::v8i32))
16286       return Op;
16287     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16288       return Op;
16289   }
16290
16291   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16292   // shifts per-lane and then shuffle the partial results back together.
16293   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16294     // Splat the shift amounts so the scalar shifts above will catch it.
16295     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16296     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16297     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16298     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16299     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16300   }
16301
16302   // If possible, lower this packed shift into a vector multiply instead of
16303   // expanding it into a sequence of scalar shifts.
16304   // Do this only if the vector shift count is a constant build_vector.
16305   if (Op.getOpcode() == ISD::SHL &&
16306       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16307        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16308       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16309     SmallVector<SDValue, 8> Elts;
16310     EVT SVT = VT.getScalarType();
16311     unsigned SVTBits = SVT.getSizeInBits();
16312     const APInt &One = APInt(SVTBits, 1);
16313     unsigned NumElems = VT.getVectorNumElements();
16314
16315     for (unsigned i=0; i !=NumElems; ++i) {
16316       SDValue Op = Amt->getOperand(i);
16317       if (Op->getOpcode() == ISD::UNDEF) {
16318         Elts.push_back(Op);
16319         continue;
16320       }
16321
16322       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16323       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16324       uint64_t ShAmt = C.getZExtValue();
16325       if (ShAmt >= SVTBits) {
16326         Elts.push_back(DAG.getUNDEF(SVT));
16327         continue;
16328       }
16329       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16330     }
16331     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16332     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16333   }
16334
16335   // Lower SHL with variable shift amount.
16336   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16337     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16338
16339     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16340     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16341     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16342     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16343   }
16344
16345   // If possible, lower this shift as a sequence of two shifts by
16346   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16347   // Example:
16348   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16349   //
16350   // Could be rewritten as:
16351   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16352   //
16353   // The advantage is that the two shifts from the example would be
16354   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16355   // the vector shift into four scalar shifts plus four pairs of vector
16356   // insert/extract.
16357   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16358       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16359     unsigned TargetOpcode = X86ISD::MOVSS;
16360     bool CanBeSimplified;
16361     // The splat value for the first packed shift (the 'X' from the example).
16362     SDValue Amt1 = Amt->getOperand(0);
16363     // The splat value for the second packed shift (the 'Y' from the example).
16364     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16365                                         Amt->getOperand(2);
16366
16367     // See if it is possible to replace this node with a sequence of
16368     // two shifts followed by a MOVSS/MOVSD
16369     if (VT == MVT::v4i32) {
16370       // Check if it is legal to use a MOVSS.
16371       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16372                         Amt2 == Amt->getOperand(3);
16373       if (!CanBeSimplified) {
16374         // Otherwise, check if we can still simplify this node using a MOVSD.
16375         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16376                           Amt->getOperand(2) == Amt->getOperand(3);
16377         TargetOpcode = X86ISD::MOVSD;
16378         Amt2 = Amt->getOperand(2);
16379       }
16380     } else {
16381       // Do similar checks for the case where the machine value type
16382       // is MVT::v8i16.
16383       CanBeSimplified = Amt1 == Amt->getOperand(1);
16384       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16385         CanBeSimplified = Amt2 == Amt->getOperand(i);
16386
16387       if (!CanBeSimplified) {
16388         TargetOpcode = X86ISD::MOVSD;
16389         CanBeSimplified = true;
16390         Amt2 = Amt->getOperand(4);
16391         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16392           CanBeSimplified = Amt1 == Amt->getOperand(i);
16393         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16394           CanBeSimplified = Amt2 == Amt->getOperand(j);
16395       }
16396     }
16397
16398     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16399         isa<ConstantSDNode>(Amt2)) {
16400       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16401       EVT CastVT = MVT::v4i32;
16402       SDValue Splat1 =
16403         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16404       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16405       SDValue Splat2 =
16406         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16407       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16408       if (TargetOpcode == X86ISD::MOVSD)
16409         CastVT = MVT::v2i64;
16410       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16411       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16412       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16413                                             BitCast1, DAG);
16414       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16415     }
16416   }
16417
16418   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16419     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16420
16421     // a = a << 5;
16422     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16423     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16424
16425     // Turn 'a' into a mask suitable for VSELECT
16426     SDValue VSelM = DAG.getConstant(0x80, VT);
16427     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16428     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16429
16430     SDValue CM1 = DAG.getConstant(0x0f, VT);
16431     SDValue CM2 = DAG.getConstant(0x3f, VT);
16432
16433     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16434     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16435     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16436     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16437     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16438
16439     // a += a
16440     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16441     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16442     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16443
16444     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16445     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16446     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16447     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16448     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16449
16450     // a += a
16451     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16452     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16453     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16454
16455     // return VSELECT(r, r+r, a);
16456     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16457                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16458     return R;
16459   }
16460
16461   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16462   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16463   // solution better.
16464   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16465     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16466     unsigned ExtOpc =
16467         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16468     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16469     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16470     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16471                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16472   }
16473
16474   // Decompose 256-bit shifts into smaller 128-bit shifts.
16475   if (VT.is256BitVector()) {
16476     unsigned NumElems = VT.getVectorNumElements();
16477     MVT EltVT = VT.getVectorElementType();
16478     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16479
16480     // Extract the two vectors
16481     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16482     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16483
16484     // Recreate the shift amount vectors
16485     SDValue Amt1, Amt2;
16486     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16487       // Constant shift amount
16488       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16489       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16490       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16491
16492       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16493       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16494     } else {
16495       // Variable shift amount
16496       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16497       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16498     }
16499
16500     // Issue new vector shifts for the smaller types
16501     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16502     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16503
16504     // Concatenate the result back
16505     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16506   }
16507
16508   return SDValue();
16509 }
16510
16511 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16512   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16513   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16514   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16515   // has only one use.
16516   SDNode *N = Op.getNode();
16517   SDValue LHS = N->getOperand(0);
16518   SDValue RHS = N->getOperand(1);
16519   unsigned BaseOp = 0;
16520   unsigned Cond = 0;
16521   SDLoc DL(Op);
16522   switch (Op.getOpcode()) {
16523   default: llvm_unreachable("Unknown ovf instruction!");
16524   case ISD::SADDO:
16525     // A subtract of one will be selected as a INC. Note that INC doesn't
16526     // set CF, so we can't do this for UADDO.
16527     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16528       if (C->isOne()) {
16529         BaseOp = X86ISD::INC;
16530         Cond = X86::COND_O;
16531         break;
16532       }
16533     BaseOp = X86ISD::ADD;
16534     Cond = X86::COND_O;
16535     break;
16536   case ISD::UADDO:
16537     BaseOp = X86ISD::ADD;
16538     Cond = X86::COND_B;
16539     break;
16540   case ISD::SSUBO:
16541     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16542     // set CF, so we can't do this for USUBO.
16543     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16544       if (C->isOne()) {
16545         BaseOp = X86ISD::DEC;
16546         Cond = X86::COND_O;
16547         break;
16548       }
16549     BaseOp = X86ISD::SUB;
16550     Cond = X86::COND_O;
16551     break;
16552   case ISD::USUBO:
16553     BaseOp = X86ISD::SUB;
16554     Cond = X86::COND_B;
16555     break;
16556   case ISD::SMULO:
16557     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16558     Cond = X86::COND_O;
16559     break;
16560   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16561     if (N->getValueType(0) == MVT::i8) {
16562       BaseOp = X86ISD::UMUL8;
16563       Cond = X86::COND_O;
16564       break;
16565     }
16566     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16567                                  MVT::i32);
16568     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16569
16570     SDValue SetCC =
16571       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16572                   DAG.getConstant(X86::COND_O, MVT::i32),
16573                   SDValue(Sum.getNode(), 2));
16574
16575     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16576   }
16577   }
16578
16579   // Also sets EFLAGS.
16580   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16581   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16582
16583   SDValue SetCC =
16584     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16585                 DAG.getConstant(Cond, MVT::i32),
16586                 SDValue(Sum.getNode(), 1));
16587
16588   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16589 }
16590
16591 /// Returns true if the operand type is exactly twice the native width, and
16592 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16593 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16594 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16595 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16596   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16597
16598   if (OpWidth == 64)
16599     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16600   else if (OpWidth == 128)
16601     return Subtarget->hasCmpxchg16b();
16602   else
16603     return false;
16604 }
16605
16606 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16607   return needsCmpXchgNb(SI->getValueOperand()->getType());
16608 }
16609
16610 // Note: this turns large loads into lock cmpxchg8b/16b.
16611 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16612 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16613   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16614   return needsCmpXchgNb(PTy->getElementType());
16615 }
16616
16617 TargetLoweringBase::AtomicRMWExpansionKind
16618 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16619   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16620   const Type *MemType = AI->getType();
16621
16622   // If the operand is too big, we must see if cmpxchg8/16b is available
16623   // and default to library calls otherwise.
16624   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16625     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16626                                    : AtomicRMWExpansionKind::None;
16627   }
16628
16629   AtomicRMWInst::BinOp Op = AI->getOperation();
16630   switch (Op) {
16631   default:
16632     llvm_unreachable("Unknown atomic operation");
16633   case AtomicRMWInst::Xchg:
16634   case AtomicRMWInst::Add:
16635   case AtomicRMWInst::Sub:
16636     // It's better to use xadd, xsub or xchg for these in all cases.
16637     return AtomicRMWExpansionKind::None;
16638   case AtomicRMWInst::Or:
16639   case AtomicRMWInst::And:
16640   case AtomicRMWInst::Xor:
16641     // If the atomicrmw's result isn't actually used, we can just add a "lock"
16642     // prefix to a normal instruction for these operations.
16643     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16644                             : AtomicRMWExpansionKind::None;
16645   case AtomicRMWInst::Nand:
16646   case AtomicRMWInst::Max:
16647   case AtomicRMWInst::Min:
16648   case AtomicRMWInst::UMax:
16649   case AtomicRMWInst::UMin:
16650     // These always require a non-trivial set of data operations on x86. We must
16651     // use a cmpxchg loop.
16652     return AtomicRMWExpansionKind::CmpXChg;
16653   }
16654 }
16655
16656 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16657   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16658   // no-sse2). There isn't any reason to disable it if the target processor
16659   // supports it.
16660   return Subtarget.hasSSE2() || Subtarget.is64Bit();
16661 }
16662
16663 LoadInst *
16664 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16665   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16666   const Type *MemType = AI->getType();
16667   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16668   // there is no benefit in turning such RMWs into loads, and it is actually
16669   // harmful as it introduces a mfence.
16670   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16671     return nullptr;
16672
16673   auto Builder = IRBuilder<>(AI);
16674   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16675   auto SynchScope = AI->getSynchScope();
16676   // We must restrict the ordering to avoid generating loads with Release or
16677   // ReleaseAcquire orderings.
16678   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16679   auto Ptr = AI->getPointerOperand();
16680
16681   // Before the load we need a fence. Here is an example lifted from
16682   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16683   // is required:
16684   // Thread 0:
16685   //   x.store(1, relaxed);
16686   //   r1 = y.fetch_add(0, release);
16687   // Thread 1:
16688   //   y.fetch_add(42, acquire);
16689   //   r2 = x.load(relaxed);
16690   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16691   // lowered to just a load without a fence. A mfence flushes the store buffer,
16692   // making the optimization clearly correct.
16693   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16694   // otherwise, we might be able to be more agressive on relaxed idempotent
16695   // rmw. In practice, they do not look useful, so we don't try to be
16696   // especially clever.
16697   if (SynchScope == SingleThread) {
16698     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16699     // the IR level, so we must wrap it in an intrinsic.
16700     return nullptr;
16701   } else if (hasMFENCE(*Subtarget)) {
16702     Function *MFence = llvm::Intrinsic::getDeclaration(M,
16703             Intrinsic::x86_sse2_mfence);
16704     Builder.CreateCall(MFence);
16705   } else {
16706     // FIXME: it might make sense to use a locked operation here but on a
16707     // different cache-line to prevent cache-line bouncing. In practice it
16708     // is probably a small win, and x86 processors without mfence are rare
16709     // enough that we do not bother.
16710     return nullptr;
16711   }
16712
16713   // Finally we can emit the atomic load.
16714   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
16715           AI->getType()->getPrimitiveSizeInBits());
16716   Loaded->setAtomic(Order, SynchScope);
16717   AI->replaceAllUsesWith(Loaded);
16718   AI->eraseFromParent();
16719   return Loaded;
16720 }
16721
16722 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16723                                  SelectionDAG &DAG) {
16724   SDLoc dl(Op);
16725   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16726     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16727   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16728     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16729
16730   // The only fence that needs an instruction is a sequentially-consistent
16731   // cross-thread fence.
16732   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16733     if (hasMFENCE(*Subtarget))
16734       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16735
16736     SDValue Chain = Op.getOperand(0);
16737     SDValue Zero = DAG.getConstant(0, MVT::i32);
16738     SDValue Ops[] = {
16739       DAG.getRegister(X86::ESP, MVT::i32), // Base
16740       DAG.getTargetConstant(1, MVT::i8),   // Scale
16741       DAG.getRegister(0, MVT::i32),        // Index
16742       DAG.getTargetConstant(0, MVT::i32),  // Disp
16743       DAG.getRegister(0, MVT::i32),        // Segment.
16744       Zero,
16745       Chain
16746     };
16747     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16748     return SDValue(Res, 0);
16749   }
16750
16751   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16752   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16753 }
16754
16755 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16756                              SelectionDAG &DAG) {
16757   MVT T = Op.getSimpleValueType();
16758   SDLoc DL(Op);
16759   unsigned Reg = 0;
16760   unsigned size = 0;
16761   switch(T.SimpleTy) {
16762   default: llvm_unreachable("Invalid value type!");
16763   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16764   case MVT::i16: Reg = X86::AX;  size = 2; break;
16765   case MVT::i32: Reg = X86::EAX; size = 4; break;
16766   case MVT::i64:
16767     assert(Subtarget->is64Bit() && "Node not type legal!");
16768     Reg = X86::RAX; size = 8;
16769     break;
16770   }
16771   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16772                                   Op.getOperand(2), SDValue());
16773   SDValue Ops[] = { cpIn.getValue(0),
16774                     Op.getOperand(1),
16775                     Op.getOperand(3),
16776                     DAG.getTargetConstant(size, MVT::i8),
16777                     cpIn.getValue(1) };
16778   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16779   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16780   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16781                                            Ops, T, MMO);
16782
16783   SDValue cpOut =
16784     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16785   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16786                                       MVT::i32, cpOut.getValue(2));
16787   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16788                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16789
16790   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16791   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16792   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16793   return SDValue();
16794 }
16795
16796 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16797                             SelectionDAG &DAG) {
16798   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16799   MVT DstVT = Op.getSimpleValueType();
16800
16801   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16802     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16803     if (DstVT != MVT::f64)
16804       // This conversion needs to be expanded.
16805       return SDValue();
16806
16807     SDValue InVec = Op->getOperand(0);
16808     SDLoc dl(Op);
16809     unsigned NumElts = SrcVT.getVectorNumElements();
16810     EVT SVT = SrcVT.getVectorElementType();
16811
16812     // Widen the vector in input in the case of MVT::v2i32.
16813     // Example: from MVT::v2i32 to MVT::v4i32.
16814     SmallVector<SDValue, 16> Elts;
16815     for (unsigned i = 0, e = NumElts; i != e; ++i)
16816       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16817                                  DAG.getIntPtrConstant(i)));
16818
16819     // Explicitly mark the extra elements as Undef.
16820     Elts.append(NumElts, DAG.getUNDEF(SVT));
16821
16822     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16823     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16824     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16825     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16826                        DAG.getIntPtrConstant(0));
16827   }
16828
16829   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16830          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16831   assert((DstVT == MVT::i64 ||
16832           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16833          "Unexpected custom BITCAST");
16834   // i64 <=> MMX conversions are Legal.
16835   if (SrcVT==MVT::i64 && DstVT.isVector())
16836     return Op;
16837   if (DstVT==MVT::i64 && SrcVT.isVector())
16838     return Op;
16839   // MMX <=> MMX conversions are Legal.
16840   if (SrcVT.isVector() && DstVT.isVector())
16841     return Op;
16842   // All other conversions need to be expanded.
16843   return SDValue();
16844 }
16845
16846 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
16847                           SelectionDAG &DAG) {
16848   SDNode *Node = Op.getNode();
16849   SDLoc dl(Node);
16850
16851   Op = Op.getOperand(0);
16852   EVT VT = Op.getValueType();
16853   assert((VT.is128BitVector() || VT.is256BitVector()) &&
16854          "CTPOP lowering only implemented for 128/256-bit wide vector types");
16855
16856   unsigned NumElts = VT.getVectorNumElements();
16857   EVT EltVT = VT.getVectorElementType();
16858   unsigned Len = EltVT.getSizeInBits();
16859
16860   // This is the vectorized version of the "best" algorithm from
16861   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
16862   // with a minor tweak to use a series of adds + shifts instead of vector
16863   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
16864   //
16865   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
16866   //  v8i32 => Always profitable
16867   //
16868   // FIXME: There a couple of possible improvements:
16869   //
16870   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
16871   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
16872   //
16873   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
16874          "CTPOP not implemented for this vector element type.");
16875
16876   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
16877   // extra legalization.
16878   bool NeedsBitcast = EltVT == MVT::i32;
16879   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
16880
16881   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), EltVT);
16882   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), EltVT);
16883   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), EltVT);
16884
16885   // v = v - ((v >> 1) & 0x55555555...)
16886   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, EltVT));
16887   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
16888   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
16889   if (NeedsBitcast)
16890     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16891
16892   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
16893   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
16894   if (NeedsBitcast)
16895     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
16896
16897   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
16898   if (VT != And.getValueType())
16899     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16900   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
16901
16902   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
16903   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
16904   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
16905   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, EltVT));
16906   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
16907
16908   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
16909   if (NeedsBitcast) {
16910     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16911     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
16912     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
16913   }
16914
16915   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
16916   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
16917   if (VT != AndRHS.getValueType()) {
16918     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
16919     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
16920   }
16921   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
16922
16923   // v = (v + (v >> 4)) & 0x0F0F0F0F...
16924   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, EltVT));
16925   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
16926   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
16927   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16928
16929   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
16930   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
16931   if (NeedsBitcast) {
16932     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16933     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
16934   }
16935   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
16936   if (VT != And.getValueType())
16937     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16938
16939   // The algorithm mentioned above uses:
16940   //    v = (v * 0x01010101...) >> (Len - 8)
16941   //
16942   // Change it to use vector adds + vector shifts which yield faster results on
16943   // Haswell than using vector integer multiplication.
16944   //
16945   // For i32 elements:
16946   //    v = v + (v >> 8)
16947   //    v = v + (v >> 16)
16948   //
16949   // For i64 elements:
16950   //    v = v + (v >> 8)
16951   //    v = v + (v >> 16)
16952   //    v = v + (v >> 32)
16953   //
16954   Add = And;
16955   SmallVector<SDValue, 8> Csts;
16956   for (unsigned i = 8; i <= Len/2; i *= 2) {
16957     Csts.assign(NumElts, DAG.getConstant(i, EltVT));
16958     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
16959     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
16960     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16961     Csts.clear();
16962   }
16963
16964   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
16965   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), EltVT);
16966   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
16967   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
16968   if (NeedsBitcast) {
16969     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16970     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
16971   }
16972   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
16973   if (VT != And.getValueType())
16974     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16975
16976   return And;
16977 }
16978
16979 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16980   SDNode *Node = Op.getNode();
16981   SDLoc dl(Node);
16982   EVT T = Node->getValueType(0);
16983   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16984                               DAG.getConstant(0, T), Node->getOperand(2));
16985   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16986                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16987                        Node->getOperand(0),
16988                        Node->getOperand(1), negOp,
16989                        cast<AtomicSDNode>(Node)->getMemOperand(),
16990                        cast<AtomicSDNode>(Node)->getOrdering(),
16991                        cast<AtomicSDNode>(Node)->getSynchScope());
16992 }
16993
16994 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16995   SDNode *Node = Op.getNode();
16996   SDLoc dl(Node);
16997   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16998
16999   // Convert seq_cst store -> xchg
17000   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17001   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17002   //        (The only way to get a 16-byte store is cmpxchg16b)
17003   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17004   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17005       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17006     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17007                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17008                                  Node->getOperand(0),
17009                                  Node->getOperand(1), Node->getOperand(2),
17010                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17011                                  cast<AtomicSDNode>(Node)->getOrdering(),
17012                                  cast<AtomicSDNode>(Node)->getSynchScope());
17013     return Swap.getValue(1);
17014   }
17015   // Other atomic stores have a simple pattern.
17016   return Op;
17017 }
17018
17019 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17020   EVT VT = Op.getNode()->getSimpleValueType(0);
17021
17022   // Let legalize expand this if it isn't a legal type yet.
17023   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17024     return SDValue();
17025
17026   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17027
17028   unsigned Opc;
17029   bool ExtraOp = false;
17030   switch (Op.getOpcode()) {
17031   default: llvm_unreachable("Invalid code");
17032   case ISD::ADDC: Opc = X86ISD::ADD; break;
17033   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17034   case ISD::SUBC: Opc = X86ISD::SUB; break;
17035   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17036   }
17037
17038   if (!ExtraOp)
17039     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17040                        Op.getOperand(1));
17041   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17042                      Op.getOperand(1), Op.getOperand(2));
17043 }
17044
17045 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17046                             SelectionDAG &DAG) {
17047   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17048
17049   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17050   // which returns the values as { float, float } (in XMM0) or
17051   // { double, double } (which is returned in XMM0, XMM1).
17052   SDLoc dl(Op);
17053   SDValue Arg = Op.getOperand(0);
17054   EVT ArgVT = Arg.getValueType();
17055   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17056
17057   TargetLowering::ArgListTy Args;
17058   TargetLowering::ArgListEntry Entry;
17059
17060   Entry.Node = Arg;
17061   Entry.Ty = ArgTy;
17062   Entry.isSExt = false;
17063   Entry.isZExt = false;
17064   Args.push_back(Entry);
17065
17066   bool isF64 = ArgVT == MVT::f64;
17067   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17068   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17069   // the results are returned via SRet in memory.
17070   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17071   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17072   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17073
17074   Type *RetTy = isF64
17075     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17076     : (Type*)VectorType::get(ArgTy, 4);
17077
17078   TargetLowering::CallLoweringInfo CLI(DAG);
17079   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17080     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17081
17082   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17083
17084   if (isF64)
17085     // Returned in xmm0 and xmm1.
17086     return CallResult.first;
17087
17088   // Returned in bits 0:31 and 32:64 xmm0.
17089   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17090                                CallResult.first, DAG.getIntPtrConstant(0));
17091   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17092                                CallResult.first, DAG.getIntPtrConstant(1));
17093   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17094   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17095 }
17096
17097 /// LowerOperation - Provide custom lowering hooks for some operations.
17098 ///
17099 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17100   switch (Op.getOpcode()) {
17101   default: llvm_unreachable("Should not custom lower this!");
17102   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17103   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17104     return LowerCMP_SWAP(Op, Subtarget, DAG);
17105   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
17106   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17107   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17108   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17109   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17110   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17111   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17112   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17113   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17114   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17115   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17116   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17117   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17118   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17119   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17120   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17121   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17122   case ISD::SHL_PARTS:
17123   case ISD::SRA_PARTS:
17124   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17125   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17126   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17127   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17128   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17129   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17130   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17131   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17132   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17133   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17134   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17135   case ISD::FABS:
17136   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17137   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17138   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17139   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17140   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17141   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17142   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17143   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17144   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17145   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17146   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17147   case ISD::INTRINSIC_VOID:
17148   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17149   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17150   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17151   case ISD::FRAME_TO_ARGS_OFFSET:
17152                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17153   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17154   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17155   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17156   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17157   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17158   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17159   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17160   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17161   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17162   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17163   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17164   case ISD::UMUL_LOHI:
17165   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17166   case ISD::SRA:
17167   case ISD::SRL:
17168   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17169   case ISD::SADDO:
17170   case ISD::UADDO:
17171   case ISD::SSUBO:
17172   case ISD::USUBO:
17173   case ISD::SMULO:
17174   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17175   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17176   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17177   case ISD::ADDC:
17178   case ISD::ADDE:
17179   case ISD::SUBC:
17180   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17181   case ISD::ADD:                return LowerADD(Op, DAG);
17182   case ISD::SUB:                return LowerSUB(Op, DAG);
17183   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17184   }
17185 }
17186
17187 /// ReplaceNodeResults - Replace a node with an illegal result type
17188 /// with a new node built out of custom code.
17189 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17190                                            SmallVectorImpl<SDValue>&Results,
17191                                            SelectionDAG &DAG) const {
17192   SDLoc dl(N);
17193   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17194   switch (N->getOpcode()) {
17195   default:
17196     llvm_unreachable("Do not know how to custom type legalize this operation!");
17197   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17198   case X86ISD::FMINC:
17199   case X86ISD::FMIN:
17200   case X86ISD::FMAXC:
17201   case X86ISD::FMAX: {
17202     EVT VT = N->getValueType(0);
17203     if (VT != MVT::v2f32)
17204       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17205     SDValue UNDEF = DAG.getUNDEF(VT);
17206     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17207                               N->getOperand(0), UNDEF);
17208     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17209                               N->getOperand(1), UNDEF);
17210     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17211     return;
17212   }
17213   case ISD::SIGN_EXTEND_INREG:
17214   case ISD::ADDC:
17215   case ISD::ADDE:
17216   case ISD::SUBC:
17217   case ISD::SUBE:
17218     // We don't want to expand or promote these.
17219     return;
17220   case ISD::SDIV:
17221   case ISD::UDIV:
17222   case ISD::SREM:
17223   case ISD::UREM:
17224   case ISD::SDIVREM:
17225   case ISD::UDIVREM: {
17226     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17227     Results.push_back(V);
17228     return;
17229   }
17230   case ISD::FP_TO_SINT:
17231   case ISD::FP_TO_UINT: {
17232     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17233
17234     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17235       return;
17236
17237     std::pair<SDValue,SDValue> Vals =
17238         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17239     SDValue FIST = Vals.first, StackSlot = Vals.second;
17240     if (FIST.getNode()) {
17241       EVT VT = N->getValueType(0);
17242       // Return a load from the stack slot.
17243       if (StackSlot.getNode())
17244         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17245                                       MachinePointerInfo(),
17246                                       false, false, false, 0));
17247       else
17248         Results.push_back(FIST);
17249     }
17250     return;
17251   }
17252   case ISD::UINT_TO_FP: {
17253     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17254     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17255         N->getValueType(0) != MVT::v2f32)
17256       return;
17257     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17258                                  N->getOperand(0));
17259     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17260                                      MVT::f64);
17261     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17262     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17263                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17264     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17265     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17266     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17267     return;
17268   }
17269   case ISD::FP_ROUND: {
17270     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17271         return;
17272     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17273     Results.push_back(V);
17274     return;
17275   }
17276   case ISD::INTRINSIC_W_CHAIN: {
17277     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17278     switch (IntNo) {
17279     default : llvm_unreachable("Do not know how to custom type "
17280                                "legalize this intrinsic operation!");
17281     case Intrinsic::x86_rdtsc:
17282       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17283                                      Results);
17284     case Intrinsic::x86_rdtscp:
17285       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17286                                      Results);
17287     case Intrinsic::x86_rdpmc:
17288       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17289     }
17290   }
17291   case ISD::READCYCLECOUNTER: {
17292     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17293                                    Results);
17294   }
17295   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17296     EVT T = N->getValueType(0);
17297     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17298     bool Regs64bit = T == MVT::i128;
17299     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17300     SDValue cpInL, cpInH;
17301     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17302                         DAG.getConstant(0, HalfT));
17303     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17304                         DAG.getConstant(1, HalfT));
17305     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17306                              Regs64bit ? X86::RAX : X86::EAX,
17307                              cpInL, SDValue());
17308     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17309                              Regs64bit ? X86::RDX : X86::EDX,
17310                              cpInH, cpInL.getValue(1));
17311     SDValue swapInL, swapInH;
17312     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17313                           DAG.getConstant(0, HalfT));
17314     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17315                           DAG.getConstant(1, HalfT));
17316     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17317                                Regs64bit ? X86::RBX : X86::EBX,
17318                                swapInL, cpInH.getValue(1));
17319     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17320                                Regs64bit ? X86::RCX : X86::ECX,
17321                                swapInH, swapInL.getValue(1));
17322     SDValue Ops[] = { swapInH.getValue(0),
17323                       N->getOperand(1),
17324                       swapInH.getValue(1) };
17325     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17326     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17327     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17328                                   X86ISD::LCMPXCHG8_DAG;
17329     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17330     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17331                                         Regs64bit ? X86::RAX : X86::EAX,
17332                                         HalfT, Result.getValue(1));
17333     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17334                                         Regs64bit ? X86::RDX : X86::EDX,
17335                                         HalfT, cpOutL.getValue(2));
17336     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17337
17338     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17339                                         MVT::i32, cpOutH.getValue(2));
17340     SDValue Success =
17341         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17342                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17343     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17344
17345     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17346     Results.push_back(Success);
17347     Results.push_back(EFLAGS.getValue(1));
17348     return;
17349   }
17350   case ISD::ATOMIC_SWAP:
17351   case ISD::ATOMIC_LOAD_ADD:
17352   case ISD::ATOMIC_LOAD_SUB:
17353   case ISD::ATOMIC_LOAD_AND:
17354   case ISD::ATOMIC_LOAD_OR:
17355   case ISD::ATOMIC_LOAD_XOR:
17356   case ISD::ATOMIC_LOAD_NAND:
17357   case ISD::ATOMIC_LOAD_MIN:
17358   case ISD::ATOMIC_LOAD_MAX:
17359   case ISD::ATOMIC_LOAD_UMIN:
17360   case ISD::ATOMIC_LOAD_UMAX:
17361   case ISD::ATOMIC_LOAD: {
17362     // Delegate to generic TypeLegalization. Situations we can really handle
17363     // should have already been dealt with by AtomicExpandPass.cpp.
17364     break;
17365   }
17366   case ISD::BITCAST: {
17367     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17368     EVT DstVT = N->getValueType(0);
17369     EVT SrcVT = N->getOperand(0)->getValueType(0);
17370
17371     if (SrcVT != MVT::f64 ||
17372         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17373       return;
17374
17375     unsigned NumElts = DstVT.getVectorNumElements();
17376     EVT SVT = DstVT.getVectorElementType();
17377     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17378     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17379                                    MVT::v2f64, N->getOperand(0));
17380     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17381
17382     if (ExperimentalVectorWideningLegalization) {
17383       // If we are legalizing vectors by widening, we already have the desired
17384       // legal vector type, just return it.
17385       Results.push_back(ToVecInt);
17386       return;
17387     }
17388
17389     SmallVector<SDValue, 8> Elts;
17390     for (unsigned i = 0, e = NumElts; i != e; ++i)
17391       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17392                                    ToVecInt, DAG.getIntPtrConstant(i)));
17393
17394     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17395   }
17396   }
17397 }
17398
17399 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17400   switch (Opcode) {
17401   default: return nullptr;
17402   case X86ISD::BSF:                return "X86ISD::BSF";
17403   case X86ISD::BSR:                return "X86ISD::BSR";
17404   case X86ISD::SHLD:               return "X86ISD::SHLD";
17405   case X86ISD::SHRD:               return "X86ISD::SHRD";
17406   case X86ISD::FAND:               return "X86ISD::FAND";
17407   case X86ISD::FANDN:              return "X86ISD::FANDN";
17408   case X86ISD::FOR:                return "X86ISD::FOR";
17409   case X86ISD::FXOR:               return "X86ISD::FXOR";
17410   case X86ISD::FSRL:               return "X86ISD::FSRL";
17411   case X86ISD::FILD:               return "X86ISD::FILD";
17412   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17413   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17414   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17415   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17416   case X86ISD::FLD:                return "X86ISD::FLD";
17417   case X86ISD::FST:                return "X86ISD::FST";
17418   case X86ISD::CALL:               return "X86ISD::CALL";
17419   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17420   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17421   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17422   case X86ISD::BT:                 return "X86ISD::BT";
17423   case X86ISD::CMP:                return "X86ISD::CMP";
17424   case X86ISD::COMI:               return "X86ISD::COMI";
17425   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17426   case X86ISD::CMPM:               return "X86ISD::CMPM";
17427   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17428   case X86ISD::SETCC:              return "X86ISD::SETCC";
17429   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17430   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17431   case X86ISD::CMOV:               return "X86ISD::CMOV";
17432   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17433   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17434   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17435   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17436   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17437   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17438   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17439   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17440   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17441   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17442   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17443   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17444   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17445   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17446   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17447   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17448   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17449   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17450   case X86ISD::HADD:               return "X86ISD::HADD";
17451   case X86ISD::HSUB:               return "X86ISD::HSUB";
17452   case X86ISD::FHADD:              return "X86ISD::FHADD";
17453   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17454   case X86ISD::UMAX:               return "X86ISD::UMAX";
17455   case X86ISD::UMIN:               return "X86ISD::UMIN";
17456   case X86ISD::SMAX:               return "X86ISD::SMAX";
17457   case X86ISD::SMIN:               return "X86ISD::SMIN";
17458   case X86ISD::FMAX:               return "X86ISD::FMAX";
17459   case X86ISD::FMIN:               return "X86ISD::FMIN";
17460   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17461   case X86ISD::FMINC:              return "X86ISD::FMINC";
17462   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17463   case X86ISD::FRCP:               return "X86ISD::FRCP";
17464   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17465   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17466   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17467   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17468   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17469   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17470   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17471   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17472   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17473   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17474   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17475   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17476   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17477   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17478   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17479   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17480   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17481   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17482   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17483   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17484   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17485   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17486   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17487   case X86ISD::VSHL:               return "X86ISD::VSHL";
17488   case X86ISD::VSRL:               return "X86ISD::VSRL";
17489   case X86ISD::VSRA:               return "X86ISD::VSRA";
17490   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17491   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17492   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17493   case X86ISD::CMPP:               return "X86ISD::CMPP";
17494   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17495   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17496   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17497   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17498   case X86ISD::ADD:                return "X86ISD::ADD";
17499   case X86ISD::SUB:                return "X86ISD::SUB";
17500   case X86ISD::ADC:                return "X86ISD::ADC";
17501   case X86ISD::SBB:                return "X86ISD::SBB";
17502   case X86ISD::SMUL:               return "X86ISD::SMUL";
17503   case X86ISD::UMUL:               return "X86ISD::UMUL";
17504   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
17505   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
17506   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17507   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17508   case X86ISD::INC:                return "X86ISD::INC";
17509   case X86ISD::DEC:                return "X86ISD::DEC";
17510   case X86ISD::OR:                 return "X86ISD::OR";
17511   case X86ISD::XOR:                return "X86ISD::XOR";
17512   case X86ISD::AND:                return "X86ISD::AND";
17513   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17514   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17515   case X86ISD::PTEST:              return "X86ISD::PTEST";
17516   case X86ISD::TESTP:              return "X86ISD::TESTP";
17517   case X86ISD::TESTM:              return "X86ISD::TESTM";
17518   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17519   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17520   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17521   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17522   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17523   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17524   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17525   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17526   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17527   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17528   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17529   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17530   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17531   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17532   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17533   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17534   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17535   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17536   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17537   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17538   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17539   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17540   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17541   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17542   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17543   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
17544   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17545   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17546   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17547   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17548   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17549   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17550   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17551   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17552   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17553   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17554   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17555   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17556   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17557   case X86ISD::SAHF:               return "X86ISD::SAHF";
17558   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17559   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17560   case X86ISD::FMADD:              return "X86ISD::FMADD";
17561   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17562   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17563   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17564   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17565   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17566   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17567   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17568   case X86ISD::XTEST:              return "X86ISD::XTEST";
17569   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
17570   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
17571   case X86ISD::SELECT:             return "X86ISD::SELECT";
17572   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
17573   case X86ISD::RCP28:              return "X86ISD::RCP28";
17574   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
17575   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
17576   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
17577   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
17578   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
17579   }
17580 }
17581
17582 // isLegalAddressingMode - Return true if the addressing mode represented
17583 // by AM is legal for this target, for a load/store of the specified type.
17584 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17585                                               Type *Ty) const {
17586   // X86 supports extremely general addressing modes.
17587   CodeModel::Model M = getTargetMachine().getCodeModel();
17588   Reloc::Model R = getTargetMachine().getRelocationModel();
17589
17590   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17591   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17592     return false;
17593
17594   if (AM.BaseGV) {
17595     unsigned GVFlags =
17596       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17597
17598     // If a reference to this global requires an extra load, we can't fold it.
17599     if (isGlobalStubReference(GVFlags))
17600       return false;
17601
17602     // If BaseGV requires a register for the PIC base, we cannot also have a
17603     // BaseReg specified.
17604     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17605       return false;
17606
17607     // If lower 4G is not available, then we must use rip-relative addressing.
17608     if ((M != CodeModel::Small || R != Reloc::Static) &&
17609         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17610       return false;
17611   }
17612
17613   switch (AM.Scale) {
17614   case 0:
17615   case 1:
17616   case 2:
17617   case 4:
17618   case 8:
17619     // These scales always work.
17620     break;
17621   case 3:
17622   case 5:
17623   case 9:
17624     // These scales are formed with basereg+scalereg.  Only accept if there is
17625     // no basereg yet.
17626     if (AM.HasBaseReg)
17627       return false;
17628     break;
17629   default:  // Other stuff never works.
17630     return false;
17631   }
17632
17633   return true;
17634 }
17635
17636 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17637   unsigned Bits = Ty->getScalarSizeInBits();
17638
17639   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17640   // particularly cheaper than those without.
17641   if (Bits == 8)
17642     return false;
17643
17644   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17645   // variable shifts just as cheap as scalar ones.
17646   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17647     return false;
17648
17649   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17650   // fully general vector.
17651   return true;
17652 }
17653
17654 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17655   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17656     return false;
17657   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17658   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17659   return NumBits1 > NumBits2;
17660 }
17661
17662 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17663   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17664     return false;
17665
17666   if (!isTypeLegal(EVT::getEVT(Ty1)))
17667     return false;
17668
17669   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17670
17671   // Assuming the caller doesn't have a zeroext or signext return parameter,
17672   // truncation all the way down to i1 is valid.
17673   return true;
17674 }
17675
17676 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17677   return isInt<32>(Imm);
17678 }
17679
17680 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17681   // Can also use sub to handle negated immediates.
17682   return isInt<32>(Imm);
17683 }
17684
17685 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17686   if (!VT1.isInteger() || !VT2.isInteger())
17687     return false;
17688   unsigned NumBits1 = VT1.getSizeInBits();
17689   unsigned NumBits2 = VT2.getSizeInBits();
17690   return NumBits1 > NumBits2;
17691 }
17692
17693 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17694   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17695   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17696 }
17697
17698 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17699   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17700   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17701 }
17702
17703 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17704   EVT VT1 = Val.getValueType();
17705   if (isZExtFree(VT1, VT2))
17706     return true;
17707
17708   if (Val.getOpcode() != ISD::LOAD)
17709     return false;
17710
17711   if (!VT1.isSimple() || !VT1.isInteger() ||
17712       !VT2.isSimple() || !VT2.isInteger())
17713     return false;
17714
17715   switch (VT1.getSimpleVT().SimpleTy) {
17716   default: break;
17717   case MVT::i8:
17718   case MVT::i16:
17719   case MVT::i32:
17720     // X86 has 8, 16, and 32-bit zero-extending loads.
17721     return true;
17722   }
17723
17724   return false;
17725 }
17726
17727 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
17728
17729 bool
17730 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17731   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17732     return false;
17733
17734   VT = VT.getScalarType();
17735
17736   if (!VT.isSimple())
17737     return false;
17738
17739   switch (VT.getSimpleVT().SimpleTy) {
17740   case MVT::f32:
17741   case MVT::f64:
17742     return true;
17743   default:
17744     break;
17745   }
17746
17747   return false;
17748 }
17749
17750 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17751   // i16 instructions are longer (0x66 prefix) and potentially slower.
17752   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17753 }
17754
17755 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17756 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17757 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17758 /// are assumed to be legal.
17759 bool
17760 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17761                                       EVT VT) const {
17762   if (!VT.isSimple())
17763     return false;
17764
17765   // Very little shuffling can be done for 64-bit vectors right now.
17766   if (VT.getSizeInBits() == 64)
17767     return false;
17768
17769   // We only care that the types being shuffled are legal. The lowering can
17770   // handle any possible shuffle mask that results.
17771   return isTypeLegal(VT.getSimpleVT());
17772 }
17773
17774 bool
17775 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17776                                           EVT VT) const {
17777   // Just delegate to the generic legality, clear masks aren't special.
17778   return isShuffleMaskLegal(Mask, VT);
17779 }
17780
17781 //===----------------------------------------------------------------------===//
17782 //                           X86 Scheduler Hooks
17783 //===----------------------------------------------------------------------===//
17784
17785 /// Utility function to emit xbegin specifying the start of an RTM region.
17786 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17787                                      const TargetInstrInfo *TII) {
17788   DebugLoc DL = MI->getDebugLoc();
17789
17790   const BasicBlock *BB = MBB->getBasicBlock();
17791   MachineFunction::iterator I = MBB;
17792   ++I;
17793
17794   // For the v = xbegin(), we generate
17795   //
17796   // thisMBB:
17797   //  xbegin sinkMBB
17798   //
17799   // mainMBB:
17800   //  eax = -1
17801   //
17802   // sinkMBB:
17803   //  v = eax
17804
17805   MachineBasicBlock *thisMBB = MBB;
17806   MachineFunction *MF = MBB->getParent();
17807   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17808   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17809   MF->insert(I, mainMBB);
17810   MF->insert(I, sinkMBB);
17811
17812   // Transfer the remainder of BB and its successor edges to sinkMBB.
17813   sinkMBB->splice(sinkMBB->begin(), MBB,
17814                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17815   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17816
17817   // thisMBB:
17818   //  xbegin sinkMBB
17819   //  # fallthrough to mainMBB
17820   //  # abortion to sinkMBB
17821   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17822   thisMBB->addSuccessor(mainMBB);
17823   thisMBB->addSuccessor(sinkMBB);
17824
17825   // mainMBB:
17826   //  EAX = -1
17827   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17828   mainMBB->addSuccessor(sinkMBB);
17829
17830   // sinkMBB:
17831   // EAX is live into the sinkMBB
17832   sinkMBB->addLiveIn(X86::EAX);
17833   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17834           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17835     .addReg(X86::EAX);
17836
17837   MI->eraseFromParent();
17838   return sinkMBB;
17839 }
17840
17841 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17842 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17843 // in the .td file.
17844 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17845                                        const TargetInstrInfo *TII) {
17846   unsigned Opc;
17847   switch (MI->getOpcode()) {
17848   default: llvm_unreachable("illegal opcode!");
17849   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17850   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17851   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17852   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17853   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17854   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17855   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17856   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17857   }
17858
17859   DebugLoc dl = MI->getDebugLoc();
17860   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17861
17862   unsigned NumArgs = MI->getNumOperands();
17863   for (unsigned i = 1; i < NumArgs; ++i) {
17864     MachineOperand &Op = MI->getOperand(i);
17865     if (!(Op.isReg() && Op.isImplicit()))
17866       MIB.addOperand(Op);
17867   }
17868   if (MI->hasOneMemOperand())
17869     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17870
17871   BuildMI(*BB, MI, dl,
17872     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17873     .addReg(X86::XMM0);
17874
17875   MI->eraseFromParent();
17876   return BB;
17877 }
17878
17879 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17880 // defs in an instruction pattern
17881 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17882                                        const TargetInstrInfo *TII) {
17883   unsigned Opc;
17884   switch (MI->getOpcode()) {
17885   default: llvm_unreachable("illegal opcode!");
17886   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17887   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17888   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17889   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17890   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17891   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17892   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17893   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17894   }
17895
17896   DebugLoc dl = MI->getDebugLoc();
17897   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17898
17899   unsigned NumArgs = MI->getNumOperands(); // remove the results
17900   for (unsigned i = 1; i < NumArgs; ++i) {
17901     MachineOperand &Op = MI->getOperand(i);
17902     if (!(Op.isReg() && Op.isImplicit()))
17903       MIB.addOperand(Op);
17904   }
17905   if (MI->hasOneMemOperand())
17906     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17907
17908   BuildMI(*BB, MI, dl,
17909     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17910     .addReg(X86::ECX);
17911
17912   MI->eraseFromParent();
17913   return BB;
17914 }
17915
17916 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17917                                       const X86Subtarget *Subtarget) {
17918   DebugLoc dl = MI->getDebugLoc();
17919   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17920   // Address into RAX/EAX, other two args into ECX, EDX.
17921   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17922   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17923   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17924   for (int i = 0; i < X86::AddrNumOperands; ++i)
17925     MIB.addOperand(MI->getOperand(i));
17926
17927   unsigned ValOps = X86::AddrNumOperands;
17928   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17929     .addReg(MI->getOperand(ValOps).getReg());
17930   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17931     .addReg(MI->getOperand(ValOps+1).getReg());
17932
17933   // The instruction doesn't actually take any operands though.
17934   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17935
17936   MI->eraseFromParent(); // The pseudo is gone now.
17937   return BB;
17938 }
17939
17940 MachineBasicBlock *
17941 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
17942                                                  MachineBasicBlock *MBB) const {
17943   // Emit va_arg instruction on X86-64.
17944
17945   // Operands to this pseudo-instruction:
17946   // 0  ) Output        : destination address (reg)
17947   // 1-5) Input         : va_list address (addr, i64mem)
17948   // 6  ) ArgSize       : Size (in bytes) of vararg type
17949   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17950   // 8  ) Align         : Alignment of type
17951   // 9  ) EFLAGS (implicit-def)
17952
17953   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17954   static_assert(X86::AddrNumOperands == 5,
17955                 "VAARG_64 assumes 5 address operands");
17956
17957   unsigned DestReg = MI->getOperand(0).getReg();
17958   MachineOperand &Base = MI->getOperand(1);
17959   MachineOperand &Scale = MI->getOperand(2);
17960   MachineOperand &Index = MI->getOperand(3);
17961   MachineOperand &Disp = MI->getOperand(4);
17962   MachineOperand &Segment = MI->getOperand(5);
17963   unsigned ArgSize = MI->getOperand(6).getImm();
17964   unsigned ArgMode = MI->getOperand(7).getImm();
17965   unsigned Align = MI->getOperand(8).getImm();
17966
17967   // Memory Reference
17968   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17969   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17970   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17971
17972   // Machine Information
17973   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17974   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17975   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17976   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17977   DebugLoc DL = MI->getDebugLoc();
17978
17979   // struct va_list {
17980   //   i32   gp_offset
17981   //   i32   fp_offset
17982   //   i64   overflow_area (address)
17983   //   i64   reg_save_area (address)
17984   // }
17985   // sizeof(va_list) = 24
17986   // alignment(va_list) = 8
17987
17988   unsigned TotalNumIntRegs = 6;
17989   unsigned TotalNumXMMRegs = 8;
17990   bool UseGPOffset = (ArgMode == 1);
17991   bool UseFPOffset = (ArgMode == 2);
17992   unsigned MaxOffset = TotalNumIntRegs * 8 +
17993                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17994
17995   /* Align ArgSize to a multiple of 8 */
17996   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17997   bool NeedsAlign = (Align > 8);
17998
17999   MachineBasicBlock *thisMBB = MBB;
18000   MachineBasicBlock *overflowMBB;
18001   MachineBasicBlock *offsetMBB;
18002   MachineBasicBlock *endMBB;
18003
18004   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18005   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18006   unsigned OffsetReg = 0;
18007
18008   if (!UseGPOffset && !UseFPOffset) {
18009     // If we only pull from the overflow region, we don't create a branch.
18010     // We don't need to alter control flow.
18011     OffsetDestReg = 0; // unused
18012     OverflowDestReg = DestReg;
18013
18014     offsetMBB = nullptr;
18015     overflowMBB = thisMBB;
18016     endMBB = thisMBB;
18017   } else {
18018     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18019     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18020     // If not, pull from overflow_area. (branch to overflowMBB)
18021     //
18022     //       thisMBB
18023     //         |     .
18024     //         |        .
18025     //     offsetMBB   overflowMBB
18026     //         |        .
18027     //         |     .
18028     //        endMBB
18029
18030     // Registers for the PHI in endMBB
18031     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18032     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18033
18034     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18035     MachineFunction *MF = MBB->getParent();
18036     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18037     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18038     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18039
18040     MachineFunction::iterator MBBIter = MBB;
18041     ++MBBIter;
18042
18043     // Insert the new basic blocks
18044     MF->insert(MBBIter, offsetMBB);
18045     MF->insert(MBBIter, overflowMBB);
18046     MF->insert(MBBIter, endMBB);
18047
18048     // Transfer the remainder of MBB and its successor edges to endMBB.
18049     endMBB->splice(endMBB->begin(), thisMBB,
18050                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18051     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18052
18053     // Make offsetMBB and overflowMBB successors of thisMBB
18054     thisMBB->addSuccessor(offsetMBB);
18055     thisMBB->addSuccessor(overflowMBB);
18056
18057     // endMBB is a successor of both offsetMBB and overflowMBB
18058     offsetMBB->addSuccessor(endMBB);
18059     overflowMBB->addSuccessor(endMBB);
18060
18061     // Load the offset value into a register
18062     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18063     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18064       .addOperand(Base)
18065       .addOperand(Scale)
18066       .addOperand(Index)
18067       .addDisp(Disp, UseFPOffset ? 4 : 0)
18068       .addOperand(Segment)
18069       .setMemRefs(MMOBegin, MMOEnd);
18070
18071     // Check if there is enough room left to pull this argument.
18072     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18073       .addReg(OffsetReg)
18074       .addImm(MaxOffset + 8 - ArgSizeA8);
18075
18076     // Branch to "overflowMBB" if offset >= max
18077     // Fall through to "offsetMBB" otherwise
18078     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18079       .addMBB(overflowMBB);
18080   }
18081
18082   // In offsetMBB, emit code to use the reg_save_area.
18083   if (offsetMBB) {
18084     assert(OffsetReg != 0);
18085
18086     // Read the reg_save_area address.
18087     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18088     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18089       .addOperand(Base)
18090       .addOperand(Scale)
18091       .addOperand(Index)
18092       .addDisp(Disp, 16)
18093       .addOperand(Segment)
18094       .setMemRefs(MMOBegin, MMOEnd);
18095
18096     // Zero-extend the offset
18097     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18098       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18099         .addImm(0)
18100         .addReg(OffsetReg)
18101         .addImm(X86::sub_32bit);
18102
18103     // Add the offset to the reg_save_area to get the final address.
18104     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18105       .addReg(OffsetReg64)
18106       .addReg(RegSaveReg);
18107
18108     // Compute the offset for the next argument
18109     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18110     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18111       .addReg(OffsetReg)
18112       .addImm(UseFPOffset ? 16 : 8);
18113
18114     // Store it back into the va_list.
18115     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18116       .addOperand(Base)
18117       .addOperand(Scale)
18118       .addOperand(Index)
18119       .addDisp(Disp, UseFPOffset ? 4 : 0)
18120       .addOperand(Segment)
18121       .addReg(NextOffsetReg)
18122       .setMemRefs(MMOBegin, MMOEnd);
18123
18124     // Jump to endMBB
18125     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18126       .addMBB(endMBB);
18127   }
18128
18129   //
18130   // Emit code to use overflow area
18131   //
18132
18133   // Load the overflow_area address into a register.
18134   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18135   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18136     .addOperand(Base)
18137     .addOperand(Scale)
18138     .addOperand(Index)
18139     .addDisp(Disp, 8)
18140     .addOperand(Segment)
18141     .setMemRefs(MMOBegin, MMOEnd);
18142
18143   // If we need to align it, do so. Otherwise, just copy the address
18144   // to OverflowDestReg.
18145   if (NeedsAlign) {
18146     // Align the overflow address
18147     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18148     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18149
18150     // aligned_addr = (addr + (align-1)) & ~(align-1)
18151     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18152       .addReg(OverflowAddrReg)
18153       .addImm(Align-1);
18154
18155     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18156       .addReg(TmpReg)
18157       .addImm(~(uint64_t)(Align-1));
18158   } else {
18159     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18160       .addReg(OverflowAddrReg);
18161   }
18162
18163   // Compute the next overflow address after this argument.
18164   // (the overflow address should be kept 8-byte aligned)
18165   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18166   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18167     .addReg(OverflowDestReg)
18168     .addImm(ArgSizeA8);
18169
18170   // Store the new overflow address.
18171   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18172     .addOperand(Base)
18173     .addOperand(Scale)
18174     .addOperand(Index)
18175     .addDisp(Disp, 8)
18176     .addOperand(Segment)
18177     .addReg(NextAddrReg)
18178     .setMemRefs(MMOBegin, MMOEnd);
18179
18180   // If we branched, emit the PHI to the front of endMBB.
18181   if (offsetMBB) {
18182     BuildMI(*endMBB, endMBB->begin(), DL,
18183             TII->get(X86::PHI), DestReg)
18184       .addReg(OffsetDestReg).addMBB(offsetMBB)
18185       .addReg(OverflowDestReg).addMBB(overflowMBB);
18186   }
18187
18188   // Erase the pseudo instruction
18189   MI->eraseFromParent();
18190
18191   return endMBB;
18192 }
18193
18194 MachineBasicBlock *
18195 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18196                                                  MachineInstr *MI,
18197                                                  MachineBasicBlock *MBB) const {
18198   // Emit code to save XMM registers to the stack. The ABI says that the
18199   // number of registers to save is given in %al, so it's theoretically
18200   // possible to do an indirect jump trick to avoid saving all of them,
18201   // however this code takes a simpler approach and just executes all
18202   // of the stores if %al is non-zero. It's less code, and it's probably
18203   // easier on the hardware branch predictor, and stores aren't all that
18204   // expensive anyway.
18205
18206   // Create the new basic blocks. One block contains all the XMM stores,
18207   // and one block is the final destination regardless of whether any
18208   // stores were performed.
18209   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18210   MachineFunction *F = MBB->getParent();
18211   MachineFunction::iterator MBBIter = MBB;
18212   ++MBBIter;
18213   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18214   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18215   F->insert(MBBIter, XMMSaveMBB);
18216   F->insert(MBBIter, EndMBB);
18217
18218   // Transfer the remainder of MBB and its successor edges to EndMBB.
18219   EndMBB->splice(EndMBB->begin(), MBB,
18220                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18221   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18222
18223   // The original block will now fall through to the XMM save block.
18224   MBB->addSuccessor(XMMSaveMBB);
18225   // The XMMSaveMBB will fall through to the end block.
18226   XMMSaveMBB->addSuccessor(EndMBB);
18227
18228   // Now add the instructions.
18229   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18230   DebugLoc DL = MI->getDebugLoc();
18231
18232   unsigned CountReg = MI->getOperand(0).getReg();
18233   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18234   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18235
18236   if (!Subtarget->isTargetWin64()) {
18237     // If %al is 0, branch around the XMM save block.
18238     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18239     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18240     MBB->addSuccessor(EndMBB);
18241   }
18242
18243   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18244   // that was just emitted, but clearly shouldn't be "saved".
18245   assert((MI->getNumOperands() <= 3 ||
18246           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18247           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18248          && "Expected last argument to be EFLAGS");
18249   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18250   // In the XMM save block, save all the XMM argument registers.
18251   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18252     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18253     MachineMemOperand *MMO =
18254       F->getMachineMemOperand(
18255           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18256         MachineMemOperand::MOStore,
18257         /*Size=*/16, /*Align=*/16);
18258     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18259       .addFrameIndex(RegSaveFrameIndex)
18260       .addImm(/*Scale=*/1)
18261       .addReg(/*IndexReg=*/0)
18262       .addImm(/*Disp=*/Offset)
18263       .addReg(/*Segment=*/0)
18264       .addReg(MI->getOperand(i).getReg())
18265       .addMemOperand(MMO);
18266   }
18267
18268   MI->eraseFromParent();   // The pseudo instruction is gone now.
18269
18270   return EndMBB;
18271 }
18272
18273 // The EFLAGS operand of SelectItr might be missing a kill marker
18274 // because there were multiple uses of EFLAGS, and ISel didn't know
18275 // which to mark. Figure out whether SelectItr should have had a
18276 // kill marker, and set it if it should. Returns the correct kill
18277 // marker value.
18278 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18279                                      MachineBasicBlock* BB,
18280                                      const TargetRegisterInfo* TRI) {
18281   // Scan forward through BB for a use/def of EFLAGS.
18282   MachineBasicBlock::iterator miI(std::next(SelectItr));
18283   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18284     const MachineInstr& mi = *miI;
18285     if (mi.readsRegister(X86::EFLAGS))
18286       return false;
18287     if (mi.definesRegister(X86::EFLAGS))
18288       break; // Should have kill-flag - update below.
18289   }
18290
18291   // If we hit the end of the block, check whether EFLAGS is live into a
18292   // successor.
18293   if (miI == BB->end()) {
18294     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18295                                           sEnd = BB->succ_end();
18296          sItr != sEnd; ++sItr) {
18297       MachineBasicBlock* succ = *sItr;
18298       if (succ->isLiveIn(X86::EFLAGS))
18299         return false;
18300     }
18301   }
18302
18303   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18304   // out. SelectMI should have a kill flag on EFLAGS.
18305   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18306   return true;
18307 }
18308
18309 MachineBasicBlock *
18310 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18311                                      MachineBasicBlock *BB) const {
18312   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18313   DebugLoc DL = MI->getDebugLoc();
18314
18315   // To "insert" a SELECT_CC instruction, we actually have to insert the
18316   // diamond control-flow pattern.  The incoming instruction knows the
18317   // destination vreg to set, the condition code register to branch on, the
18318   // true/false values to select between, and a branch opcode to use.
18319   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18320   MachineFunction::iterator It = BB;
18321   ++It;
18322
18323   //  thisMBB:
18324   //  ...
18325   //   TrueVal = ...
18326   //   cmpTY ccX, r1, r2
18327   //   bCC copy1MBB
18328   //   fallthrough --> copy0MBB
18329   MachineBasicBlock *thisMBB = BB;
18330   MachineFunction *F = BB->getParent();
18331
18332   // We also lower double CMOVs:
18333   //   (CMOV (CMOV F, T, cc1), T, cc2)
18334   // to two successives branches.  For that, we look for another CMOV as the
18335   // following instruction.
18336   //
18337   // Without this, we would add a PHI between the two jumps, which ends up
18338   // creating a few copies all around. For instance, for
18339   //
18340   //    (sitofp (zext (fcmp une)))
18341   //
18342   // we would generate:
18343   //
18344   //         ucomiss %xmm1, %xmm0
18345   //         movss  <1.0f>, %xmm0
18346   //         movaps  %xmm0, %xmm1
18347   //         jne     .LBB5_2
18348   //         xorps   %xmm1, %xmm1
18349   // .LBB5_2:
18350   //         jp      .LBB5_4
18351   //         movaps  %xmm1, %xmm0
18352   // .LBB5_4:
18353   //         retq
18354   //
18355   // because this custom-inserter would have generated:
18356   //
18357   //   A
18358   //   | \
18359   //   |  B
18360   //   | /
18361   //   C
18362   //   | \
18363   //   |  D
18364   //   | /
18365   //   E
18366   //
18367   // A: X = ...; Y = ...
18368   // B: empty
18369   // C: Z = PHI [X, A], [Y, B]
18370   // D: empty
18371   // E: PHI [X, C], [Z, D]
18372   //
18373   // If we lower both CMOVs in a single step, we can instead generate:
18374   //
18375   //   A
18376   //   | \
18377   //   |  C
18378   //   | /|
18379   //   |/ |
18380   //   |  |
18381   //   |  D
18382   //   | /
18383   //   E
18384   //
18385   // A: X = ...; Y = ...
18386   // D: empty
18387   // E: PHI [X, A], [X, C], [Y, D]
18388   //
18389   // Which, in our sitofp/fcmp example, gives us something like:
18390   //
18391   //         ucomiss %xmm1, %xmm0
18392   //         movss  <1.0f>, %xmm0
18393   //         jne     .LBB5_4
18394   //         jp      .LBB5_4
18395   //         xorps   %xmm0, %xmm0
18396   // .LBB5_4:
18397   //         retq
18398   //
18399   MachineInstr *NextCMOV = nullptr;
18400   MachineBasicBlock::iterator NextMIIt =
18401       std::next(MachineBasicBlock::iterator(MI));
18402   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18403       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18404       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18405     NextCMOV = &*NextMIIt;
18406
18407   MachineBasicBlock *jcc1MBB = nullptr;
18408
18409   // If we have a double CMOV, we lower it to two successive branches to
18410   // the same block.  EFLAGS is used by both, so mark it as live in the second.
18411   if (NextCMOV) {
18412     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18413     F->insert(It, jcc1MBB);
18414     jcc1MBB->addLiveIn(X86::EFLAGS);
18415   }
18416
18417   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18418   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18419   F->insert(It, copy0MBB);
18420   F->insert(It, sinkMBB);
18421
18422   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18423   // live into the sink and copy blocks.
18424   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18425
18426   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18427   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18428       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18429     copy0MBB->addLiveIn(X86::EFLAGS);
18430     sinkMBB->addLiveIn(X86::EFLAGS);
18431   }
18432
18433   // Transfer the remainder of BB and its successor edges to sinkMBB.
18434   sinkMBB->splice(sinkMBB->begin(), BB,
18435                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18436   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18437
18438   // Add the true and fallthrough blocks as its successors.
18439   if (NextCMOV) {
18440     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18441     BB->addSuccessor(jcc1MBB);
18442
18443     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18444     // jump to the sinkMBB.
18445     jcc1MBB->addSuccessor(copy0MBB);
18446     jcc1MBB->addSuccessor(sinkMBB);
18447   } else {
18448     BB->addSuccessor(copy0MBB);
18449   }
18450
18451   // The true block target of the first (or only) branch is always sinkMBB.
18452   BB->addSuccessor(sinkMBB);
18453
18454   // Create the conditional branch instruction.
18455   unsigned Opc =
18456     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18457   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18458
18459   if (NextCMOV) {
18460     unsigned Opc2 = X86::GetCondBranchFromCond(
18461         (X86::CondCode)NextCMOV->getOperand(3).getImm());
18462     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18463   }
18464
18465   //  copy0MBB:
18466   //   %FalseValue = ...
18467   //   # fallthrough to sinkMBB
18468   copy0MBB->addSuccessor(sinkMBB);
18469
18470   //  sinkMBB:
18471   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18472   //  ...
18473   MachineInstrBuilder MIB =
18474       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18475               MI->getOperand(0).getReg())
18476           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18477           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18478
18479   // If we have a double CMOV, the second Jcc provides the same incoming
18480   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18481   if (NextCMOV) {
18482     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18483     // Copy the PHI result to the register defined by the second CMOV.
18484     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18485             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18486         .addReg(MI->getOperand(0).getReg());
18487     NextCMOV->eraseFromParent();
18488   }
18489
18490   MI->eraseFromParent();   // The pseudo instruction is gone now.
18491   return sinkMBB;
18492 }
18493
18494 MachineBasicBlock *
18495 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18496                                         MachineBasicBlock *BB) const {
18497   MachineFunction *MF = BB->getParent();
18498   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18499   DebugLoc DL = MI->getDebugLoc();
18500   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18501
18502   assert(MF->shouldSplitStack());
18503
18504   const bool Is64Bit = Subtarget->is64Bit();
18505   const bool IsLP64 = Subtarget->isTarget64BitLP64();
18506
18507   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18508   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18509
18510   // BB:
18511   //  ... [Till the alloca]
18512   // If stacklet is not large enough, jump to mallocMBB
18513   //
18514   // bumpMBB:
18515   //  Allocate by subtracting from RSP
18516   //  Jump to continueMBB
18517   //
18518   // mallocMBB:
18519   //  Allocate by call to runtime
18520   //
18521   // continueMBB:
18522   //  ...
18523   //  [rest of original BB]
18524   //
18525
18526   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18527   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18528   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18529
18530   MachineRegisterInfo &MRI = MF->getRegInfo();
18531   const TargetRegisterClass *AddrRegClass =
18532     getRegClassFor(getPointerTy());
18533
18534   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18535     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18536     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18537     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18538     sizeVReg = MI->getOperand(1).getReg(),
18539     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18540
18541   MachineFunction::iterator MBBIter = BB;
18542   ++MBBIter;
18543
18544   MF->insert(MBBIter, bumpMBB);
18545   MF->insert(MBBIter, mallocMBB);
18546   MF->insert(MBBIter, continueMBB);
18547
18548   continueMBB->splice(continueMBB->begin(), BB,
18549                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18550   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18551
18552   // Add code to the main basic block to check if the stack limit has been hit,
18553   // and if so, jump to mallocMBB otherwise to bumpMBB.
18554   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18555   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18556     .addReg(tmpSPVReg).addReg(sizeVReg);
18557   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18558     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18559     .addReg(SPLimitVReg);
18560   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18561
18562   // bumpMBB simply decreases the stack pointer, since we know the current
18563   // stacklet has enough space.
18564   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18565     .addReg(SPLimitVReg);
18566   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18567     .addReg(SPLimitVReg);
18568   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18569
18570   // Calls into a routine in libgcc to allocate more space from the heap.
18571   const uint32_t *RegMask =
18572       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
18573   if (IsLP64) {
18574     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18575       .addReg(sizeVReg);
18576     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18577       .addExternalSymbol("__morestack_allocate_stack_space")
18578       .addRegMask(RegMask)
18579       .addReg(X86::RDI, RegState::Implicit)
18580       .addReg(X86::RAX, RegState::ImplicitDefine);
18581   } else if (Is64Bit) {
18582     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
18583       .addReg(sizeVReg);
18584     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18585       .addExternalSymbol("__morestack_allocate_stack_space")
18586       .addRegMask(RegMask)
18587       .addReg(X86::EDI, RegState::Implicit)
18588       .addReg(X86::EAX, RegState::ImplicitDefine);
18589   } else {
18590     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18591       .addImm(12);
18592     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18593     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18594       .addExternalSymbol("__morestack_allocate_stack_space")
18595       .addRegMask(RegMask)
18596       .addReg(X86::EAX, RegState::ImplicitDefine);
18597   }
18598
18599   if (!Is64Bit)
18600     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18601       .addImm(16);
18602
18603   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18604     .addReg(IsLP64 ? X86::RAX : X86::EAX);
18605   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18606
18607   // Set up the CFG correctly.
18608   BB->addSuccessor(bumpMBB);
18609   BB->addSuccessor(mallocMBB);
18610   mallocMBB->addSuccessor(continueMBB);
18611   bumpMBB->addSuccessor(continueMBB);
18612
18613   // Take care of the PHI nodes.
18614   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18615           MI->getOperand(0).getReg())
18616     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18617     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18618
18619   // Delete the original pseudo instruction.
18620   MI->eraseFromParent();
18621
18622   // And we're done.
18623   return continueMBB;
18624 }
18625
18626 MachineBasicBlock *
18627 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18628                                         MachineBasicBlock *BB) const {
18629   DebugLoc DL = MI->getDebugLoc();
18630
18631   assert(!Subtarget->isTargetMachO());
18632
18633   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
18634
18635   MI->eraseFromParent();   // The pseudo instruction is gone now.
18636   return BB;
18637 }
18638
18639 MachineBasicBlock *
18640 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18641                                       MachineBasicBlock *BB) const {
18642   // This is pretty easy.  We're taking the value that we received from
18643   // our load from the relocation, sticking it in either RDI (x86-64)
18644   // or EAX and doing an indirect call.  The return value will then
18645   // be in the normal return register.
18646   MachineFunction *F = BB->getParent();
18647   const X86InstrInfo *TII = Subtarget->getInstrInfo();
18648   DebugLoc DL = MI->getDebugLoc();
18649
18650   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18651   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18652
18653   // Get a register mask for the lowered call.
18654   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18655   // proper register mask.
18656   const uint32_t *RegMask =
18657       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
18658   if (Subtarget->is64Bit()) {
18659     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18660                                       TII->get(X86::MOV64rm), X86::RDI)
18661     .addReg(X86::RIP)
18662     .addImm(0).addReg(0)
18663     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18664                       MI->getOperand(3).getTargetFlags())
18665     .addReg(0);
18666     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18667     addDirectMem(MIB, X86::RDI);
18668     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18669   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18670     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18671                                       TII->get(X86::MOV32rm), X86::EAX)
18672     .addReg(0)
18673     .addImm(0).addReg(0)
18674     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18675                       MI->getOperand(3).getTargetFlags())
18676     .addReg(0);
18677     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18678     addDirectMem(MIB, X86::EAX);
18679     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18680   } else {
18681     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18682                                       TII->get(X86::MOV32rm), X86::EAX)
18683     .addReg(TII->getGlobalBaseReg(F))
18684     .addImm(0).addReg(0)
18685     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18686                       MI->getOperand(3).getTargetFlags())
18687     .addReg(0);
18688     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18689     addDirectMem(MIB, X86::EAX);
18690     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18691   }
18692
18693   MI->eraseFromParent(); // The pseudo instruction is gone now.
18694   return BB;
18695 }
18696
18697 MachineBasicBlock *
18698 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18699                                     MachineBasicBlock *MBB) const {
18700   DebugLoc DL = MI->getDebugLoc();
18701   MachineFunction *MF = MBB->getParent();
18702   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18703   MachineRegisterInfo &MRI = MF->getRegInfo();
18704
18705   const BasicBlock *BB = MBB->getBasicBlock();
18706   MachineFunction::iterator I = MBB;
18707   ++I;
18708
18709   // Memory Reference
18710   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18711   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18712
18713   unsigned DstReg;
18714   unsigned MemOpndSlot = 0;
18715
18716   unsigned CurOp = 0;
18717
18718   DstReg = MI->getOperand(CurOp++).getReg();
18719   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18720   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18721   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18722   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18723
18724   MemOpndSlot = CurOp;
18725
18726   MVT PVT = getPointerTy();
18727   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18728          "Invalid Pointer Size!");
18729
18730   // For v = setjmp(buf), we generate
18731   //
18732   // thisMBB:
18733   //  buf[LabelOffset] = restoreMBB
18734   //  SjLjSetup restoreMBB
18735   //
18736   // mainMBB:
18737   //  v_main = 0
18738   //
18739   // sinkMBB:
18740   //  v = phi(main, restore)
18741   //
18742   // restoreMBB:
18743   //  if base pointer being used, load it from frame
18744   //  v_restore = 1
18745
18746   MachineBasicBlock *thisMBB = MBB;
18747   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18748   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18749   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18750   MF->insert(I, mainMBB);
18751   MF->insert(I, sinkMBB);
18752   MF->push_back(restoreMBB);
18753
18754   MachineInstrBuilder MIB;
18755
18756   // Transfer the remainder of BB and its successor edges to sinkMBB.
18757   sinkMBB->splice(sinkMBB->begin(), MBB,
18758                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18759   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18760
18761   // thisMBB:
18762   unsigned PtrStoreOpc = 0;
18763   unsigned LabelReg = 0;
18764   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18765   Reloc::Model RM = MF->getTarget().getRelocationModel();
18766   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18767                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18768
18769   // Prepare IP either in reg or imm.
18770   if (!UseImmLabel) {
18771     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18772     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18773     LabelReg = MRI.createVirtualRegister(PtrRC);
18774     if (Subtarget->is64Bit()) {
18775       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18776               .addReg(X86::RIP)
18777               .addImm(0)
18778               .addReg(0)
18779               .addMBB(restoreMBB)
18780               .addReg(0);
18781     } else {
18782       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18783       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18784               .addReg(XII->getGlobalBaseReg(MF))
18785               .addImm(0)
18786               .addReg(0)
18787               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18788               .addReg(0);
18789     }
18790   } else
18791     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18792   // Store IP
18793   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18794   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18795     if (i == X86::AddrDisp)
18796       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18797     else
18798       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18799   }
18800   if (!UseImmLabel)
18801     MIB.addReg(LabelReg);
18802   else
18803     MIB.addMBB(restoreMBB);
18804   MIB.setMemRefs(MMOBegin, MMOEnd);
18805   // Setup
18806   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18807           .addMBB(restoreMBB);
18808
18809   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18810   MIB.addRegMask(RegInfo->getNoPreservedMask());
18811   thisMBB->addSuccessor(mainMBB);
18812   thisMBB->addSuccessor(restoreMBB);
18813
18814   // mainMBB:
18815   //  EAX = 0
18816   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18817   mainMBB->addSuccessor(sinkMBB);
18818
18819   // sinkMBB:
18820   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18821           TII->get(X86::PHI), DstReg)
18822     .addReg(mainDstReg).addMBB(mainMBB)
18823     .addReg(restoreDstReg).addMBB(restoreMBB);
18824
18825   // restoreMBB:
18826   if (RegInfo->hasBasePointer(*MF)) {
18827     const bool Uses64BitFramePtr =
18828         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
18829     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
18830     X86FI->setRestoreBasePointer(MF);
18831     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
18832     unsigned BasePtr = RegInfo->getBaseRegister();
18833     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
18834     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
18835                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
18836       .setMIFlag(MachineInstr::FrameSetup);
18837   }
18838   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18839   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
18840   restoreMBB->addSuccessor(sinkMBB);
18841
18842   MI->eraseFromParent();
18843   return sinkMBB;
18844 }
18845
18846 MachineBasicBlock *
18847 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18848                                      MachineBasicBlock *MBB) const {
18849   DebugLoc DL = MI->getDebugLoc();
18850   MachineFunction *MF = MBB->getParent();
18851   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18852   MachineRegisterInfo &MRI = MF->getRegInfo();
18853
18854   // Memory Reference
18855   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18856   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18857
18858   MVT PVT = getPointerTy();
18859   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18860          "Invalid Pointer Size!");
18861
18862   const TargetRegisterClass *RC =
18863     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18864   unsigned Tmp = MRI.createVirtualRegister(RC);
18865   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18866   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18867   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18868   unsigned SP = RegInfo->getStackRegister();
18869
18870   MachineInstrBuilder MIB;
18871
18872   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18873   const int64_t SPOffset = 2 * PVT.getStoreSize();
18874
18875   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18876   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18877
18878   // Reload FP
18879   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18880   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18881     MIB.addOperand(MI->getOperand(i));
18882   MIB.setMemRefs(MMOBegin, MMOEnd);
18883   // Reload IP
18884   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18885   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18886     if (i == X86::AddrDisp)
18887       MIB.addDisp(MI->getOperand(i), LabelOffset);
18888     else
18889       MIB.addOperand(MI->getOperand(i));
18890   }
18891   MIB.setMemRefs(MMOBegin, MMOEnd);
18892   // Reload SP
18893   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18894   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18895     if (i == X86::AddrDisp)
18896       MIB.addDisp(MI->getOperand(i), SPOffset);
18897     else
18898       MIB.addOperand(MI->getOperand(i));
18899   }
18900   MIB.setMemRefs(MMOBegin, MMOEnd);
18901   // Jump
18902   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18903
18904   MI->eraseFromParent();
18905   return MBB;
18906 }
18907
18908 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18909 // accumulator loops. Writing back to the accumulator allows the coalescer
18910 // to remove extra copies in the loop.
18911 MachineBasicBlock *
18912 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18913                                  MachineBasicBlock *MBB) const {
18914   MachineOperand &AddendOp = MI->getOperand(3);
18915
18916   // Bail out early if the addend isn't a register - we can't switch these.
18917   if (!AddendOp.isReg())
18918     return MBB;
18919
18920   MachineFunction &MF = *MBB->getParent();
18921   MachineRegisterInfo &MRI = MF.getRegInfo();
18922
18923   // Check whether the addend is defined by a PHI:
18924   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18925   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18926   if (!AddendDef.isPHI())
18927     return MBB;
18928
18929   // Look for the following pattern:
18930   // loop:
18931   //   %addend = phi [%entry, 0], [%loop, %result]
18932   //   ...
18933   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18934
18935   // Replace with:
18936   //   loop:
18937   //   %addend = phi [%entry, 0], [%loop, %result]
18938   //   ...
18939   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18940
18941   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18942     assert(AddendDef.getOperand(i).isReg());
18943     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18944     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18945     if (&PHISrcInst == MI) {
18946       // Found a matching instruction.
18947       unsigned NewFMAOpc = 0;
18948       switch (MI->getOpcode()) {
18949         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18950         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18951         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18952         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18953         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18954         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18955         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18956         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18957         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18958         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18959         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18960         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18961         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18962         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18963         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18964         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18965         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
18966         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
18967         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
18968         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
18969
18970         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18971         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18972         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18973         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18974         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18975         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18976         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18977         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18978         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
18979         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
18980         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
18981         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
18982         default: llvm_unreachable("Unrecognized FMA variant.");
18983       }
18984
18985       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
18986       MachineInstrBuilder MIB =
18987         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18988         .addOperand(MI->getOperand(0))
18989         .addOperand(MI->getOperand(3))
18990         .addOperand(MI->getOperand(2))
18991         .addOperand(MI->getOperand(1));
18992       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18993       MI->eraseFromParent();
18994     }
18995   }
18996
18997   return MBB;
18998 }
18999
19000 MachineBasicBlock *
19001 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19002                                                MachineBasicBlock *BB) const {
19003   switch (MI->getOpcode()) {
19004   default: llvm_unreachable("Unexpected instr type to insert");
19005   case X86::TAILJMPd64:
19006   case X86::TAILJMPr64:
19007   case X86::TAILJMPm64:
19008   case X86::TAILJMPd64_REX:
19009   case X86::TAILJMPr64_REX:
19010   case X86::TAILJMPm64_REX:
19011     llvm_unreachable("TAILJMP64 would not be touched here.");
19012   case X86::TCRETURNdi64:
19013   case X86::TCRETURNri64:
19014   case X86::TCRETURNmi64:
19015     return BB;
19016   case X86::WIN_ALLOCA:
19017     return EmitLoweredWinAlloca(MI, BB);
19018   case X86::SEG_ALLOCA_32:
19019   case X86::SEG_ALLOCA_64:
19020     return EmitLoweredSegAlloca(MI, BB);
19021   case X86::TLSCall_32:
19022   case X86::TLSCall_64:
19023     return EmitLoweredTLSCall(MI, BB);
19024   case X86::CMOV_GR8:
19025   case X86::CMOV_FR32:
19026   case X86::CMOV_FR64:
19027   case X86::CMOV_V4F32:
19028   case X86::CMOV_V2F64:
19029   case X86::CMOV_V2I64:
19030   case X86::CMOV_V8F32:
19031   case X86::CMOV_V4F64:
19032   case X86::CMOV_V4I64:
19033   case X86::CMOV_V16F32:
19034   case X86::CMOV_V8F64:
19035   case X86::CMOV_V8I64:
19036   case X86::CMOV_GR16:
19037   case X86::CMOV_GR32:
19038   case X86::CMOV_RFP32:
19039   case X86::CMOV_RFP64:
19040   case X86::CMOV_RFP80:
19041     return EmitLoweredSelect(MI, BB);
19042
19043   case X86::FP32_TO_INT16_IN_MEM:
19044   case X86::FP32_TO_INT32_IN_MEM:
19045   case X86::FP32_TO_INT64_IN_MEM:
19046   case X86::FP64_TO_INT16_IN_MEM:
19047   case X86::FP64_TO_INT32_IN_MEM:
19048   case X86::FP64_TO_INT64_IN_MEM:
19049   case X86::FP80_TO_INT16_IN_MEM:
19050   case X86::FP80_TO_INT32_IN_MEM:
19051   case X86::FP80_TO_INT64_IN_MEM: {
19052     MachineFunction *F = BB->getParent();
19053     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19054     DebugLoc DL = MI->getDebugLoc();
19055
19056     // Change the floating point control register to use "round towards zero"
19057     // mode when truncating to an integer value.
19058     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19059     addFrameReference(BuildMI(*BB, MI, DL,
19060                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19061
19062     // Load the old value of the high byte of the control word...
19063     unsigned OldCW =
19064       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19065     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19066                       CWFrameIdx);
19067
19068     // Set the high part to be round to zero...
19069     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19070       .addImm(0xC7F);
19071
19072     // Reload the modified control word now...
19073     addFrameReference(BuildMI(*BB, MI, DL,
19074                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19075
19076     // Restore the memory image of control word to original value
19077     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19078       .addReg(OldCW);
19079
19080     // Get the X86 opcode to use.
19081     unsigned Opc;
19082     switch (MI->getOpcode()) {
19083     default: llvm_unreachable("illegal opcode!");
19084     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19085     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19086     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19087     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19088     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19089     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19090     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19091     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19092     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19093     }
19094
19095     X86AddressMode AM;
19096     MachineOperand &Op = MI->getOperand(0);
19097     if (Op.isReg()) {
19098       AM.BaseType = X86AddressMode::RegBase;
19099       AM.Base.Reg = Op.getReg();
19100     } else {
19101       AM.BaseType = X86AddressMode::FrameIndexBase;
19102       AM.Base.FrameIndex = Op.getIndex();
19103     }
19104     Op = MI->getOperand(1);
19105     if (Op.isImm())
19106       AM.Scale = Op.getImm();
19107     Op = MI->getOperand(2);
19108     if (Op.isImm())
19109       AM.IndexReg = Op.getImm();
19110     Op = MI->getOperand(3);
19111     if (Op.isGlobal()) {
19112       AM.GV = Op.getGlobal();
19113     } else {
19114       AM.Disp = Op.getImm();
19115     }
19116     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19117                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19118
19119     // Reload the original control word now.
19120     addFrameReference(BuildMI(*BB, MI, DL,
19121                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19122
19123     MI->eraseFromParent();   // The pseudo instruction is gone now.
19124     return BB;
19125   }
19126     // String/text processing lowering.
19127   case X86::PCMPISTRM128REG:
19128   case X86::VPCMPISTRM128REG:
19129   case X86::PCMPISTRM128MEM:
19130   case X86::VPCMPISTRM128MEM:
19131   case X86::PCMPESTRM128REG:
19132   case X86::VPCMPESTRM128REG:
19133   case X86::PCMPESTRM128MEM:
19134   case X86::VPCMPESTRM128MEM:
19135     assert(Subtarget->hasSSE42() &&
19136            "Target must have SSE4.2 or AVX features enabled");
19137     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19138
19139   // String/text processing lowering.
19140   case X86::PCMPISTRIREG:
19141   case X86::VPCMPISTRIREG:
19142   case X86::PCMPISTRIMEM:
19143   case X86::VPCMPISTRIMEM:
19144   case X86::PCMPESTRIREG:
19145   case X86::VPCMPESTRIREG:
19146   case X86::PCMPESTRIMEM:
19147   case X86::VPCMPESTRIMEM:
19148     assert(Subtarget->hasSSE42() &&
19149            "Target must have SSE4.2 or AVX features enabled");
19150     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19151
19152   // Thread synchronization.
19153   case X86::MONITOR:
19154     return EmitMonitor(MI, BB, Subtarget);
19155
19156   // xbegin
19157   case X86::XBEGIN:
19158     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19159
19160   case X86::VASTART_SAVE_XMM_REGS:
19161     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19162
19163   case X86::VAARG_64:
19164     return EmitVAARG64WithCustomInserter(MI, BB);
19165
19166   case X86::EH_SjLj_SetJmp32:
19167   case X86::EH_SjLj_SetJmp64:
19168     return emitEHSjLjSetJmp(MI, BB);
19169
19170   case X86::EH_SjLj_LongJmp32:
19171   case X86::EH_SjLj_LongJmp64:
19172     return emitEHSjLjLongJmp(MI, BB);
19173
19174   case TargetOpcode::STATEPOINT:
19175     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19176     // this point in the process.  We diverge later.
19177     return emitPatchPoint(MI, BB);
19178
19179   case TargetOpcode::STACKMAP:
19180   case TargetOpcode::PATCHPOINT:
19181     return emitPatchPoint(MI, BB);
19182
19183   case X86::VFMADDPDr213r:
19184   case X86::VFMADDPSr213r:
19185   case X86::VFMADDSDr213r:
19186   case X86::VFMADDSSr213r:
19187   case X86::VFMSUBPDr213r:
19188   case X86::VFMSUBPSr213r:
19189   case X86::VFMSUBSDr213r:
19190   case X86::VFMSUBSSr213r:
19191   case X86::VFNMADDPDr213r:
19192   case X86::VFNMADDPSr213r:
19193   case X86::VFNMADDSDr213r:
19194   case X86::VFNMADDSSr213r:
19195   case X86::VFNMSUBPDr213r:
19196   case X86::VFNMSUBPSr213r:
19197   case X86::VFNMSUBSDr213r:
19198   case X86::VFNMSUBSSr213r:
19199   case X86::VFMADDSUBPDr213r:
19200   case X86::VFMADDSUBPSr213r:
19201   case X86::VFMSUBADDPDr213r:
19202   case X86::VFMSUBADDPSr213r:
19203   case X86::VFMADDPDr213rY:
19204   case X86::VFMADDPSr213rY:
19205   case X86::VFMSUBPDr213rY:
19206   case X86::VFMSUBPSr213rY:
19207   case X86::VFNMADDPDr213rY:
19208   case X86::VFNMADDPSr213rY:
19209   case X86::VFNMSUBPDr213rY:
19210   case X86::VFNMSUBPSr213rY:
19211   case X86::VFMADDSUBPDr213rY:
19212   case X86::VFMADDSUBPSr213rY:
19213   case X86::VFMSUBADDPDr213rY:
19214   case X86::VFMSUBADDPSr213rY:
19215     return emitFMA3Instr(MI, BB);
19216   }
19217 }
19218
19219 //===----------------------------------------------------------------------===//
19220 //                           X86 Optimization Hooks
19221 //===----------------------------------------------------------------------===//
19222
19223 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19224                                                       APInt &KnownZero,
19225                                                       APInt &KnownOne,
19226                                                       const SelectionDAG &DAG,
19227                                                       unsigned Depth) const {
19228   unsigned BitWidth = KnownZero.getBitWidth();
19229   unsigned Opc = Op.getOpcode();
19230   assert((Opc >= ISD::BUILTIN_OP_END ||
19231           Opc == ISD::INTRINSIC_WO_CHAIN ||
19232           Opc == ISD::INTRINSIC_W_CHAIN ||
19233           Opc == ISD::INTRINSIC_VOID) &&
19234          "Should use MaskedValueIsZero if you don't know whether Op"
19235          " is a target node!");
19236
19237   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19238   switch (Opc) {
19239   default: break;
19240   case X86ISD::ADD:
19241   case X86ISD::SUB:
19242   case X86ISD::ADC:
19243   case X86ISD::SBB:
19244   case X86ISD::SMUL:
19245   case X86ISD::UMUL:
19246   case X86ISD::INC:
19247   case X86ISD::DEC:
19248   case X86ISD::OR:
19249   case X86ISD::XOR:
19250   case X86ISD::AND:
19251     // These nodes' second result is a boolean.
19252     if (Op.getResNo() == 0)
19253       break;
19254     // Fallthrough
19255   case X86ISD::SETCC:
19256     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19257     break;
19258   case ISD::INTRINSIC_WO_CHAIN: {
19259     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19260     unsigned NumLoBits = 0;
19261     switch (IntId) {
19262     default: break;
19263     case Intrinsic::x86_sse_movmsk_ps:
19264     case Intrinsic::x86_avx_movmsk_ps_256:
19265     case Intrinsic::x86_sse2_movmsk_pd:
19266     case Intrinsic::x86_avx_movmsk_pd_256:
19267     case Intrinsic::x86_mmx_pmovmskb:
19268     case Intrinsic::x86_sse2_pmovmskb_128:
19269     case Intrinsic::x86_avx2_pmovmskb: {
19270       // High bits of movmskp{s|d}, pmovmskb are known zero.
19271       switch (IntId) {
19272         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19273         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19274         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19275         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19276         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19277         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19278         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19279         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19280       }
19281       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19282       break;
19283     }
19284     }
19285     break;
19286   }
19287   }
19288 }
19289
19290 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19291   SDValue Op,
19292   const SelectionDAG &,
19293   unsigned Depth) const {
19294   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19295   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19296     return Op.getValueType().getScalarType().getSizeInBits();
19297
19298   // Fallback case.
19299   return 1;
19300 }
19301
19302 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19303 /// node is a GlobalAddress + offset.
19304 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19305                                        const GlobalValue* &GA,
19306                                        int64_t &Offset) const {
19307   if (N->getOpcode() == X86ISD::Wrapper) {
19308     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19309       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19310       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19311       return true;
19312     }
19313   }
19314   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19315 }
19316
19317 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19318 /// same as extracting the high 128-bit part of 256-bit vector and then
19319 /// inserting the result into the low part of a new 256-bit vector
19320 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19321   EVT VT = SVOp->getValueType(0);
19322   unsigned NumElems = VT.getVectorNumElements();
19323
19324   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19325   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19326     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19327         SVOp->getMaskElt(j) >= 0)
19328       return false;
19329
19330   return true;
19331 }
19332
19333 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19334 /// same as extracting the low 128-bit part of 256-bit vector and then
19335 /// inserting the result into the high part of a new 256-bit vector
19336 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19337   EVT VT = SVOp->getValueType(0);
19338   unsigned NumElems = VT.getVectorNumElements();
19339
19340   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19341   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19342     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19343         SVOp->getMaskElt(j) >= 0)
19344       return false;
19345
19346   return true;
19347 }
19348
19349 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19350 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19351                                         TargetLowering::DAGCombinerInfo &DCI,
19352                                         const X86Subtarget* Subtarget) {
19353   SDLoc dl(N);
19354   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19355   SDValue V1 = SVOp->getOperand(0);
19356   SDValue V2 = SVOp->getOperand(1);
19357   EVT VT = SVOp->getValueType(0);
19358   unsigned NumElems = VT.getVectorNumElements();
19359
19360   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19361       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19362     //
19363     //                   0,0,0,...
19364     //                      |
19365     //    V      UNDEF    BUILD_VECTOR    UNDEF
19366     //     \      /           \           /
19367     //  CONCAT_VECTOR         CONCAT_VECTOR
19368     //         \                  /
19369     //          \                /
19370     //          RESULT: V + zero extended
19371     //
19372     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19373         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19374         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19375       return SDValue();
19376
19377     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19378       return SDValue();
19379
19380     // To match the shuffle mask, the first half of the mask should
19381     // be exactly the first vector, and all the rest a splat with the
19382     // first element of the second one.
19383     for (unsigned i = 0; i != NumElems/2; ++i)
19384       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19385           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19386         return SDValue();
19387
19388     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19389     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19390       if (Ld->hasNUsesOfValue(1, 0)) {
19391         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19392         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19393         SDValue ResNode =
19394           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19395                                   Ld->getMemoryVT(),
19396                                   Ld->getPointerInfo(),
19397                                   Ld->getAlignment(),
19398                                   false/*isVolatile*/, true/*ReadMem*/,
19399                                   false/*WriteMem*/);
19400
19401         // Make sure the newly-created LOAD is in the same position as Ld in
19402         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19403         // and update uses of Ld's output chain to use the TokenFactor.
19404         if (Ld->hasAnyUseOfValue(1)) {
19405           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19406                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19407           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19408           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19409                                  SDValue(ResNode.getNode(), 1));
19410         }
19411
19412         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19413       }
19414     }
19415
19416     // Emit a zeroed vector and insert the desired subvector on its
19417     // first half.
19418     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19419     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19420     return DCI.CombineTo(N, InsV);
19421   }
19422
19423   //===--------------------------------------------------------------------===//
19424   // Combine some shuffles into subvector extracts and inserts:
19425   //
19426
19427   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19428   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19429     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19430     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19431     return DCI.CombineTo(N, InsV);
19432   }
19433
19434   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19435   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19436     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19437     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19438     return DCI.CombineTo(N, InsV);
19439   }
19440
19441   return SDValue();
19442 }
19443
19444 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19445 /// possible.
19446 ///
19447 /// This is the leaf of the recursive combinine below. When we have found some
19448 /// chain of single-use x86 shuffle instructions and accumulated the combined
19449 /// shuffle mask represented by them, this will try to pattern match that mask
19450 /// into either a single instruction if there is a special purpose instruction
19451 /// for this operation, or into a PSHUFB instruction which is a fully general
19452 /// instruction but should only be used to replace chains over a certain depth.
19453 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19454                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19455                                    TargetLowering::DAGCombinerInfo &DCI,
19456                                    const X86Subtarget *Subtarget) {
19457   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19458
19459   // Find the operand that enters the chain. Note that multiple uses are OK
19460   // here, we're not going to remove the operand we find.
19461   SDValue Input = Op.getOperand(0);
19462   while (Input.getOpcode() == ISD::BITCAST)
19463     Input = Input.getOperand(0);
19464
19465   MVT VT = Input.getSimpleValueType();
19466   MVT RootVT = Root.getSimpleValueType();
19467   SDLoc DL(Root);
19468
19469   // Just remove no-op shuffle masks.
19470   if (Mask.size() == 1) {
19471     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19472                   /*AddTo*/ true);
19473     return true;
19474   }
19475
19476   // Use the float domain if the operand type is a floating point type.
19477   bool FloatDomain = VT.isFloatingPoint();
19478
19479   // For floating point shuffles, we don't have free copies in the shuffle
19480   // instructions or the ability to load as part of the instruction, so
19481   // canonicalize their shuffles to UNPCK or MOV variants.
19482   //
19483   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19484   // vectors because it can have a load folded into it that UNPCK cannot. This
19485   // doesn't preclude something switching to the shorter encoding post-RA.
19486   //
19487   // FIXME: Should teach these routines about AVX vector widths.
19488   if (FloatDomain && VT.getSizeInBits() == 128) {
19489     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19490       bool Lo = Mask.equals({0, 0});
19491       unsigned Shuffle;
19492       MVT ShuffleVT;
19493       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19494       // is no slower than UNPCKLPD but has the option to fold the input operand
19495       // into even an unaligned memory load.
19496       if (Lo && Subtarget->hasSSE3()) {
19497         Shuffle = X86ISD::MOVDDUP;
19498         ShuffleVT = MVT::v2f64;
19499       } else {
19500         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19501         // than the UNPCK variants.
19502         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19503         ShuffleVT = MVT::v4f32;
19504       }
19505       if (Depth == 1 && Root->getOpcode() == Shuffle)
19506         return false; // Nothing to do!
19507       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19508       DCI.AddToWorklist(Op.getNode());
19509       if (Shuffle == X86ISD::MOVDDUP)
19510         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19511       else
19512         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19513       DCI.AddToWorklist(Op.getNode());
19514       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19515                     /*AddTo*/ true);
19516       return true;
19517     }
19518     if (Subtarget->hasSSE3() &&
19519         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19520       bool Lo = Mask.equals({0, 0, 2, 2});
19521       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19522       MVT ShuffleVT = MVT::v4f32;
19523       if (Depth == 1 && Root->getOpcode() == Shuffle)
19524         return false; // Nothing to do!
19525       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19526       DCI.AddToWorklist(Op.getNode());
19527       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19528       DCI.AddToWorklist(Op.getNode());
19529       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19530                     /*AddTo*/ true);
19531       return true;
19532     }
19533     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19534       bool Lo = Mask.equals({0, 0, 1, 1});
19535       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19536       MVT ShuffleVT = MVT::v4f32;
19537       if (Depth == 1 && Root->getOpcode() == Shuffle)
19538         return false; // Nothing to do!
19539       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19540       DCI.AddToWorklist(Op.getNode());
19541       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19542       DCI.AddToWorklist(Op.getNode());
19543       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19544                     /*AddTo*/ true);
19545       return true;
19546     }
19547   }
19548
19549   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19550   // variants as none of these have single-instruction variants that are
19551   // superior to the UNPCK formulation.
19552   if (!FloatDomain && VT.getSizeInBits() == 128 &&
19553       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19554        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19555        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
19556        Mask.equals(
19557            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
19558     bool Lo = Mask[0] == 0;
19559     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19560     if (Depth == 1 && Root->getOpcode() == Shuffle)
19561       return false; // Nothing to do!
19562     MVT ShuffleVT;
19563     switch (Mask.size()) {
19564     case 8:
19565       ShuffleVT = MVT::v8i16;
19566       break;
19567     case 16:
19568       ShuffleVT = MVT::v16i8;
19569       break;
19570     default:
19571       llvm_unreachable("Impossible mask size!");
19572     };
19573     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19574     DCI.AddToWorklist(Op.getNode());
19575     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19576     DCI.AddToWorklist(Op.getNode());
19577     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19578                   /*AddTo*/ true);
19579     return true;
19580   }
19581
19582   // Don't try to re-form single instruction chains under any circumstances now
19583   // that we've done encoding canonicalization for them.
19584   if (Depth < 2)
19585     return false;
19586
19587   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19588   // can replace them with a single PSHUFB instruction profitably. Intel's
19589   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19590   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19591   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19592     SmallVector<SDValue, 16> PSHUFBMask;
19593     int NumBytes = VT.getSizeInBits() / 8;
19594     int Ratio = NumBytes / Mask.size();
19595     for (int i = 0; i < NumBytes; ++i) {
19596       if (Mask[i / Ratio] == SM_SentinelUndef) {
19597         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
19598         continue;
19599       }
19600       int M = Mask[i / Ratio] != SM_SentinelZero
19601                   ? Ratio * Mask[i / Ratio] + i % Ratio
19602                   : 255;
19603       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19604     }
19605     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
19606     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
19607     DCI.AddToWorklist(Op.getNode());
19608     SDValue PSHUFBMaskOp =
19609         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
19610     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19611     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
19612     DCI.AddToWorklist(Op.getNode());
19613     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19614                   /*AddTo*/ true);
19615     return true;
19616   }
19617
19618   // Failed to find any combines.
19619   return false;
19620 }
19621
19622 /// \brief Fully generic combining of x86 shuffle instructions.
19623 ///
19624 /// This should be the last combine run over the x86 shuffle instructions. Once
19625 /// they have been fully optimized, this will recursively consider all chains
19626 /// of single-use shuffle instructions, build a generic model of the cumulative
19627 /// shuffle operation, and check for simpler instructions which implement this
19628 /// operation. We use this primarily for two purposes:
19629 ///
19630 /// 1) Collapse generic shuffles to specialized single instructions when
19631 ///    equivalent. In most cases, this is just an encoding size win, but
19632 ///    sometimes we will collapse multiple generic shuffles into a single
19633 ///    special-purpose shuffle.
19634 /// 2) Look for sequences of shuffle instructions with 3 or more total
19635 ///    instructions, and replace them with the slightly more expensive SSSE3
19636 ///    PSHUFB instruction if available. We do this as the last combining step
19637 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19638 ///    a suitable short sequence of other instructions. The PHUFB will either
19639 ///    use a register or have to read from memory and so is slightly (but only
19640 ///    slightly) more expensive than the other shuffle instructions.
19641 ///
19642 /// Because this is inherently a quadratic operation (for each shuffle in
19643 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19644 /// This should never be an issue in practice as the shuffle lowering doesn't
19645 /// produce sequences of more than 8 instructions.
19646 ///
19647 /// FIXME: We will currently miss some cases where the redundant shuffling
19648 /// would simplify under the threshold for PSHUFB formation because of
19649 /// combine-ordering. To fix this, we should do the redundant instruction
19650 /// combining in this recursive walk.
19651 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19652                                           ArrayRef<int> RootMask,
19653                                           int Depth, bool HasPSHUFB,
19654                                           SelectionDAG &DAG,
19655                                           TargetLowering::DAGCombinerInfo &DCI,
19656                                           const X86Subtarget *Subtarget) {
19657   // Bound the depth of our recursive combine because this is ultimately
19658   // quadratic in nature.
19659   if (Depth > 8)
19660     return false;
19661
19662   // Directly rip through bitcasts to find the underlying operand.
19663   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19664     Op = Op.getOperand(0);
19665
19666   MVT VT = Op.getSimpleValueType();
19667   if (!VT.isVector())
19668     return false; // Bail if we hit a non-vector.
19669
19670   assert(Root.getSimpleValueType().isVector() &&
19671          "Shuffles operate on vector types!");
19672   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19673          "Can only combine shuffles of the same vector register size.");
19674
19675   if (!isTargetShuffle(Op.getOpcode()))
19676     return false;
19677   SmallVector<int, 16> OpMask;
19678   bool IsUnary;
19679   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19680   // We only can combine unary shuffles which we can decode the mask for.
19681   if (!HaveMask || !IsUnary)
19682     return false;
19683
19684   assert(VT.getVectorNumElements() == OpMask.size() &&
19685          "Different mask size from vector size!");
19686   assert(((RootMask.size() > OpMask.size() &&
19687            RootMask.size() % OpMask.size() == 0) ||
19688           (OpMask.size() > RootMask.size() &&
19689            OpMask.size() % RootMask.size() == 0) ||
19690           OpMask.size() == RootMask.size()) &&
19691          "The smaller number of elements must divide the larger.");
19692   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19693   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19694   assert(((RootRatio == 1 && OpRatio == 1) ||
19695           (RootRatio == 1) != (OpRatio == 1)) &&
19696          "Must not have a ratio for both incoming and op masks!");
19697
19698   SmallVector<int, 16> Mask;
19699   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19700
19701   // Merge this shuffle operation's mask into our accumulated mask. Note that
19702   // this shuffle's mask will be the first applied to the input, followed by the
19703   // root mask to get us all the way to the root value arrangement. The reason
19704   // for this order is that we are recursing up the operation chain.
19705   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19706     int RootIdx = i / RootRatio;
19707     if (RootMask[RootIdx] < 0) {
19708       // This is a zero or undef lane, we're done.
19709       Mask.push_back(RootMask[RootIdx]);
19710       continue;
19711     }
19712
19713     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19714     int OpIdx = RootMaskedIdx / OpRatio;
19715     if (OpMask[OpIdx] < 0) {
19716       // The incoming lanes are zero or undef, it doesn't matter which ones we
19717       // are using.
19718       Mask.push_back(OpMask[OpIdx]);
19719       continue;
19720     }
19721
19722     // Ok, we have non-zero lanes, map them through.
19723     Mask.push_back(OpMask[OpIdx] * OpRatio +
19724                    RootMaskedIdx % OpRatio);
19725   }
19726
19727   // See if we can recurse into the operand to combine more things.
19728   switch (Op.getOpcode()) {
19729     case X86ISD::PSHUFB:
19730       HasPSHUFB = true;
19731     case X86ISD::PSHUFD:
19732     case X86ISD::PSHUFHW:
19733     case X86ISD::PSHUFLW:
19734       if (Op.getOperand(0).hasOneUse() &&
19735           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19736                                         HasPSHUFB, DAG, DCI, Subtarget))
19737         return true;
19738       break;
19739
19740     case X86ISD::UNPCKL:
19741     case X86ISD::UNPCKH:
19742       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19743       // We can't check for single use, we have to check that this shuffle is the only user.
19744       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19745           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19746                                         HasPSHUFB, DAG, DCI, Subtarget))
19747           return true;
19748       break;
19749   }
19750
19751   // Minor canonicalization of the accumulated shuffle mask to make it easier
19752   // to match below. All this does is detect masks with squential pairs of
19753   // elements, and shrink them to the half-width mask. It does this in a loop
19754   // so it will reduce the size of the mask to the minimal width mask which
19755   // performs an equivalent shuffle.
19756   SmallVector<int, 16> WidenedMask;
19757   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
19758     Mask = std::move(WidenedMask);
19759     WidenedMask.clear();
19760   }
19761
19762   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19763                                 Subtarget);
19764 }
19765
19766 /// \brief Get the PSHUF-style mask from PSHUF node.
19767 ///
19768 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19769 /// PSHUF-style masks that can be reused with such instructions.
19770 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19771   MVT VT = N.getSimpleValueType();
19772   SmallVector<int, 4> Mask;
19773   bool IsUnary;
19774   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
19775   (void)HaveMask;
19776   assert(HaveMask);
19777
19778   // If we have more than 128-bits, only the low 128-bits of shuffle mask
19779   // matter. Check that the upper masks are repeats and remove them.
19780   if (VT.getSizeInBits() > 128) {
19781     int LaneElts = 128 / VT.getScalarSizeInBits();
19782 #ifndef NDEBUG
19783     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
19784       for (int j = 0; j < LaneElts; ++j)
19785         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
19786                "Mask doesn't repeat in high 128-bit lanes!");
19787 #endif
19788     Mask.resize(LaneElts);
19789   }
19790
19791   switch (N.getOpcode()) {
19792   case X86ISD::PSHUFD:
19793     return Mask;
19794   case X86ISD::PSHUFLW:
19795     Mask.resize(4);
19796     return Mask;
19797   case X86ISD::PSHUFHW:
19798     Mask.erase(Mask.begin(), Mask.begin() + 4);
19799     for (int &M : Mask)
19800       M -= 4;
19801     return Mask;
19802   default:
19803     llvm_unreachable("No valid shuffle instruction found!");
19804   }
19805 }
19806
19807 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19808 ///
19809 /// We walk up the chain and look for a combinable shuffle, skipping over
19810 /// shuffles that we could hoist this shuffle's transformation past without
19811 /// altering anything.
19812 static SDValue
19813 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19814                              SelectionDAG &DAG,
19815                              TargetLowering::DAGCombinerInfo &DCI) {
19816   assert(N.getOpcode() == X86ISD::PSHUFD &&
19817          "Called with something other than an x86 128-bit half shuffle!");
19818   SDLoc DL(N);
19819
19820   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19821   // of the shuffles in the chain so that we can form a fresh chain to replace
19822   // this one.
19823   SmallVector<SDValue, 8> Chain;
19824   SDValue V = N.getOperand(0);
19825   for (; V.hasOneUse(); V = V.getOperand(0)) {
19826     switch (V.getOpcode()) {
19827     default:
19828       return SDValue(); // Nothing combined!
19829
19830     case ISD::BITCAST:
19831       // Skip bitcasts as we always know the type for the target specific
19832       // instructions.
19833       continue;
19834
19835     case X86ISD::PSHUFD:
19836       // Found another dword shuffle.
19837       break;
19838
19839     case X86ISD::PSHUFLW:
19840       // Check that the low words (being shuffled) are the identity in the
19841       // dword shuffle, and the high words are self-contained.
19842       if (Mask[0] != 0 || Mask[1] != 1 ||
19843           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19844         return SDValue();
19845
19846       Chain.push_back(V);
19847       continue;
19848
19849     case X86ISD::PSHUFHW:
19850       // Check that the high words (being shuffled) are the identity in the
19851       // dword shuffle, and the low words are self-contained.
19852       if (Mask[2] != 2 || Mask[3] != 3 ||
19853           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19854         return SDValue();
19855
19856       Chain.push_back(V);
19857       continue;
19858
19859     case X86ISD::UNPCKL:
19860     case X86ISD::UNPCKH:
19861       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19862       // shuffle into a preceding word shuffle.
19863       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
19864           V.getSimpleValueType().getScalarType() != MVT::i16)
19865         return SDValue();
19866
19867       // Search for a half-shuffle which we can combine with.
19868       unsigned CombineOp =
19869           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19870       if (V.getOperand(0) != V.getOperand(1) ||
19871           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19872         return SDValue();
19873       Chain.push_back(V);
19874       V = V.getOperand(0);
19875       do {
19876         switch (V.getOpcode()) {
19877         default:
19878           return SDValue(); // Nothing to combine.
19879
19880         case X86ISD::PSHUFLW:
19881         case X86ISD::PSHUFHW:
19882           if (V.getOpcode() == CombineOp)
19883             break;
19884
19885           Chain.push_back(V);
19886
19887           // Fallthrough!
19888         case ISD::BITCAST:
19889           V = V.getOperand(0);
19890           continue;
19891         }
19892         break;
19893       } while (V.hasOneUse());
19894       break;
19895     }
19896     // Break out of the loop if we break out of the switch.
19897     break;
19898   }
19899
19900   if (!V.hasOneUse())
19901     // We fell out of the loop without finding a viable combining instruction.
19902     return SDValue();
19903
19904   // Merge this node's mask and our incoming mask.
19905   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19906   for (int &M : Mask)
19907     M = VMask[M];
19908   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19909                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19910
19911   // Rebuild the chain around this new shuffle.
19912   while (!Chain.empty()) {
19913     SDValue W = Chain.pop_back_val();
19914
19915     if (V.getValueType() != W.getOperand(0).getValueType())
19916       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19917
19918     switch (W.getOpcode()) {
19919     default:
19920       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19921
19922     case X86ISD::UNPCKL:
19923     case X86ISD::UNPCKH:
19924       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19925       break;
19926
19927     case X86ISD::PSHUFD:
19928     case X86ISD::PSHUFLW:
19929     case X86ISD::PSHUFHW:
19930       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19931       break;
19932     }
19933   }
19934   if (V.getValueType() != N.getValueType())
19935     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19936
19937   // Return the new chain to replace N.
19938   return V;
19939 }
19940
19941 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19942 ///
19943 /// We walk up the chain, skipping shuffles of the other half and looking
19944 /// through shuffles which switch halves trying to find a shuffle of the same
19945 /// pair of dwords.
19946 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19947                                         SelectionDAG &DAG,
19948                                         TargetLowering::DAGCombinerInfo &DCI) {
19949   assert(
19950       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19951       "Called with something other than an x86 128-bit half shuffle!");
19952   SDLoc DL(N);
19953   unsigned CombineOpcode = N.getOpcode();
19954
19955   // Walk up a single-use chain looking for a combinable shuffle.
19956   SDValue V = N.getOperand(0);
19957   for (; V.hasOneUse(); V = V.getOperand(0)) {
19958     switch (V.getOpcode()) {
19959     default:
19960       return false; // Nothing combined!
19961
19962     case ISD::BITCAST:
19963       // Skip bitcasts as we always know the type for the target specific
19964       // instructions.
19965       continue;
19966
19967     case X86ISD::PSHUFLW:
19968     case X86ISD::PSHUFHW:
19969       if (V.getOpcode() == CombineOpcode)
19970         break;
19971
19972       // Other-half shuffles are no-ops.
19973       continue;
19974     }
19975     // Break out of the loop if we break out of the switch.
19976     break;
19977   }
19978
19979   if (!V.hasOneUse())
19980     // We fell out of the loop without finding a viable combining instruction.
19981     return false;
19982
19983   // Combine away the bottom node as its shuffle will be accumulated into
19984   // a preceding shuffle.
19985   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19986
19987   // Record the old value.
19988   SDValue Old = V;
19989
19990   // Merge this node's mask and our incoming mask (adjusted to account for all
19991   // the pshufd instructions encountered).
19992   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19993   for (int &M : Mask)
19994     M = VMask[M];
19995   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19996                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19997
19998   // Check that the shuffles didn't cancel each other out. If not, we need to
19999   // combine to the new one.
20000   if (Old != V)
20001     // Replace the combinable shuffle with the combined one, updating all users
20002     // so that we re-evaluate the chain here.
20003     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20004
20005   return true;
20006 }
20007
20008 /// \brief Try to combine x86 target specific shuffles.
20009 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20010                                            TargetLowering::DAGCombinerInfo &DCI,
20011                                            const X86Subtarget *Subtarget) {
20012   SDLoc DL(N);
20013   MVT VT = N.getSimpleValueType();
20014   SmallVector<int, 4> Mask;
20015
20016   switch (N.getOpcode()) {
20017   case X86ISD::PSHUFD:
20018   case X86ISD::PSHUFLW:
20019   case X86ISD::PSHUFHW:
20020     Mask = getPSHUFShuffleMask(N);
20021     assert(Mask.size() == 4);
20022     break;
20023   default:
20024     return SDValue();
20025   }
20026
20027   // Nuke no-op shuffles that show up after combining.
20028   if (isNoopShuffleMask(Mask))
20029     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20030
20031   // Look for simplifications involving one or two shuffle instructions.
20032   SDValue V = N.getOperand(0);
20033   switch (N.getOpcode()) {
20034   default:
20035     break;
20036   case X86ISD::PSHUFLW:
20037   case X86ISD::PSHUFHW:
20038     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20039
20040     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20041       return SDValue(); // We combined away this shuffle, so we're done.
20042
20043     // See if this reduces to a PSHUFD which is no more expensive and can
20044     // combine with more operations. Note that it has to at least flip the
20045     // dwords as otherwise it would have been removed as a no-op.
20046     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20047       int DMask[] = {0, 1, 2, 3};
20048       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20049       DMask[DOffset + 0] = DOffset + 1;
20050       DMask[DOffset + 1] = DOffset + 0;
20051       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20052       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20053       DCI.AddToWorklist(V.getNode());
20054       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20055                       getV4X86ShuffleImm8ForMask(DMask, DAG));
20056       DCI.AddToWorklist(V.getNode());
20057       return DAG.getNode(ISD::BITCAST, DL, VT, V);
20058     }
20059
20060     // Look for shuffle patterns which can be implemented as a single unpack.
20061     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20062     // only works when we have a PSHUFD followed by two half-shuffles.
20063     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20064         (V.getOpcode() == X86ISD::PSHUFLW ||
20065          V.getOpcode() == X86ISD::PSHUFHW) &&
20066         V.getOpcode() != N.getOpcode() &&
20067         V.hasOneUse()) {
20068       SDValue D = V.getOperand(0);
20069       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20070         D = D.getOperand(0);
20071       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20072         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20073         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20074         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20075         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20076         int WordMask[8];
20077         for (int i = 0; i < 4; ++i) {
20078           WordMask[i + NOffset] = Mask[i] + NOffset;
20079           WordMask[i + VOffset] = VMask[i] + VOffset;
20080         }
20081         // Map the word mask through the DWord mask.
20082         int MappedMask[8];
20083         for (int i = 0; i < 8; ++i)
20084           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20085         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20086             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20087           // We can replace all three shuffles with an unpack.
20088           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20089           DCI.AddToWorklist(V.getNode());
20090           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20091                                                 : X86ISD::UNPCKH,
20092                              DL, VT, V, V);
20093         }
20094       }
20095     }
20096
20097     break;
20098
20099   case X86ISD::PSHUFD:
20100     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20101       return NewN;
20102
20103     break;
20104   }
20105
20106   return SDValue();
20107 }
20108
20109 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20110 ///
20111 /// We combine this directly on the abstract vector shuffle nodes so it is
20112 /// easier to generically match. We also insert dummy vector shuffle nodes for
20113 /// the operands which explicitly discard the lanes which are unused by this
20114 /// operation to try to flow through the rest of the combiner the fact that
20115 /// they're unused.
20116 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20117   SDLoc DL(N);
20118   EVT VT = N->getValueType(0);
20119
20120   // We only handle target-independent shuffles.
20121   // FIXME: It would be easy and harmless to use the target shuffle mask
20122   // extraction tool to support more.
20123   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20124     return SDValue();
20125
20126   auto *SVN = cast<ShuffleVectorSDNode>(N);
20127   ArrayRef<int> Mask = SVN->getMask();
20128   SDValue V1 = N->getOperand(0);
20129   SDValue V2 = N->getOperand(1);
20130
20131   // We require the first shuffle operand to be the SUB node, and the second to
20132   // be the ADD node.
20133   // FIXME: We should support the commuted patterns.
20134   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20135     return SDValue();
20136
20137   // If there are other uses of these operations we can't fold them.
20138   if (!V1->hasOneUse() || !V2->hasOneUse())
20139     return SDValue();
20140
20141   // Ensure that both operations have the same operands. Note that we can
20142   // commute the FADD operands.
20143   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20144   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20145       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20146     return SDValue();
20147
20148   // We're looking for blends between FADD and FSUB nodes. We insist on these
20149   // nodes being lined up in a specific expected pattern.
20150   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20151         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20152         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20153     return SDValue();
20154
20155   // Only specific types are legal at this point, assert so we notice if and
20156   // when these change.
20157   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20158           VT == MVT::v4f64) &&
20159          "Unknown vector type encountered!");
20160
20161   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20162 }
20163
20164 /// PerformShuffleCombine - Performs several different shuffle combines.
20165 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20166                                      TargetLowering::DAGCombinerInfo &DCI,
20167                                      const X86Subtarget *Subtarget) {
20168   SDLoc dl(N);
20169   SDValue N0 = N->getOperand(0);
20170   SDValue N1 = N->getOperand(1);
20171   EVT VT = N->getValueType(0);
20172
20173   // Don't create instructions with illegal types after legalize types has run.
20174   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20175   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20176     return SDValue();
20177
20178   // If we have legalized the vector types, look for blends of FADD and FSUB
20179   // nodes that we can fuse into an ADDSUB node.
20180   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20181     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20182       return AddSub;
20183
20184   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20185   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20186       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20187     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20188
20189   // During Type Legalization, when promoting illegal vector types,
20190   // the backend might introduce new shuffle dag nodes and bitcasts.
20191   //
20192   // This code performs the following transformation:
20193   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20194   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20195   //
20196   // We do this only if both the bitcast and the BINOP dag nodes have
20197   // one use. Also, perform this transformation only if the new binary
20198   // operation is legal. This is to avoid introducing dag nodes that
20199   // potentially need to be further expanded (or custom lowered) into a
20200   // less optimal sequence of dag nodes.
20201   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20202       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20203       N0.getOpcode() == ISD::BITCAST) {
20204     SDValue BC0 = N0.getOperand(0);
20205     EVT SVT = BC0.getValueType();
20206     unsigned Opcode = BC0.getOpcode();
20207     unsigned NumElts = VT.getVectorNumElements();
20208
20209     if (BC0.hasOneUse() && SVT.isVector() &&
20210         SVT.getVectorNumElements() * 2 == NumElts &&
20211         TLI.isOperationLegal(Opcode, VT)) {
20212       bool CanFold = false;
20213       switch (Opcode) {
20214       default : break;
20215       case ISD::ADD :
20216       case ISD::FADD :
20217       case ISD::SUB :
20218       case ISD::FSUB :
20219       case ISD::MUL :
20220       case ISD::FMUL :
20221         CanFold = true;
20222       }
20223
20224       unsigned SVTNumElts = SVT.getVectorNumElements();
20225       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20226       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20227         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20228       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20229         CanFold = SVOp->getMaskElt(i) < 0;
20230
20231       if (CanFold) {
20232         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20233         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20234         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20235         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20236       }
20237     }
20238   }
20239
20240   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20241   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20242   // consecutive, non-overlapping, and in the right order.
20243   SmallVector<SDValue, 16> Elts;
20244   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20245     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20246
20247   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20248   if (LD.getNode())
20249     return LD;
20250
20251   if (isTargetShuffle(N->getOpcode())) {
20252     SDValue Shuffle =
20253         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20254     if (Shuffle.getNode())
20255       return Shuffle;
20256
20257     // Try recursively combining arbitrary sequences of x86 shuffle
20258     // instructions into higher-order shuffles. We do this after combining
20259     // specific PSHUF instruction sequences into their minimal form so that we
20260     // can evaluate how many specialized shuffle instructions are involved in
20261     // a particular chain.
20262     SmallVector<int, 1> NonceMask; // Just a placeholder.
20263     NonceMask.push_back(0);
20264     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20265                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20266                                       DCI, Subtarget))
20267       return SDValue(); // This routine will use CombineTo to replace N.
20268   }
20269
20270   return SDValue();
20271 }
20272
20273 /// PerformTruncateCombine - Converts truncate operation to
20274 /// a sequence of vector shuffle operations.
20275 /// It is possible when we truncate 256-bit vector to 128-bit vector
20276 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20277                                       TargetLowering::DAGCombinerInfo &DCI,
20278                                       const X86Subtarget *Subtarget)  {
20279   return SDValue();
20280 }
20281
20282 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20283 /// specific shuffle of a load can be folded into a single element load.
20284 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20285 /// shuffles have been custom lowered so we need to handle those here.
20286 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20287                                          TargetLowering::DAGCombinerInfo &DCI) {
20288   if (DCI.isBeforeLegalizeOps())
20289     return SDValue();
20290
20291   SDValue InVec = N->getOperand(0);
20292   SDValue EltNo = N->getOperand(1);
20293
20294   if (!isa<ConstantSDNode>(EltNo))
20295     return SDValue();
20296
20297   EVT OriginalVT = InVec.getValueType();
20298
20299   if (InVec.getOpcode() == ISD::BITCAST) {
20300     // Don't duplicate a load with other uses.
20301     if (!InVec.hasOneUse())
20302       return SDValue();
20303     EVT BCVT = InVec.getOperand(0).getValueType();
20304     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20305       return SDValue();
20306     InVec = InVec.getOperand(0);
20307   }
20308
20309   EVT CurrentVT = InVec.getValueType();
20310
20311   if (!isTargetShuffle(InVec.getOpcode()))
20312     return SDValue();
20313
20314   // Don't duplicate a load with other uses.
20315   if (!InVec.hasOneUse())
20316     return SDValue();
20317
20318   SmallVector<int, 16> ShuffleMask;
20319   bool UnaryShuffle;
20320   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20321                             ShuffleMask, UnaryShuffle))
20322     return SDValue();
20323
20324   // Select the input vector, guarding against out of range extract vector.
20325   unsigned NumElems = CurrentVT.getVectorNumElements();
20326   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20327   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20328   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20329                                          : InVec.getOperand(1);
20330
20331   // If inputs to shuffle are the same for both ops, then allow 2 uses
20332   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20333                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20334
20335   if (LdNode.getOpcode() == ISD::BITCAST) {
20336     // Don't duplicate a load with other uses.
20337     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20338       return SDValue();
20339
20340     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20341     LdNode = LdNode.getOperand(0);
20342   }
20343
20344   if (!ISD::isNormalLoad(LdNode.getNode()))
20345     return SDValue();
20346
20347   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20348
20349   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20350     return SDValue();
20351
20352   EVT EltVT = N->getValueType(0);
20353   // If there's a bitcast before the shuffle, check if the load type and
20354   // alignment is valid.
20355   unsigned Align = LN0->getAlignment();
20356   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20357   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20358       EltVT.getTypeForEVT(*DAG.getContext()));
20359
20360   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20361     return SDValue();
20362
20363   // All checks match so transform back to vector_shuffle so that DAG combiner
20364   // can finish the job
20365   SDLoc dl(N);
20366
20367   // Create shuffle node taking into account the case that its a unary shuffle
20368   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20369                                    : InVec.getOperand(1);
20370   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20371                                  InVec.getOperand(0), Shuffle,
20372                                  &ShuffleMask[0]);
20373   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20374   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20375                      EltNo);
20376 }
20377
20378 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20379 /// special and don't usually play with other vector types, it's better to
20380 /// handle them early to be sure we emit efficient code by avoiding
20381 /// store-load conversions.
20382 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20383   if (N->getValueType(0) != MVT::x86mmx ||
20384       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20385       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20386     return SDValue();
20387
20388   SDValue V = N->getOperand(0);
20389   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20390   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20391     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20392                        N->getValueType(0), V.getOperand(0));
20393
20394   return SDValue();
20395 }
20396
20397 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20398 /// generation and convert it from being a bunch of shuffles and extracts
20399 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20400 /// storing the value and loading scalars back, while for x64 we should
20401 /// use 64-bit extracts and shifts.
20402 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20403                                          TargetLowering::DAGCombinerInfo &DCI) {
20404   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20405   if (NewOp.getNode())
20406     return NewOp;
20407
20408   SDValue InputVector = N->getOperand(0);
20409
20410   // Detect mmx to i32 conversion through a v2i32 elt extract.
20411   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20412       N->getValueType(0) == MVT::i32 &&
20413       InputVector.getValueType() == MVT::v2i32) {
20414
20415     // The bitcast source is a direct mmx result.
20416     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20417     if (MMXSrc.getValueType() == MVT::x86mmx)
20418       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20419                          N->getValueType(0),
20420                          InputVector.getNode()->getOperand(0));
20421
20422     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20423     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20424     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20425         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20426         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20427         MMXSrcOp.getValueType() == MVT::v1i64 &&
20428         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20429       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20430                          N->getValueType(0),
20431                          MMXSrcOp.getOperand(0));
20432   }
20433
20434   // Only operate on vectors of 4 elements, where the alternative shuffling
20435   // gets to be more expensive.
20436   if (InputVector.getValueType() != MVT::v4i32)
20437     return SDValue();
20438
20439   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20440   // single use which is a sign-extend or zero-extend, and all elements are
20441   // used.
20442   SmallVector<SDNode *, 4> Uses;
20443   unsigned ExtractedElements = 0;
20444   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20445        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20446     if (UI.getUse().getResNo() != InputVector.getResNo())
20447       return SDValue();
20448
20449     SDNode *Extract = *UI;
20450     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20451       return SDValue();
20452
20453     if (Extract->getValueType(0) != MVT::i32)
20454       return SDValue();
20455     if (!Extract->hasOneUse())
20456       return SDValue();
20457     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20458         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20459       return SDValue();
20460     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20461       return SDValue();
20462
20463     // Record which element was extracted.
20464     ExtractedElements |=
20465       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20466
20467     Uses.push_back(Extract);
20468   }
20469
20470   // If not all the elements were used, this may not be worthwhile.
20471   if (ExtractedElements != 15)
20472     return SDValue();
20473
20474   // Ok, we've now decided to do the transformation.
20475   // If 64-bit shifts are legal, use the extract-shift sequence,
20476   // otherwise bounce the vector off the cache.
20477   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20478   SDValue Vals[4];
20479   SDLoc dl(InputVector);
20480
20481   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20482     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20483     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20484     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20485       DAG.getConstant(0, VecIdxTy));
20486     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20487       DAG.getConstant(1, VecIdxTy));
20488
20489     SDValue ShAmt = DAG.getConstant(32,
20490       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20491     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20492     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20493       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20494     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20495     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20496       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20497   } else {
20498     // Store the value to a temporary stack slot.
20499     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20500     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20501       MachinePointerInfo(), false, false, 0);
20502
20503     EVT ElementType = InputVector.getValueType().getVectorElementType();
20504     unsigned EltSize = ElementType.getSizeInBits() / 8;
20505
20506     // Replace each use (extract) with a load of the appropriate element.
20507     for (unsigned i = 0; i < 4; ++i) {
20508       uint64_t Offset = EltSize * i;
20509       SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20510
20511       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20512                                        StackPtr, OffsetVal);
20513
20514       // Load the scalar.
20515       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20516                             ScalarAddr, MachinePointerInfo(),
20517                             false, false, false, 0);
20518
20519     }
20520   }
20521
20522   // Replace the extracts
20523   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20524     UE = Uses.end(); UI != UE; ++UI) {
20525     SDNode *Extract = *UI;
20526
20527     SDValue Idx = Extract->getOperand(1);
20528     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20529     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20530   }
20531
20532   // The replacement was made in place; don't return anything.
20533   return SDValue();
20534 }
20535
20536 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20537 static std::pair<unsigned, bool>
20538 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20539                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20540   if (!VT.isVector())
20541     return std::make_pair(0, false);
20542
20543   bool NeedSplit = false;
20544   switch (VT.getSimpleVT().SimpleTy) {
20545   default: return std::make_pair(0, false);
20546   case MVT::v4i64:
20547   case MVT::v2i64:
20548     if (!Subtarget->hasVLX())
20549       return std::make_pair(0, false);
20550     break;
20551   case MVT::v64i8:
20552   case MVT::v32i16:
20553     if (!Subtarget->hasBWI())
20554       return std::make_pair(0, false);
20555     break;
20556   case MVT::v16i32:
20557   case MVT::v8i64:
20558     if (!Subtarget->hasAVX512())
20559       return std::make_pair(0, false);
20560     break;
20561   case MVT::v32i8:
20562   case MVT::v16i16:
20563   case MVT::v8i32:
20564     if (!Subtarget->hasAVX2())
20565       NeedSplit = true;
20566     if (!Subtarget->hasAVX())
20567       return std::make_pair(0, false);
20568     break;
20569   case MVT::v16i8:
20570   case MVT::v8i16:
20571   case MVT::v4i32:
20572     if (!Subtarget->hasSSE2())
20573       return std::make_pair(0, false);
20574   }
20575
20576   // SSE2 has only a small subset of the operations.
20577   bool hasUnsigned = Subtarget->hasSSE41() ||
20578                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
20579   bool hasSigned = Subtarget->hasSSE41() ||
20580                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
20581
20582   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20583
20584   unsigned Opc = 0;
20585   // Check for x CC y ? x : y.
20586   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20587       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20588     switch (CC) {
20589     default: break;
20590     case ISD::SETULT:
20591     case ISD::SETULE:
20592       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20593     case ISD::SETUGT:
20594     case ISD::SETUGE:
20595       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20596     case ISD::SETLT:
20597     case ISD::SETLE:
20598       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20599     case ISD::SETGT:
20600     case ISD::SETGE:
20601       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20602     }
20603   // Check for x CC y ? y : x -- a min/max with reversed arms.
20604   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20605              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20606     switch (CC) {
20607     default: break;
20608     case ISD::SETULT:
20609     case ISD::SETULE:
20610       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20611     case ISD::SETUGT:
20612     case ISD::SETUGE:
20613       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20614     case ISD::SETLT:
20615     case ISD::SETLE:
20616       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20617     case ISD::SETGT:
20618     case ISD::SETGE:
20619       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20620     }
20621   }
20622
20623   return std::make_pair(Opc, NeedSplit);
20624 }
20625
20626 static SDValue
20627 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20628                                       const X86Subtarget *Subtarget) {
20629   SDLoc dl(N);
20630   SDValue Cond = N->getOperand(0);
20631   SDValue LHS = N->getOperand(1);
20632   SDValue RHS = N->getOperand(2);
20633
20634   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20635     SDValue CondSrc = Cond->getOperand(0);
20636     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20637       Cond = CondSrc->getOperand(0);
20638   }
20639
20640   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20641     return SDValue();
20642
20643   // A vselect where all conditions and data are constants can be optimized into
20644   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20645   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20646       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20647     return SDValue();
20648
20649   unsigned MaskValue = 0;
20650   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20651     return SDValue();
20652
20653   MVT VT = N->getSimpleValueType(0);
20654   unsigned NumElems = VT.getVectorNumElements();
20655   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20656   for (unsigned i = 0; i < NumElems; ++i) {
20657     // Be sure we emit undef where we can.
20658     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20659       ShuffleMask[i] = -1;
20660     else
20661       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20662   }
20663
20664   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20665   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
20666     return SDValue();
20667   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20668 }
20669
20670 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20671 /// nodes.
20672 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20673                                     TargetLowering::DAGCombinerInfo &DCI,
20674                                     const X86Subtarget *Subtarget) {
20675   SDLoc DL(N);
20676   SDValue Cond = N->getOperand(0);
20677   // Get the LHS/RHS of the select.
20678   SDValue LHS = N->getOperand(1);
20679   SDValue RHS = N->getOperand(2);
20680   EVT VT = LHS.getValueType();
20681   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20682
20683   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20684   // instructions match the semantics of the common C idiom x<y?x:y but not
20685   // x<=y?x:y, because of how they handle negative zero (which can be
20686   // ignored in unsafe-math mode).
20687   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
20688   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20689       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
20690       (Subtarget->hasSSE2() ||
20691        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20692     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20693
20694     unsigned Opcode = 0;
20695     // Check for x CC y ? x : y.
20696     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20697         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20698       switch (CC) {
20699       default: break;
20700       case ISD::SETULT:
20701         // Converting this to a min would handle NaNs incorrectly, and swapping
20702         // the operands would cause it to handle comparisons between positive
20703         // and negative zero incorrectly.
20704         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20705           if (!DAG.getTarget().Options.UnsafeFPMath &&
20706               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20707             break;
20708           std::swap(LHS, RHS);
20709         }
20710         Opcode = X86ISD::FMIN;
20711         break;
20712       case ISD::SETOLE:
20713         // Converting this to a min would handle comparisons between positive
20714         // and negative zero incorrectly.
20715         if (!DAG.getTarget().Options.UnsafeFPMath &&
20716             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20717           break;
20718         Opcode = X86ISD::FMIN;
20719         break;
20720       case ISD::SETULE:
20721         // Converting this to a min would handle both negative zeros and NaNs
20722         // incorrectly, but we can swap the operands to fix both.
20723         std::swap(LHS, RHS);
20724       case ISD::SETOLT:
20725       case ISD::SETLT:
20726       case ISD::SETLE:
20727         Opcode = X86ISD::FMIN;
20728         break;
20729
20730       case ISD::SETOGE:
20731         // Converting this to a max would handle comparisons between positive
20732         // and negative zero incorrectly.
20733         if (!DAG.getTarget().Options.UnsafeFPMath &&
20734             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20735           break;
20736         Opcode = X86ISD::FMAX;
20737         break;
20738       case ISD::SETUGT:
20739         // Converting this to a max would handle NaNs incorrectly, and swapping
20740         // the operands would cause it to handle comparisons between positive
20741         // and negative zero incorrectly.
20742         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20743           if (!DAG.getTarget().Options.UnsafeFPMath &&
20744               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20745             break;
20746           std::swap(LHS, RHS);
20747         }
20748         Opcode = X86ISD::FMAX;
20749         break;
20750       case ISD::SETUGE:
20751         // Converting this to a max would handle both negative zeros and NaNs
20752         // incorrectly, but we can swap the operands to fix both.
20753         std::swap(LHS, RHS);
20754       case ISD::SETOGT:
20755       case ISD::SETGT:
20756       case ISD::SETGE:
20757         Opcode = X86ISD::FMAX;
20758         break;
20759       }
20760     // Check for x CC y ? y : x -- a min/max with reversed arms.
20761     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20762                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20763       switch (CC) {
20764       default: break;
20765       case ISD::SETOGE:
20766         // Converting this to a min would handle comparisons between positive
20767         // and negative zero incorrectly, and swapping the operands would
20768         // cause it to handle NaNs incorrectly.
20769         if (!DAG.getTarget().Options.UnsafeFPMath &&
20770             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20771           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20772             break;
20773           std::swap(LHS, RHS);
20774         }
20775         Opcode = X86ISD::FMIN;
20776         break;
20777       case ISD::SETUGT:
20778         // Converting this to a min would handle NaNs incorrectly.
20779         if (!DAG.getTarget().Options.UnsafeFPMath &&
20780             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20781           break;
20782         Opcode = X86ISD::FMIN;
20783         break;
20784       case ISD::SETUGE:
20785         // Converting this to a min would handle both negative zeros and NaNs
20786         // incorrectly, but we can swap the operands to fix both.
20787         std::swap(LHS, RHS);
20788       case ISD::SETOGT:
20789       case ISD::SETGT:
20790       case ISD::SETGE:
20791         Opcode = X86ISD::FMIN;
20792         break;
20793
20794       case ISD::SETULT:
20795         // Converting this to a max would handle NaNs incorrectly.
20796         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20797           break;
20798         Opcode = X86ISD::FMAX;
20799         break;
20800       case ISD::SETOLE:
20801         // Converting this to a max would handle comparisons between positive
20802         // and negative zero incorrectly, and swapping the operands would
20803         // cause it to handle NaNs incorrectly.
20804         if (!DAG.getTarget().Options.UnsafeFPMath &&
20805             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20806           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20807             break;
20808           std::swap(LHS, RHS);
20809         }
20810         Opcode = X86ISD::FMAX;
20811         break;
20812       case ISD::SETULE:
20813         // Converting this to a max would handle both negative zeros and NaNs
20814         // incorrectly, but we can swap the operands to fix both.
20815         std::swap(LHS, RHS);
20816       case ISD::SETOLT:
20817       case ISD::SETLT:
20818       case ISD::SETLE:
20819         Opcode = X86ISD::FMAX;
20820         break;
20821       }
20822     }
20823
20824     if (Opcode)
20825       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20826   }
20827
20828   EVT CondVT = Cond.getValueType();
20829   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20830       CondVT.getVectorElementType() == MVT::i1) {
20831     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20832     // lowering on KNL. In this case we convert it to
20833     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20834     // The same situation for all 128 and 256-bit vectors of i8 and i16.
20835     // Since SKX these selects have a proper lowering.
20836     EVT OpVT = LHS.getValueType();
20837     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20838         (OpVT.getVectorElementType() == MVT::i8 ||
20839          OpVT.getVectorElementType() == MVT::i16) &&
20840         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
20841       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20842       DCI.AddToWorklist(Cond.getNode());
20843       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20844     }
20845   }
20846   // If this is a select between two integer constants, try to do some
20847   // optimizations.
20848   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20849     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20850       // Don't do this for crazy integer types.
20851       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20852         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20853         // so that TrueC (the true value) is larger than FalseC.
20854         bool NeedsCondInvert = false;
20855
20856         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20857             // Efficiently invertible.
20858             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20859              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20860               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20861           NeedsCondInvert = true;
20862           std::swap(TrueC, FalseC);
20863         }
20864
20865         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20866         if (FalseC->getAPIntValue() == 0 &&
20867             TrueC->getAPIntValue().isPowerOf2()) {
20868           if (NeedsCondInvert) // Invert the condition if needed.
20869             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20870                                DAG.getConstant(1, Cond.getValueType()));
20871
20872           // Zero extend the condition if needed.
20873           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20874
20875           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20876           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20877                              DAG.getConstant(ShAmt, MVT::i8));
20878         }
20879
20880         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20881         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20882           if (NeedsCondInvert) // Invert the condition if needed.
20883             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20884                                DAG.getConstant(1, Cond.getValueType()));
20885
20886           // Zero extend the condition if needed.
20887           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20888                              FalseC->getValueType(0), Cond);
20889           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20890                              SDValue(FalseC, 0));
20891         }
20892
20893         // Optimize cases that will turn into an LEA instruction.  This requires
20894         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20895         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20896           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20897           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20898
20899           bool isFastMultiplier = false;
20900           if (Diff < 10) {
20901             switch ((unsigned char)Diff) {
20902               default: break;
20903               case 1:  // result = add base, cond
20904               case 2:  // result = lea base(    , cond*2)
20905               case 3:  // result = lea base(cond, cond*2)
20906               case 4:  // result = lea base(    , cond*4)
20907               case 5:  // result = lea base(cond, cond*4)
20908               case 8:  // result = lea base(    , cond*8)
20909               case 9:  // result = lea base(cond, cond*8)
20910                 isFastMultiplier = true;
20911                 break;
20912             }
20913           }
20914
20915           if (isFastMultiplier) {
20916             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20917             if (NeedsCondInvert) // Invert the condition if needed.
20918               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20919                                  DAG.getConstant(1, Cond.getValueType()));
20920
20921             // Zero extend the condition if needed.
20922             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20923                                Cond);
20924             // Scale the condition by the difference.
20925             if (Diff != 1)
20926               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20927                                  DAG.getConstant(Diff, Cond.getValueType()));
20928
20929             // Add the base if non-zero.
20930             if (FalseC->getAPIntValue() != 0)
20931               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20932                                  SDValue(FalseC, 0));
20933             return Cond;
20934           }
20935         }
20936       }
20937   }
20938
20939   // Canonicalize max and min:
20940   // (x > y) ? x : y -> (x >= y) ? x : y
20941   // (x < y) ? x : y -> (x <= y) ? x : y
20942   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20943   // the need for an extra compare
20944   // against zero. e.g.
20945   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20946   // subl   %esi, %edi
20947   // testl  %edi, %edi
20948   // movl   $0, %eax
20949   // cmovgl %edi, %eax
20950   // =>
20951   // xorl   %eax, %eax
20952   // subl   %esi, $edi
20953   // cmovsl %eax, %edi
20954   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20955       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20956       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20957     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20958     switch (CC) {
20959     default: break;
20960     case ISD::SETLT:
20961     case ISD::SETGT: {
20962       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20963       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20964                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20965       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20966     }
20967     }
20968   }
20969
20970   // Early exit check
20971   if (!TLI.isTypeLegal(VT))
20972     return SDValue();
20973
20974   // Match VSELECTs into subs with unsigned saturation.
20975   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20976       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20977       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20978        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20979     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20980
20981     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20982     // left side invert the predicate to simplify logic below.
20983     SDValue Other;
20984     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20985       Other = RHS;
20986       CC = ISD::getSetCCInverse(CC, true);
20987     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20988       Other = LHS;
20989     }
20990
20991     if (Other.getNode() && Other->getNumOperands() == 2 &&
20992         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20993       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20994       SDValue CondRHS = Cond->getOperand(1);
20995
20996       // Look for a general sub with unsigned saturation first.
20997       // x >= y ? x-y : 0 --> subus x, y
20998       // x >  y ? x-y : 0 --> subus x, y
20999       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21000           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21001         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21002
21003       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21004         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21005           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21006             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21007               // If the RHS is a constant we have to reverse the const
21008               // canonicalization.
21009               // x > C-1 ? x+-C : 0 --> subus x, C
21010               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21011                   CondRHSConst->getAPIntValue() ==
21012                       (-OpRHSConst->getAPIntValue() - 1))
21013                 return DAG.getNode(
21014                     X86ISD::SUBUS, DL, VT, OpLHS,
21015                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
21016
21017           // Another special case: If C was a sign bit, the sub has been
21018           // canonicalized into a xor.
21019           // FIXME: Would it be better to use computeKnownBits to determine
21020           //        whether it's safe to decanonicalize the xor?
21021           // x s< 0 ? x^C : 0 --> subus x, C
21022           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21023               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21024               OpRHSConst->getAPIntValue().isSignBit())
21025             // Note that we have to rebuild the RHS constant here to ensure we
21026             // don't rely on particular values of undef lanes.
21027             return DAG.getNode(
21028                 X86ISD::SUBUS, DL, VT, OpLHS,
21029                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
21030         }
21031     }
21032   }
21033
21034   // Try to match a min/max vector operation.
21035   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21036     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21037     unsigned Opc = ret.first;
21038     bool NeedSplit = ret.second;
21039
21040     if (Opc && NeedSplit) {
21041       unsigned NumElems = VT.getVectorNumElements();
21042       // Extract the LHS vectors
21043       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21044       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21045
21046       // Extract the RHS vectors
21047       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21048       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21049
21050       // Create min/max for each subvector
21051       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21052       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21053
21054       // Merge the result
21055       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21056     } else if (Opc)
21057       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21058   }
21059
21060   // Simplify vector selection if condition value type matches vselect
21061   // operand type
21062   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21063     assert(Cond.getValueType().isVector() &&
21064            "vector select expects a vector selector!");
21065
21066     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21067     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21068
21069     // Try invert the condition if true value is not all 1s and false value
21070     // is not all 0s.
21071     if (!TValIsAllOnes && !FValIsAllZeros &&
21072         // Check if the selector will be produced by CMPP*/PCMP*
21073         Cond.getOpcode() == ISD::SETCC &&
21074         // Check if SETCC has already been promoted
21075         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21076       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21077       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21078
21079       if (TValIsAllZeros || FValIsAllOnes) {
21080         SDValue CC = Cond.getOperand(2);
21081         ISD::CondCode NewCC =
21082           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21083                                Cond.getOperand(0).getValueType().isInteger());
21084         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21085         std::swap(LHS, RHS);
21086         TValIsAllOnes = FValIsAllOnes;
21087         FValIsAllZeros = TValIsAllZeros;
21088       }
21089     }
21090
21091     if (TValIsAllOnes || FValIsAllZeros) {
21092       SDValue Ret;
21093
21094       if (TValIsAllOnes && FValIsAllZeros)
21095         Ret = Cond;
21096       else if (TValIsAllOnes)
21097         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21098                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21099       else if (FValIsAllZeros)
21100         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21101                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21102
21103       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21104     }
21105   }
21106
21107   // We should generate an X86ISD::BLENDI from a vselect if its argument
21108   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21109   // constants. This specific pattern gets generated when we split a
21110   // selector for a 512 bit vector in a machine without AVX512 (but with
21111   // 256-bit vectors), during legalization:
21112   //
21113   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21114   //
21115   // Iff we find this pattern and the build_vectors are built from
21116   // constants, we translate the vselect into a shuffle_vector that we
21117   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21118   if ((N->getOpcode() == ISD::VSELECT ||
21119        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21120       !DCI.isBeforeLegalize()) {
21121     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21122     if (Shuffle.getNode())
21123       return Shuffle;
21124   }
21125
21126   // If this is a *dynamic* select (non-constant condition) and we can match
21127   // this node with one of the variable blend instructions, restructure the
21128   // condition so that the blends can use the high bit of each element and use
21129   // SimplifyDemandedBits to simplify the condition operand.
21130   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21131       !DCI.isBeforeLegalize() &&
21132       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21133     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21134
21135     // Don't optimize vector selects that map to mask-registers.
21136     if (BitWidth == 1)
21137       return SDValue();
21138
21139     // We can only handle the cases where VSELECT is directly legal on the
21140     // subtarget. We custom lower VSELECT nodes with constant conditions and
21141     // this makes it hard to see whether a dynamic VSELECT will correctly
21142     // lower, so we both check the operation's status and explicitly handle the
21143     // cases where a *dynamic* blend will fail even though a constant-condition
21144     // blend could be custom lowered.
21145     // FIXME: We should find a better way to handle this class of problems.
21146     // Potentially, we should combine constant-condition vselect nodes
21147     // pre-legalization into shuffles and not mark as many types as custom
21148     // lowered.
21149     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21150       return SDValue();
21151     // FIXME: We don't support i16-element blends currently. We could and
21152     // should support them by making *all* the bits in the condition be set
21153     // rather than just the high bit and using an i8-element blend.
21154     if (VT.getScalarType() == MVT::i16)
21155       return SDValue();
21156     // Dynamic blending was only available from SSE4.1 onward.
21157     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21158       return SDValue();
21159     // Byte blends are only available in AVX2
21160     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21161         !Subtarget->hasAVX2())
21162       return SDValue();
21163
21164     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21165     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21166
21167     APInt KnownZero, KnownOne;
21168     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21169                                           DCI.isBeforeLegalizeOps());
21170     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21171         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21172                                  TLO)) {
21173       // If we changed the computation somewhere in the DAG, this change
21174       // will affect all users of Cond.
21175       // Make sure it is fine and update all the nodes so that we do not
21176       // use the generic VSELECT anymore. Otherwise, we may perform
21177       // wrong optimizations as we messed up with the actual expectation
21178       // for the vector boolean values.
21179       if (Cond != TLO.Old) {
21180         // Check all uses of that condition operand to check whether it will be
21181         // consumed by non-BLEND instructions, which may depend on all bits are
21182         // set properly.
21183         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21184              I != E; ++I)
21185           if (I->getOpcode() != ISD::VSELECT)
21186             // TODO: Add other opcodes eventually lowered into BLEND.
21187             return SDValue();
21188
21189         // Update all the users of the condition, before committing the change,
21190         // so that the VSELECT optimizations that expect the correct vector
21191         // boolean value will not be triggered.
21192         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21193              I != E; ++I)
21194           DAG.ReplaceAllUsesOfValueWith(
21195               SDValue(*I, 0),
21196               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21197                           Cond, I->getOperand(1), I->getOperand(2)));
21198         DCI.CommitTargetLoweringOpt(TLO);
21199         return SDValue();
21200       }
21201       // At this point, only Cond is changed. Change the condition
21202       // just for N to keep the opportunity to optimize all other
21203       // users their own way.
21204       DAG.ReplaceAllUsesOfValueWith(
21205           SDValue(N, 0),
21206           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21207                       TLO.New, N->getOperand(1), N->getOperand(2)));
21208       return SDValue();
21209     }
21210   }
21211
21212   return SDValue();
21213 }
21214
21215 // Check whether a boolean test is testing a boolean value generated by
21216 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21217 // code.
21218 //
21219 // Simplify the following patterns:
21220 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21221 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21222 // to (Op EFLAGS Cond)
21223 //
21224 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21225 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21226 // to (Op EFLAGS !Cond)
21227 //
21228 // where Op could be BRCOND or CMOV.
21229 //
21230 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21231   // Quit if not CMP and SUB with its value result used.
21232   if (Cmp.getOpcode() != X86ISD::CMP &&
21233       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21234       return SDValue();
21235
21236   // Quit if not used as a boolean value.
21237   if (CC != X86::COND_E && CC != X86::COND_NE)
21238     return SDValue();
21239
21240   // Check CMP operands. One of them should be 0 or 1 and the other should be
21241   // an SetCC or extended from it.
21242   SDValue Op1 = Cmp.getOperand(0);
21243   SDValue Op2 = Cmp.getOperand(1);
21244
21245   SDValue SetCC;
21246   const ConstantSDNode* C = nullptr;
21247   bool needOppositeCond = (CC == X86::COND_E);
21248   bool checkAgainstTrue = false; // Is it a comparison against 1?
21249
21250   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21251     SetCC = Op2;
21252   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21253     SetCC = Op1;
21254   else // Quit if all operands are not constants.
21255     return SDValue();
21256
21257   if (C->getZExtValue() == 1) {
21258     needOppositeCond = !needOppositeCond;
21259     checkAgainstTrue = true;
21260   } else if (C->getZExtValue() != 0)
21261     // Quit if the constant is neither 0 or 1.
21262     return SDValue();
21263
21264   bool truncatedToBoolWithAnd = false;
21265   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21266   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21267          SetCC.getOpcode() == ISD::TRUNCATE ||
21268          SetCC.getOpcode() == ISD::AND) {
21269     if (SetCC.getOpcode() == ISD::AND) {
21270       int OpIdx = -1;
21271       ConstantSDNode *CS;
21272       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21273           CS->getZExtValue() == 1)
21274         OpIdx = 1;
21275       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21276           CS->getZExtValue() == 1)
21277         OpIdx = 0;
21278       if (OpIdx == -1)
21279         break;
21280       SetCC = SetCC.getOperand(OpIdx);
21281       truncatedToBoolWithAnd = true;
21282     } else
21283       SetCC = SetCC.getOperand(0);
21284   }
21285
21286   switch (SetCC.getOpcode()) {
21287   case X86ISD::SETCC_CARRY:
21288     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21289     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21290     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21291     // truncated to i1 using 'and'.
21292     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21293       break;
21294     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21295            "Invalid use of SETCC_CARRY!");
21296     // FALL THROUGH
21297   case X86ISD::SETCC:
21298     // Set the condition code or opposite one if necessary.
21299     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21300     if (needOppositeCond)
21301       CC = X86::GetOppositeBranchCondition(CC);
21302     return SetCC.getOperand(1);
21303   case X86ISD::CMOV: {
21304     // Check whether false/true value has canonical one, i.e. 0 or 1.
21305     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21306     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21307     // Quit if true value is not a constant.
21308     if (!TVal)
21309       return SDValue();
21310     // Quit if false value is not a constant.
21311     if (!FVal) {
21312       SDValue Op = SetCC.getOperand(0);
21313       // Skip 'zext' or 'trunc' node.
21314       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21315           Op.getOpcode() == ISD::TRUNCATE)
21316         Op = Op.getOperand(0);
21317       // A special case for rdrand/rdseed, where 0 is set if false cond is
21318       // found.
21319       if ((Op.getOpcode() != X86ISD::RDRAND &&
21320            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21321         return SDValue();
21322     }
21323     // Quit if false value is not the constant 0 or 1.
21324     bool FValIsFalse = true;
21325     if (FVal && FVal->getZExtValue() != 0) {
21326       if (FVal->getZExtValue() != 1)
21327         return SDValue();
21328       // If FVal is 1, opposite cond is needed.
21329       needOppositeCond = !needOppositeCond;
21330       FValIsFalse = false;
21331     }
21332     // Quit if TVal is not the constant opposite of FVal.
21333     if (FValIsFalse && TVal->getZExtValue() != 1)
21334       return SDValue();
21335     if (!FValIsFalse && TVal->getZExtValue() != 0)
21336       return SDValue();
21337     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21338     if (needOppositeCond)
21339       CC = X86::GetOppositeBranchCondition(CC);
21340     return SetCC.getOperand(3);
21341   }
21342   }
21343
21344   return SDValue();
21345 }
21346
21347 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21348 /// Match:
21349 ///   (X86or (X86setcc) (X86setcc))
21350 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21351 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21352                                            X86::CondCode &CC1, SDValue &Flags,
21353                                            bool &isAnd) {
21354   if (Cond->getOpcode() == X86ISD::CMP) {
21355     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21356     if (!CondOp1C || !CondOp1C->isNullValue())
21357       return false;
21358
21359     Cond = Cond->getOperand(0);
21360   }
21361
21362   isAnd = false;
21363
21364   SDValue SetCC0, SetCC1;
21365   switch (Cond->getOpcode()) {
21366   default: return false;
21367   case ISD::AND:
21368   case X86ISD::AND:
21369     isAnd = true;
21370     // fallthru
21371   case ISD::OR:
21372   case X86ISD::OR:
21373     SetCC0 = Cond->getOperand(0);
21374     SetCC1 = Cond->getOperand(1);
21375     break;
21376   };
21377
21378   // Make sure we have SETCC nodes, using the same flags value.
21379   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21380       SetCC1.getOpcode() != X86ISD::SETCC ||
21381       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21382     return false;
21383
21384   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21385   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21386   Flags = SetCC0->getOperand(1);
21387   return true;
21388 }
21389
21390 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21391 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21392                                   TargetLowering::DAGCombinerInfo &DCI,
21393                                   const X86Subtarget *Subtarget) {
21394   SDLoc DL(N);
21395
21396   // If the flag operand isn't dead, don't touch this CMOV.
21397   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21398     return SDValue();
21399
21400   SDValue FalseOp = N->getOperand(0);
21401   SDValue TrueOp = N->getOperand(1);
21402   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21403   SDValue Cond = N->getOperand(3);
21404
21405   if (CC == X86::COND_E || CC == X86::COND_NE) {
21406     switch (Cond.getOpcode()) {
21407     default: break;
21408     case X86ISD::BSR:
21409     case X86ISD::BSF:
21410       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21411       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21412         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21413     }
21414   }
21415
21416   SDValue Flags;
21417
21418   Flags = checkBoolTestSetCCCombine(Cond, CC);
21419   if (Flags.getNode() &&
21420       // Extra check as FCMOV only supports a subset of X86 cond.
21421       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21422     SDValue Ops[] = { FalseOp, TrueOp,
21423                       DAG.getConstant(CC, MVT::i8), Flags };
21424     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21425   }
21426
21427   // If this is a select between two integer constants, try to do some
21428   // optimizations.  Note that the operands are ordered the opposite of SELECT
21429   // operands.
21430   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21431     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21432       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21433       // larger than FalseC (the false value).
21434       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21435         CC = X86::GetOppositeBranchCondition(CC);
21436         std::swap(TrueC, FalseC);
21437         std::swap(TrueOp, FalseOp);
21438       }
21439
21440       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21441       // This is efficient for any integer data type (including i8/i16) and
21442       // shift amount.
21443       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21444         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21445                            DAG.getConstant(CC, MVT::i8), Cond);
21446
21447         // Zero extend the condition if needed.
21448         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21449
21450         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21451         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21452                            DAG.getConstant(ShAmt, MVT::i8));
21453         if (N->getNumValues() == 2)  // Dead flag value?
21454           return DCI.CombineTo(N, Cond, SDValue());
21455         return Cond;
21456       }
21457
21458       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21459       // for any integer data type, including i8/i16.
21460       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21461         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21462                            DAG.getConstant(CC, MVT::i8), Cond);
21463
21464         // Zero extend the condition if needed.
21465         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21466                            FalseC->getValueType(0), Cond);
21467         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21468                            SDValue(FalseC, 0));
21469
21470         if (N->getNumValues() == 2)  // Dead flag value?
21471           return DCI.CombineTo(N, Cond, SDValue());
21472         return Cond;
21473       }
21474
21475       // Optimize cases that will turn into an LEA instruction.  This requires
21476       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21477       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21478         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21479         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21480
21481         bool isFastMultiplier = false;
21482         if (Diff < 10) {
21483           switch ((unsigned char)Diff) {
21484           default: break;
21485           case 1:  // result = add base, cond
21486           case 2:  // result = lea base(    , cond*2)
21487           case 3:  // result = lea base(cond, cond*2)
21488           case 4:  // result = lea base(    , cond*4)
21489           case 5:  // result = lea base(cond, cond*4)
21490           case 8:  // result = lea base(    , cond*8)
21491           case 9:  // result = lea base(cond, cond*8)
21492             isFastMultiplier = true;
21493             break;
21494           }
21495         }
21496
21497         if (isFastMultiplier) {
21498           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21499           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21500                              DAG.getConstant(CC, MVT::i8), Cond);
21501           // Zero extend the condition if needed.
21502           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21503                              Cond);
21504           // Scale the condition by the difference.
21505           if (Diff != 1)
21506             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21507                                DAG.getConstant(Diff, Cond.getValueType()));
21508
21509           // Add the base if non-zero.
21510           if (FalseC->getAPIntValue() != 0)
21511             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21512                                SDValue(FalseC, 0));
21513           if (N->getNumValues() == 2)  // Dead flag value?
21514             return DCI.CombineTo(N, Cond, SDValue());
21515           return Cond;
21516         }
21517       }
21518     }
21519   }
21520
21521   // Handle these cases:
21522   //   (select (x != c), e, c) -> select (x != c), e, x),
21523   //   (select (x == c), c, e) -> select (x == c), x, e)
21524   // where the c is an integer constant, and the "select" is the combination
21525   // of CMOV and CMP.
21526   //
21527   // The rationale for this change is that the conditional-move from a constant
21528   // needs two instructions, however, conditional-move from a register needs
21529   // only one instruction.
21530   //
21531   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21532   //  some instruction-combining opportunities. This opt needs to be
21533   //  postponed as late as possible.
21534   //
21535   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21536     // the DCI.xxxx conditions are provided to postpone the optimization as
21537     // late as possible.
21538
21539     ConstantSDNode *CmpAgainst = nullptr;
21540     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21541         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21542         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21543
21544       if (CC == X86::COND_NE &&
21545           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21546         CC = X86::GetOppositeBranchCondition(CC);
21547         std::swap(TrueOp, FalseOp);
21548       }
21549
21550       if (CC == X86::COND_E &&
21551           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21552         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21553                           DAG.getConstant(CC, MVT::i8), Cond };
21554         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21555       }
21556     }
21557   }
21558
21559   // Fold and/or of setcc's to double CMOV:
21560   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
21561   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
21562   //
21563   // This combine lets us generate:
21564   //   cmovcc1 (jcc1 if we don't have CMOV)
21565   //   cmovcc2 (same)
21566   // instead of:
21567   //   setcc1
21568   //   setcc2
21569   //   and/or
21570   //   cmovne (jne if we don't have CMOV)
21571   // When we can't use the CMOV instruction, it might increase branch
21572   // mispredicts.
21573   // When we can use CMOV, or when there is no mispredict, this improves
21574   // throughput and reduces register pressure.
21575   //
21576   if (CC == X86::COND_NE) {
21577     SDValue Flags;
21578     X86::CondCode CC0, CC1;
21579     bool isAndSetCC;
21580     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
21581       if (isAndSetCC) {
21582         std::swap(FalseOp, TrueOp);
21583         CC0 = X86::GetOppositeBranchCondition(CC0);
21584         CC1 = X86::GetOppositeBranchCondition(CC1);
21585       }
21586
21587       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, MVT::i8),
21588         Flags};
21589       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
21590       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, MVT::i8), Flags};
21591       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21592       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
21593       return CMOV;
21594     }
21595   }
21596
21597   return SDValue();
21598 }
21599
21600 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21601                                                 const X86Subtarget *Subtarget) {
21602   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21603   switch (IntNo) {
21604   default: return SDValue();
21605   // SSE/AVX/AVX2 blend intrinsics.
21606   case Intrinsic::x86_avx2_pblendvb:
21607     // Don't try to simplify this intrinsic if we don't have AVX2.
21608     if (!Subtarget->hasAVX2())
21609       return SDValue();
21610     // FALL-THROUGH
21611   case Intrinsic::x86_avx_blendv_pd_256:
21612   case Intrinsic::x86_avx_blendv_ps_256:
21613     // Don't try to simplify this intrinsic if we don't have AVX.
21614     if (!Subtarget->hasAVX())
21615       return SDValue();
21616     // FALL-THROUGH
21617   case Intrinsic::x86_sse41_blendvps:
21618   case Intrinsic::x86_sse41_blendvpd:
21619   case Intrinsic::x86_sse41_pblendvb: {
21620     SDValue Op0 = N->getOperand(1);
21621     SDValue Op1 = N->getOperand(2);
21622     SDValue Mask = N->getOperand(3);
21623
21624     // Don't try to simplify this intrinsic if we don't have SSE4.1.
21625     if (!Subtarget->hasSSE41())
21626       return SDValue();
21627
21628     // fold (blend A, A, Mask) -> A
21629     if (Op0 == Op1)
21630       return Op0;
21631     // fold (blend A, B, allZeros) -> A
21632     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21633       return Op0;
21634     // fold (blend A, B, allOnes) -> B
21635     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21636       return Op1;
21637
21638     // Simplify the case where the mask is a constant i32 value.
21639     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21640       if (C->isNullValue())
21641         return Op0;
21642       if (C->isAllOnesValue())
21643         return Op1;
21644     }
21645
21646     return SDValue();
21647   }
21648
21649   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21650   case Intrinsic::x86_sse2_psrai_w:
21651   case Intrinsic::x86_sse2_psrai_d:
21652   case Intrinsic::x86_avx2_psrai_w:
21653   case Intrinsic::x86_avx2_psrai_d:
21654   case Intrinsic::x86_sse2_psra_w:
21655   case Intrinsic::x86_sse2_psra_d:
21656   case Intrinsic::x86_avx2_psra_w:
21657   case Intrinsic::x86_avx2_psra_d: {
21658     SDValue Op0 = N->getOperand(1);
21659     SDValue Op1 = N->getOperand(2);
21660     EVT VT = Op0.getValueType();
21661     assert(VT.isVector() && "Expected a vector type!");
21662
21663     if (isa<BuildVectorSDNode>(Op1))
21664       Op1 = Op1.getOperand(0);
21665
21666     if (!isa<ConstantSDNode>(Op1))
21667       return SDValue();
21668
21669     EVT SVT = VT.getVectorElementType();
21670     unsigned SVTBits = SVT.getSizeInBits();
21671
21672     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21673     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21674     uint64_t ShAmt = C.getZExtValue();
21675
21676     // Don't try to convert this shift into a ISD::SRA if the shift
21677     // count is bigger than or equal to the element size.
21678     if (ShAmt >= SVTBits)
21679       return SDValue();
21680
21681     // Trivial case: if the shift count is zero, then fold this
21682     // into the first operand.
21683     if (ShAmt == 0)
21684       return Op0;
21685
21686     // Replace this packed shift intrinsic with a target independent
21687     // shift dag node.
21688     SDValue Splat = DAG.getConstant(C, VT);
21689     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21690   }
21691   }
21692 }
21693
21694 /// PerformMulCombine - Optimize a single multiply with constant into two
21695 /// in order to implement it with two cheaper instructions, e.g.
21696 /// LEA + SHL, LEA + LEA.
21697 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21698                                  TargetLowering::DAGCombinerInfo &DCI) {
21699   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21700     return SDValue();
21701
21702   EVT VT = N->getValueType(0);
21703   if (VT != MVT::i64 && VT != MVT::i32)
21704     return SDValue();
21705
21706   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21707   if (!C)
21708     return SDValue();
21709   uint64_t MulAmt = C->getZExtValue();
21710   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21711     return SDValue();
21712
21713   uint64_t MulAmt1 = 0;
21714   uint64_t MulAmt2 = 0;
21715   if ((MulAmt % 9) == 0) {
21716     MulAmt1 = 9;
21717     MulAmt2 = MulAmt / 9;
21718   } else if ((MulAmt % 5) == 0) {
21719     MulAmt1 = 5;
21720     MulAmt2 = MulAmt / 5;
21721   } else if ((MulAmt % 3) == 0) {
21722     MulAmt1 = 3;
21723     MulAmt2 = MulAmt / 3;
21724   }
21725   if (MulAmt2 &&
21726       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21727     SDLoc DL(N);
21728
21729     if (isPowerOf2_64(MulAmt2) &&
21730         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21731       // If second multiplifer is pow2, issue it first. We want the multiply by
21732       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21733       // is an add.
21734       std::swap(MulAmt1, MulAmt2);
21735
21736     SDValue NewMul;
21737     if (isPowerOf2_64(MulAmt1))
21738       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21739                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21740     else
21741       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21742                            DAG.getConstant(MulAmt1, VT));
21743
21744     if (isPowerOf2_64(MulAmt2))
21745       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21746                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21747     else
21748       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21749                            DAG.getConstant(MulAmt2, VT));
21750
21751     // Do not add new nodes to DAG combiner worklist.
21752     DCI.CombineTo(N, NewMul, false);
21753   }
21754   return SDValue();
21755 }
21756
21757 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21758   SDValue N0 = N->getOperand(0);
21759   SDValue N1 = N->getOperand(1);
21760   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21761   EVT VT = N0.getValueType();
21762
21763   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21764   // since the result of setcc_c is all zero's or all ones.
21765   if (VT.isInteger() && !VT.isVector() &&
21766       N1C && N0.getOpcode() == ISD::AND &&
21767       N0.getOperand(1).getOpcode() == ISD::Constant) {
21768     SDValue N00 = N0.getOperand(0);
21769     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21770         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21771           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21772          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21773       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21774       APInt ShAmt = N1C->getAPIntValue();
21775       Mask = Mask.shl(ShAmt);
21776       if (Mask != 0)
21777         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21778                            N00, DAG.getConstant(Mask, VT));
21779     }
21780   }
21781
21782   // Hardware support for vector shifts is sparse which makes us scalarize the
21783   // vector operations in many cases. Also, on sandybridge ADD is faster than
21784   // shl.
21785   // (shl V, 1) -> add V,V
21786   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21787     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21788       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21789       // We shift all of the values by one. In many cases we do not have
21790       // hardware support for this operation. This is better expressed as an ADD
21791       // of two values.
21792       if (N1SplatC->getZExtValue() == 1)
21793         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21794     }
21795
21796   return SDValue();
21797 }
21798
21799 /// \brief Returns a vector of 0s if the node in input is a vector logical
21800 /// shift by a constant amount which is known to be bigger than or equal
21801 /// to the vector element size in bits.
21802 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21803                                       const X86Subtarget *Subtarget) {
21804   EVT VT = N->getValueType(0);
21805
21806   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21807       (!Subtarget->hasInt256() ||
21808        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21809     return SDValue();
21810
21811   SDValue Amt = N->getOperand(1);
21812   SDLoc DL(N);
21813   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21814     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21815       APInt ShiftAmt = AmtSplat->getAPIntValue();
21816       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21817
21818       // SSE2/AVX2 logical shifts always return a vector of 0s
21819       // if the shift amount is bigger than or equal to
21820       // the element size. The constant shift amount will be
21821       // encoded as a 8-bit immediate.
21822       if (ShiftAmt.trunc(8).uge(MaxAmount))
21823         return getZeroVector(VT, Subtarget, DAG, DL);
21824     }
21825
21826   return SDValue();
21827 }
21828
21829 /// PerformShiftCombine - Combine shifts.
21830 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21831                                    TargetLowering::DAGCombinerInfo &DCI,
21832                                    const X86Subtarget *Subtarget) {
21833   if (N->getOpcode() == ISD::SHL) {
21834     SDValue V = PerformSHLCombine(N, DAG);
21835     if (V.getNode()) return V;
21836   }
21837
21838   if (N->getOpcode() != ISD::SRA) {
21839     // Try to fold this logical shift into a zero vector.
21840     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21841     if (V.getNode()) return V;
21842   }
21843
21844   return SDValue();
21845 }
21846
21847 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
21848 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21849 // and friends.  Likewise for OR -> CMPNEQSS.
21850 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21851                             TargetLowering::DAGCombinerInfo &DCI,
21852                             const X86Subtarget *Subtarget) {
21853   unsigned opcode;
21854
21855   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21856   // we're requiring SSE2 for both.
21857   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21858     SDValue N0 = N->getOperand(0);
21859     SDValue N1 = N->getOperand(1);
21860     SDValue CMP0 = N0->getOperand(1);
21861     SDValue CMP1 = N1->getOperand(1);
21862     SDLoc DL(N);
21863
21864     // The SETCCs should both refer to the same CMP.
21865     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21866       return SDValue();
21867
21868     SDValue CMP00 = CMP0->getOperand(0);
21869     SDValue CMP01 = CMP0->getOperand(1);
21870     EVT     VT    = CMP00.getValueType();
21871
21872     if (VT == MVT::f32 || VT == MVT::f64) {
21873       bool ExpectingFlags = false;
21874       // Check for any users that want flags:
21875       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21876            !ExpectingFlags && UI != UE; ++UI)
21877         switch (UI->getOpcode()) {
21878         default:
21879         case ISD::BR_CC:
21880         case ISD::BRCOND:
21881         case ISD::SELECT:
21882           ExpectingFlags = true;
21883           break;
21884         case ISD::CopyToReg:
21885         case ISD::SIGN_EXTEND:
21886         case ISD::ZERO_EXTEND:
21887         case ISD::ANY_EXTEND:
21888           break;
21889         }
21890
21891       if (!ExpectingFlags) {
21892         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21893         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21894
21895         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21896           X86::CondCode tmp = cc0;
21897           cc0 = cc1;
21898           cc1 = tmp;
21899         }
21900
21901         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21902             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21903           // FIXME: need symbolic constants for these magic numbers.
21904           // See X86ATTInstPrinter.cpp:printSSECC().
21905           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21906           if (Subtarget->hasAVX512()) {
21907             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21908                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21909             if (N->getValueType(0) != MVT::i1)
21910               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21911                                  FSetCC);
21912             return FSetCC;
21913           }
21914           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21915                                               CMP00.getValueType(), CMP00, CMP01,
21916                                               DAG.getConstant(x86cc, MVT::i8));
21917
21918           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21919           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21920
21921           if (is64BitFP && !Subtarget->is64Bit()) {
21922             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21923             // 64-bit integer, since that's not a legal type. Since
21924             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21925             // bits, but can do this little dance to extract the lowest 32 bits
21926             // and work with those going forward.
21927             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21928                                            OnesOrZeroesF);
21929             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21930                                            Vector64);
21931             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21932                                         Vector32, DAG.getIntPtrConstant(0));
21933             IntVT = MVT::i32;
21934           }
21935
21936           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21937           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21938                                       DAG.getConstant(1, IntVT));
21939           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21940           return OneBitOfTruth;
21941         }
21942       }
21943     }
21944   }
21945   return SDValue();
21946 }
21947
21948 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21949 /// so it can be folded inside ANDNP.
21950 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21951   EVT VT = N->getValueType(0);
21952
21953   // Match direct AllOnes for 128 and 256-bit vectors
21954   if (ISD::isBuildVectorAllOnes(N))
21955     return true;
21956
21957   // Look through a bit convert.
21958   if (N->getOpcode() == ISD::BITCAST)
21959     N = N->getOperand(0).getNode();
21960
21961   // Sometimes the operand may come from a insert_subvector building a 256-bit
21962   // allones vector
21963   if (VT.is256BitVector() &&
21964       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21965     SDValue V1 = N->getOperand(0);
21966     SDValue V2 = N->getOperand(1);
21967
21968     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21969         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21970         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21971         ISD::isBuildVectorAllOnes(V2.getNode()))
21972       return true;
21973   }
21974
21975   return false;
21976 }
21977
21978 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21979 // register. In most cases we actually compare or select YMM-sized registers
21980 // and mixing the two types creates horrible code. This method optimizes
21981 // some of the transition sequences.
21982 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21983                                  TargetLowering::DAGCombinerInfo &DCI,
21984                                  const X86Subtarget *Subtarget) {
21985   EVT VT = N->getValueType(0);
21986   if (!VT.is256BitVector())
21987     return SDValue();
21988
21989   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21990           N->getOpcode() == ISD::ZERO_EXTEND ||
21991           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21992
21993   SDValue Narrow = N->getOperand(0);
21994   EVT NarrowVT = Narrow->getValueType(0);
21995   if (!NarrowVT.is128BitVector())
21996     return SDValue();
21997
21998   if (Narrow->getOpcode() != ISD::XOR &&
21999       Narrow->getOpcode() != ISD::AND &&
22000       Narrow->getOpcode() != ISD::OR)
22001     return SDValue();
22002
22003   SDValue N0  = Narrow->getOperand(0);
22004   SDValue N1  = Narrow->getOperand(1);
22005   SDLoc DL(Narrow);
22006
22007   // The Left side has to be a trunc.
22008   if (N0.getOpcode() != ISD::TRUNCATE)
22009     return SDValue();
22010
22011   // The type of the truncated inputs.
22012   EVT WideVT = N0->getOperand(0)->getValueType(0);
22013   if (WideVT != VT)
22014     return SDValue();
22015
22016   // The right side has to be a 'trunc' or a constant vector.
22017   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22018   ConstantSDNode *RHSConstSplat = nullptr;
22019   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22020     RHSConstSplat = RHSBV->getConstantSplatNode();
22021   if (!RHSTrunc && !RHSConstSplat)
22022     return SDValue();
22023
22024   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22025
22026   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22027     return SDValue();
22028
22029   // Set N0 and N1 to hold the inputs to the new wide operation.
22030   N0 = N0->getOperand(0);
22031   if (RHSConstSplat) {
22032     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22033                      SDValue(RHSConstSplat, 0));
22034     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22035     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22036   } else if (RHSTrunc) {
22037     N1 = N1->getOperand(0);
22038   }
22039
22040   // Generate the wide operation.
22041   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22042   unsigned Opcode = N->getOpcode();
22043   switch (Opcode) {
22044   case ISD::ANY_EXTEND:
22045     return Op;
22046   case ISD::ZERO_EXTEND: {
22047     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22048     APInt Mask = APInt::getAllOnesValue(InBits);
22049     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22050     return DAG.getNode(ISD::AND, DL, VT,
22051                        Op, DAG.getConstant(Mask, VT));
22052   }
22053   case ISD::SIGN_EXTEND:
22054     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22055                        Op, DAG.getValueType(NarrowVT));
22056   default:
22057     llvm_unreachable("Unexpected opcode");
22058   }
22059 }
22060
22061 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22062                                  TargetLowering::DAGCombinerInfo &DCI,
22063                                  const X86Subtarget *Subtarget) {
22064   SDValue N0 = N->getOperand(0);
22065   SDValue N1 = N->getOperand(1);
22066   SDLoc DL(N);
22067
22068   // A vector zext_in_reg may be represented as a shuffle,
22069   // feeding into a bitcast (this represents anyext) feeding into
22070   // an and with a mask.
22071   // We'd like to try to combine that into a shuffle with zero
22072   // plus a bitcast, removing the and.
22073   if (N0.getOpcode() != ISD::BITCAST ||
22074       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22075     return SDValue();
22076
22077   // The other side of the AND should be a splat of 2^C, where C
22078   // is the number of bits in the source type.
22079   if (N1.getOpcode() == ISD::BITCAST)
22080     N1 = N1.getOperand(0);
22081   if (N1.getOpcode() != ISD::BUILD_VECTOR)
22082     return SDValue();
22083   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22084
22085   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22086   EVT SrcType = Shuffle->getValueType(0);
22087
22088   // We expect a single-source shuffle
22089   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22090     return SDValue();
22091
22092   unsigned SrcSize = SrcType.getScalarSizeInBits();
22093
22094   APInt SplatValue, SplatUndef;
22095   unsigned SplatBitSize;
22096   bool HasAnyUndefs;
22097   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22098                                 SplatBitSize, HasAnyUndefs))
22099     return SDValue();
22100
22101   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22102   // Make sure the splat matches the mask we expect
22103   if (SplatBitSize > ResSize ||
22104       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22105     return SDValue();
22106
22107   // Make sure the input and output size make sense
22108   if (SrcSize >= ResSize || ResSize % SrcSize)
22109     return SDValue();
22110
22111   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22112   // The number of u's between each two values depends on the ratio between
22113   // the source and dest type.
22114   unsigned ZextRatio = ResSize / SrcSize;
22115   bool IsZext = true;
22116   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22117     if (i % ZextRatio) {
22118       if (Shuffle->getMaskElt(i) > 0) {
22119         // Expected undef
22120         IsZext = false;
22121         break;
22122       }
22123     } else {
22124       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22125         // Expected element number
22126         IsZext = false;
22127         break;
22128       }
22129     }
22130   }
22131
22132   if (!IsZext)
22133     return SDValue();
22134
22135   // Ok, perform the transformation - replace the shuffle with
22136   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22137   // (instead of undef) where the k elements come from the zero vector.
22138   SmallVector<int, 8> Mask;
22139   unsigned NumElems = SrcType.getVectorNumElements();
22140   for (unsigned i = 0; i < NumElems; ++i)
22141     if (i % ZextRatio)
22142       Mask.push_back(NumElems);
22143     else
22144       Mask.push_back(i / ZextRatio);
22145
22146   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22147     Shuffle->getOperand(0), DAG.getConstant(0, SrcType), Mask);
22148   return DAG.getNode(ISD::BITCAST, DL,  N0.getValueType(), NewShuffle);
22149 }
22150
22151 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22152                                  TargetLowering::DAGCombinerInfo &DCI,
22153                                  const X86Subtarget *Subtarget) {
22154   if (DCI.isBeforeLegalizeOps())
22155     return SDValue();
22156
22157   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22158     return Zext;
22159
22160   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22161     return R;
22162
22163   EVT VT = N->getValueType(0);
22164   SDValue N0 = N->getOperand(0);
22165   SDValue N1 = N->getOperand(1);
22166   SDLoc DL(N);
22167
22168   // Create BEXTR instructions
22169   // BEXTR is ((X >> imm) & (2**size-1))
22170   if (VT == MVT::i32 || VT == MVT::i64) {
22171     // Check for BEXTR.
22172     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22173         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22174       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22175       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22176       if (MaskNode && ShiftNode) {
22177         uint64_t Mask = MaskNode->getZExtValue();
22178         uint64_t Shift = ShiftNode->getZExtValue();
22179         if (isMask_64(Mask)) {
22180           uint64_t MaskSize = countPopulation(Mask);
22181           if (Shift + MaskSize <= VT.getSizeInBits())
22182             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22183                                DAG.getConstant(Shift | (MaskSize << 8), VT));
22184         }
22185       }
22186     } // BEXTR
22187
22188     return SDValue();
22189   }
22190
22191   // Want to form ANDNP nodes:
22192   // 1) In the hopes of then easily combining them with OR and AND nodes
22193   //    to form PBLEND/PSIGN.
22194   // 2) To match ANDN packed intrinsics
22195   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22196     return SDValue();
22197
22198   // Check LHS for vnot
22199   if (N0.getOpcode() == ISD::XOR &&
22200       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22201       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22202     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22203
22204   // Check RHS for vnot
22205   if (N1.getOpcode() == ISD::XOR &&
22206       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22207       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22208     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22209
22210   return SDValue();
22211 }
22212
22213 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22214                                 TargetLowering::DAGCombinerInfo &DCI,
22215                                 const X86Subtarget *Subtarget) {
22216   if (DCI.isBeforeLegalizeOps())
22217     return SDValue();
22218
22219   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22220   if (R.getNode())
22221     return R;
22222
22223   SDValue N0 = N->getOperand(0);
22224   SDValue N1 = N->getOperand(1);
22225   EVT VT = N->getValueType(0);
22226
22227   // look for psign/blend
22228   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22229     if (!Subtarget->hasSSSE3() ||
22230         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22231       return SDValue();
22232
22233     // Canonicalize pandn to RHS
22234     if (N0.getOpcode() == X86ISD::ANDNP)
22235       std::swap(N0, N1);
22236     // or (and (m, y), (pandn m, x))
22237     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22238       SDValue Mask = N1.getOperand(0);
22239       SDValue X    = N1.getOperand(1);
22240       SDValue Y;
22241       if (N0.getOperand(0) == Mask)
22242         Y = N0.getOperand(1);
22243       if (N0.getOperand(1) == Mask)
22244         Y = N0.getOperand(0);
22245
22246       // Check to see if the mask appeared in both the AND and ANDNP and
22247       if (!Y.getNode())
22248         return SDValue();
22249
22250       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22251       // Look through mask bitcast.
22252       if (Mask.getOpcode() == ISD::BITCAST)
22253         Mask = Mask.getOperand(0);
22254       if (X.getOpcode() == ISD::BITCAST)
22255         X = X.getOperand(0);
22256       if (Y.getOpcode() == ISD::BITCAST)
22257         Y = Y.getOperand(0);
22258
22259       EVT MaskVT = Mask.getValueType();
22260
22261       // Validate that the Mask operand is a vector sra node.
22262       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22263       // there is no psrai.b
22264       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22265       unsigned SraAmt = ~0;
22266       if (Mask.getOpcode() == ISD::SRA) {
22267         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22268           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22269             SraAmt = AmtConst->getZExtValue();
22270       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22271         SDValue SraC = Mask.getOperand(1);
22272         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22273       }
22274       if ((SraAmt + 1) != EltBits)
22275         return SDValue();
22276
22277       SDLoc DL(N);
22278
22279       // Now we know we at least have a plendvb with the mask val.  See if
22280       // we can form a psignb/w/d.
22281       // psign = x.type == y.type == mask.type && y = sub(0, x);
22282       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22283           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22284           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22285         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22286                "Unsupported VT for PSIGN");
22287         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22288         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22289       }
22290       // PBLENDVB only available on SSE 4.1
22291       if (!Subtarget->hasSSE41())
22292         return SDValue();
22293
22294       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22295
22296       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22297       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22298       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22299       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22300       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22301     }
22302   }
22303
22304   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22305     return SDValue();
22306
22307   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22308   MachineFunction &MF = DAG.getMachineFunction();
22309   bool OptForSize =
22310       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22311
22312   // SHLD/SHRD instructions have lower register pressure, but on some
22313   // platforms they have higher latency than the equivalent
22314   // series of shifts/or that would otherwise be generated.
22315   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22316   // have higher latencies and we are not optimizing for size.
22317   if (!OptForSize && Subtarget->isSHLDSlow())
22318     return SDValue();
22319
22320   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22321     std::swap(N0, N1);
22322   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22323     return SDValue();
22324   if (!N0.hasOneUse() || !N1.hasOneUse())
22325     return SDValue();
22326
22327   SDValue ShAmt0 = N0.getOperand(1);
22328   if (ShAmt0.getValueType() != MVT::i8)
22329     return SDValue();
22330   SDValue ShAmt1 = N1.getOperand(1);
22331   if (ShAmt1.getValueType() != MVT::i8)
22332     return SDValue();
22333   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22334     ShAmt0 = ShAmt0.getOperand(0);
22335   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22336     ShAmt1 = ShAmt1.getOperand(0);
22337
22338   SDLoc DL(N);
22339   unsigned Opc = X86ISD::SHLD;
22340   SDValue Op0 = N0.getOperand(0);
22341   SDValue Op1 = N1.getOperand(0);
22342   if (ShAmt0.getOpcode() == ISD::SUB) {
22343     Opc = X86ISD::SHRD;
22344     std::swap(Op0, Op1);
22345     std::swap(ShAmt0, ShAmt1);
22346   }
22347
22348   unsigned Bits = VT.getSizeInBits();
22349   if (ShAmt1.getOpcode() == ISD::SUB) {
22350     SDValue Sum = ShAmt1.getOperand(0);
22351     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22352       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22353       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22354         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22355       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22356         return DAG.getNode(Opc, DL, VT,
22357                            Op0, Op1,
22358                            DAG.getNode(ISD::TRUNCATE, DL,
22359                                        MVT::i8, ShAmt0));
22360     }
22361   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22362     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22363     if (ShAmt0C &&
22364         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22365       return DAG.getNode(Opc, DL, VT,
22366                          N0.getOperand(0), N1.getOperand(0),
22367                          DAG.getNode(ISD::TRUNCATE, DL,
22368                                        MVT::i8, ShAmt0));
22369   }
22370
22371   return SDValue();
22372 }
22373
22374 // Generate NEG and CMOV for integer abs.
22375 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22376   EVT VT = N->getValueType(0);
22377
22378   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22379   // 8-bit integer abs to NEG and CMOV.
22380   if (VT.isInteger() && VT.getSizeInBits() == 8)
22381     return SDValue();
22382
22383   SDValue N0 = N->getOperand(0);
22384   SDValue N1 = N->getOperand(1);
22385   SDLoc DL(N);
22386
22387   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22388   // and change it to SUB and CMOV.
22389   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22390       N0.getOpcode() == ISD::ADD &&
22391       N0.getOperand(1) == N1 &&
22392       N1.getOpcode() == ISD::SRA &&
22393       N1.getOperand(0) == N0.getOperand(0))
22394     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22395       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22396         // Generate SUB & CMOV.
22397         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22398                                   DAG.getConstant(0, VT), N0.getOperand(0));
22399
22400         SDValue Ops[] = { N0.getOperand(0), Neg,
22401                           DAG.getConstant(X86::COND_GE, MVT::i8),
22402                           SDValue(Neg.getNode(), 1) };
22403         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22404       }
22405   return SDValue();
22406 }
22407
22408 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22409 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22410                                  TargetLowering::DAGCombinerInfo &DCI,
22411                                  const X86Subtarget *Subtarget) {
22412   if (DCI.isBeforeLegalizeOps())
22413     return SDValue();
22414
22415   if (Subtarget->hasCMov()) {
22416     SDValue RV = performIntegerAbsCombine(N, DAG);
22417     if (RV.getNode())
22418       return RV;
22419   }
22420
22421   return SDValue();
22422 }
22423
22424 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22425 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22426                                   TargetLowering::DAGCombinerInfo &DCI,
22427                                   const X86Subtarget *Subtarget) {
22428   LoadSDNode *Ld = cast<LoadSDNode>(N);
22429   EVT RegVT = Ld->getValueType(0);
22430   EVT MemVT = Ld->getMemoryVT();
22431   SDLoc dl(Ld);
22432   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22433
22434   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22435   // into two 16-byte operations.
22436   ISD::LoadExtType Ext = Ld->getExtensionType();
22437   unsigned Alignment = Ld->getAlignment();
22438   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22439   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22440       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22441     unsigned NumElems = RegVT.getVectorNumElements();
22442     if (NumElems < 2)
22443       return SDValue();
22444
22445     SDValue Ptr = Ld->getBasePtr();
22446     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22447
22448     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22449                                   NumElems/2);
22450     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22451                                 Ld->getPointerInfo(), Ld->isVolatile(),
22452                                 Ld->isNonTemporal(), Ld->isInvariant(),
22453                                 Alignment);
22454     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22455     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22456                                 Ld->getPointerInfo(), Ld->isVolatile(),
22457                                 Ld->isNonTemporal(), Ld->isInvariant(),
22458                                 std::min(16U, Alignment));
22459     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22460                              Load1.getValue(1),
22461                              Load2.getValue(1));
22462
22463     SDValue NewVec = DAG.getUNDEF(RegVT);
22464     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22465     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22466     return DCI.CombineTo(N, NewVec, TF, true);
22467   }
22468
22469   return SDValue();
22470 }
22471
22472 /// PerformMLOADCombine - Resolve extending loads
22473 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22474                                    TargetLowering::DAGCombinerInfo &DCI,
22475                                    const X86Subtarget *Subtarget) {
22476   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22477   if (Mld->getExtensionType() != ISD::SEXTLOAD)
22478     return SDValue();
22479
22480   EVT VT = Mld->getValueType(0);
22481   unsigned NumElems = VT.getVectorNumElements();
22482   EVT LdVT = Mld->getMemoryVT();
22483   SDLoc dl(Mld);
22484
22485   assert(LdVT != VT && "Cannot extend to the same type");
22486   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22487   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22488   // From, To sizes and ElemCount must be pow of two
22489   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22490     "Unexpected size for extending masked load");
22491
22492   unsigned SizeRatio  = ToSz / FromSz;
22493   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22494
22495   // Create a type on which we perform the shuffle
22496   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22497           LdVT.getScalarType(), NumElems*SizeRatio);
22498   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22499
22500   // Convert Src0 value
22501   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22502   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22503     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22504     for (unsigned i = 0; i != NumElems; ++i)
22505       ShuffleVec[i] = i * SizeRatio;
22506
22507     // Can't shuffle using an illegal type.
22508     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22509             && "WideVecVT should be legal");
22510     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22511                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22512   }
22513   // Prepare the new mask
22514   SDValue NewMask;
22515   SDValue Mask = Mld->getMask();
22516   if (Mask.getValueType() == VT) {
22517     // Mask and original value have the same type
22518     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22519     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22520     for (unsigned i = 0; i != NumElems; ++i)
22521       ShuffleVec[i] = i * SizeRatio;
22522     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22523       ShuffleVec[i] = NumElems*SizeRatio;
22524     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22525                                    DAG.getConstant(0, WideVecVT),
22526                                    &ShuffleVec[0]);
22527   }
22528   else {
22529     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22530     unsigned WidenNumElts = NumElems*SizeRatio;
22531     unsigned MaskNumElts = VT.getVectorNumElements();
22532     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22533                                      WidenNumElts);
22534
22535     unsigned NumConcat = WidenNumElts / MaskNumElts;
22536     SmallVector<SDValue, 16> Ops(NumConcat);
22537     SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22538     Ops[0] = Mask;
22539     for (unsigned i = 1; i != NumConcat; ++i)
22540       Ops[i] = ZeroVal;
22541
22542     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22543   }
22544
22545   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22546                                      Mld->getBasePtr(), NewMask, WideSrc0,
22547                                      Mld->getMemoryVT(), Mld->getMemOperand(),
22548                                      ISD::NON_EXTLOAD);
22549   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22550   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22551
22552 }
22553 /// PerformMSTORECombine - Resolve truncating stores
22554 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22555                                     const X86Subtarget *Subtarget) {
22556   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22557   if (!Mst->isTruncatingStore())
22558     return SDValue();
22559
22560   EVT VT = Mst->getValue().getValueType();
22561   unsigned NumElems = VT.getVectorNumElements();
22562   EVT StVT = Mst->getMemoryVT();
22563   SDLoc dl(Mst);
22564
22565   assert(StVT != VT && "Cannot truncate to the same type");
22566   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22567   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22568
22569   // From, To sizes and ElemCount must be pow of two
22570   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22571     "Unexpected size for truncating masked store");
22572   // We are going to use the original vector elt for storing.
22573   // Accumulated smaller vector elements must be a multiple of the store size.
22574   assert (((NumElems * FromSz) % ToSz) == 0 &&
22575           "Unexpected ratio for truncating masked store");
22576
22577   unsigned SizeRatio  = FromSz / ToSz;
22578   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22579
22580   // Create a type on which we perform the shuffle
22581   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22582           StVT.getScalarType(), NumElems*SizeRatio);
22583
22584   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22585
22586   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
22587   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22588   for (unsigned i = 0; i != NumElems; ++i)
22589     ShuffleVec[i] = i * SizeRatio;
22590
22591   // Can't shuffle using an illegal type.
22592   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22593           && "WideVecVT should be legal");
22594
22595   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22596                                         DAG.getUNDEF(WideVecVT),
22597                                         &ShuffleVec[0]);
22598
22599   SDValue NewMask;
22600   SDValue Mask = Mst->getMask();
22601   if (Mask.getValueType() == VT) {
22602     // Mask and original value have the same type
22603     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22604     for (unsigned i = 0; i != NumElems; ++i)
22605       ShuffleVec[i] = i * SizeRatio;
22606     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22607       ShuffleVec[i] = NumElems*SizeRatio;
22608     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22609                                    DAG.getConstant(0, WideVecVT),
22610                                    &ShuffleVec[0]);
22611   }
22612   else {
22613     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22614     unsigned WidenNumElts = NumElems*SizeRatio;
22615     unsigned MaskNumElts = VT.getVectorNumElements();
22616     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22617                                      WidenNumElts);
22618
22619     unsigned NumConcat = WidenNumElts / MaskNumElts;
22620     SmallVector<SDValue, 16> Ops(NumConcat);
22621     SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22622     Ops[0] = Mask;
22623     for (unsigned i = 1; i != NumConcat; ++i)
22624       Ops[i] = ZeroVal;
22625
22626     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22627   }
22628
22629   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
22630                             NewMask, StVT, Mst->getMemOperand(), false);
22631 }
22632 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22633 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22634                                    const X86Subtarget *Subtarget) {
22635   StoreSDNode *St = cast<StoreSDNode>(N);
22636   EVT VT = St->getValue().getValueType();
22637   EVT StVT = St->getMemoryVT();
22638   SDLoc dl(St);
22639   SDValue StoredVal = St->getOperand(1);
22640   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22641
22642   // If we are saving a concatenation of two XMM registers and 32-byte stores
22643   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
22644   unsigned Alignment = St->getAlignment();
22645   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22646   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22647       StVT == VT && !IsAligned) {
22648     unsigned NumElems = VT.getVectorNumElements();
22649     if (NumElems < 2)
22650       return SDValue();
22651
22652     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22653     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22654
22655     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22656     SDValue Ptr0 = St->getBasePtr();
22657     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22658
22659     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22660                                 St->getPointerInfo(), St->isVolatile(),
22661                                 St->isNonTemporal(), Alignment);
22662     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22663                                 St->getPointerInfo(), St->isVolatile(),
22664                                 St->isNonTemporal(),
22665                                 std::min(16U, Alignment));
22666     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22667   }
22668
22669   // Optimize trunc store (of multiple scalars) to shuffle and store.
22670   // First, pack all of the elements in one place. Next, store to memory
22671   // in fewer chunks.
22672   if (St->isTruncatingStore() && VT.isVector()) {
22673     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22674     unsigned NumElems = VT.getVectorNumElements();
22675     assert(StVT != VT && "Cannot truncate to the same type");
22676     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22677     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22678
22679     // From, To sizes and ElemCount must be pow of two
22680     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22681     // We are going to use the original vector elt for storing.
22682     // Accumulated smaller vector elements must be a multiple of the store size.
22683     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22684
22685     unsigned SizeRatio  = FromSz / ToSz;
22686
22687     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22688
22689     // Create a type on which we perform the shuffle
22690     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22691             StVT.getScalarType(), NumElems*SizeRatio);
22692
22693     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22694
22695     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22696     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22697     for (unsigned i = 0; i != NumElems; ++i)
22698       ShuffleVec[i] = i * SizeRatio;
22699
22700     // Can't shuffle using an illegal type.
22701     if (!TLI.isTypeLegal(WideVecVT))
22702       return SDValue();
22703
22704     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22705                                          DAG.getUNDEF(WideVecVT),
22706                                          &ShuffleVec[0]);
22707     // At this point all of the data is stored at the bottom of the
22708     // register. We now need to save it to mem.
22709
22710     // Find the largest store unit
22711     MVT StoreType = MVT::i8;
22712     for (MVT Tp : MVT::integer_valuetypes()) {
22713       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22714         StoreType = Tp;
22715     }
22716
22717     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22718     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22719         (64 <= NumElems * ToSz))
22720       StoreType = MVT::f64;
22721
22722     // Bitcast the original vector into a vector of store-size units
22723     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22724             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22725     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22726     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22727     SmallVector<SDValue, 8> Chains;
22728     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22729                                         TLI.getPointerTy());
22730     SDValue Ptr = St->getBasePtr();
22731
22732     // Perform one or more big stores into memory.
22733     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22734       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22735                                    StoreType, ShuffWide,
22736                                    DAG.getIntPtrConstant(i));
22737       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22738                                 St->getPointerInfo(), St->isVolatile(),
22739                                 St->isNonTemporal(), St->getAlignment());
22740       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22741       Chains.push_back(Ch);
22742     }
22743
22744     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22745   }
22746
22747   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
22748   // the FP state in cases where an emms may be missing.
22749   // A preferable solution to the general problem is to figure out the right
22750   // places to insert EMMS.  This qualifies as a quick hack.
22751
22752   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22753   if (VT.getSizeInBits() != 64)
22754     return SDValue();
22755
22756   const Function *F = DAG.getMachineFunction().getFunction();
22757   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
22758   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22759                      && Subtarget->hasSSE2();
22760   if ((VT.isVector() ||
22761        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22762       isa<LoadSDNode>(St->getValue()) &&
22763       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22764       St->getChain().hasOneUse() && !St->isVolatile()) {
22765     SDNode* LdVal = St->getValue().getNode();
22766     LoadSDNode *Ld = nullptr;
22767     int TokenFactorIndex = -1;
22768     SmallVector<SDValue, 8> Ops;
22769     SDNode* ChainVal = St->getChain().getNode();
22770     // Must be a store of a load.  We currently handle two cases:  the load
22771     // is a direct child, and it's under an intervening TokenFactor.  It is
22772     // possible to dig deeper under nested TokenFactors.
22773     if (ChainVal == LdVal)
22774       Ld = cast<LoadSDNode>(St->getChain());
22775     else if (St->getValue().hasOneUse() &&
22776              ChainVal->getOpcode() == ISD::TokenFactor) {
22777       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22778         if (ChainVal->getOperand(i).getNode() == LdVal) {
22779           TokenFactorIndex = i;
22780           Ld = cast<LoadSDNode>(St->getValue());
22781         } else
22782           Ops.push_back(ChainVal->getOperand(i));
22783       }
22784     }
22785
22786     if (!Ld || !ISD::isNormalLoad(Ld))
22787       return SDValue();
22788
22789     // If this is not the MMX case, i.e. we are just turning i64 load/store
22790     // into f64 load/store, avoid the transformation if there are multiple
22791     // uses of the loaded value.
22792     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22793       return SDValue();
22794
22795     SDLoc LdDL(Ld);
22796     SDLoc StDL(N);
22797     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22798     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22799     // pair instead.
22800     if (Subtarget->is64Bit() || F64IsLegal) {
22801       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22802       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22803                                   Ld->getPointerInfo(), Ld->isVolatile(),
22804                                   Ld->isNonTemporal(), Ld->isInvariant(),
22805                                   Ld->getAlignment());
22806       SDValue NewChain = NewLd.getValue(1);
22807       if (TokenFactorIndex != -1) {
22808         Ops.push_back(NewChain);
22809         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22810       }
22811       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22812                           St->getPointerInfo(),
22813                           St->isVolatile(), St->isNonTemporal(),
22814                           St->getAlignment());
22815     }
22816
22817     // Otherwise, lower to two pairs of 32-bit loads / stores.
22818     SDValue LoAddr = Ld->getBasePtr();
22819     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22820                                  DAG.getConstant(4, MVT::i32));
22821
22822     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22823                                Ld->getPointerInfo(),
22824                                Ld->isVolatile(), Ld->isNonTemporal(),
22825                                Ld->isInvariant(), Ld->getAlignment());
22826     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22827                                Ld->getPointerInfo().getWithOffset(4),
22828                                Ld->isVolatile(), Ld->isNonTemporal(),
22829                                Ld->isInvariant(),
22830                                MinAlign(Ld->getAlignment(), 4));
22831
22832     SDValue NewChain = LoLd.getValue(1);
22833     if (TokenFactorIndex != -1) {
22834       Ops.push_back(LoLd);
22835       Ops.push_back(HiLd);
22836       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22837     }
22838
22839     LoAddr = St->getBasePtr();
22840     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22841                          DAG.getConstant(4, MVT::i32));
22842
22843     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22844                                 St->getPointerInfo(),
22845                                 St->isVolatile(), St->isNonTemporal(),
22846                                 St->getAlignment());
22847     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22848                                 St->getPointerInfo().getWithOffset(4),
22849                                 St->isVolatile(),
22850                                 St->isNonTemporal(),
22851                                 MinAlign(St->getAlignment(), 4));
22852     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22853   }
22854   return SDValue();
22855 }
22856
22857 /// Return 'true' if this vector operation is "horizontal"
22858 /// and return the operands for the horizontal operation in LHS and RHS.  A
22859 /// horizontal operation performs the binary operation on successive elements
22860 /// of its first operand, then on successive elements of its second operand,
22861 /// returning the resulting values in a vector.  For example, if
22862 ///   A = < float a0, float a1, float a2, float a3 >
22863 /// and
22864 ///   B = < float b0, float b1, float b2, float b3 >
22865 /// then the result of doing a horizontal operation on A and B is
22866 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22867 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22868 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22869 /// set to A, RHS to B, and the routine returns 'true'.
22870 /// Note that the binary operation should have the property that if one of the
22871 /// operands is UNDEF then the result is UNDEF.
22872 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22873   // Look for the following pattern: if
22874   //   A = < float a0, float a1, float a2, float a3 >
22875   //   B = < float b0, float b1, float b2, float b3 >
22876   // and
22877   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22878   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22879   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22880   // which is A horizontal-op B.
22881
22882   // At least one of the operands should be a vector shuffle.
22883   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22884       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22885     return false;
22886
22887   MVT VT = LHS.getSimpleValueType();
22888
22889   assert((VT.is128BitVector() || VT.is256BitVector()) &&
22890          "Unsupported vector type for horizontal add/sub");
22891
22892   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22893   // operate independently on 128-bit lanes.
22894   unsigned NumElts = VT.getVectorNumElements();
22895   unsigned NumLanes = VT.getSizeInBits()/128;
22896   unsigned NumLaneElts = NumElts / NumLanes;
22897   assert((NumLaneElts % 2 == 0) &&
22898          "Vector type should have an even number of elements in each lane");
22899   unsigned HalfLaneElts = NumLaneElts/2;
22900
22901   // View LHS in the form
22902   //   LHS = VECTOR_SHUFFLE A, B, LMask
22903   // If LHS is not a shuffle then pretend it is the shuffle
22904   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22905   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22906   // type VT.
22907   SDValue A, B;
22908   SmallVector<int, 16> LMask(NumElts);
22909   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22910     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22911       A = LHS.getOperand(0);
22912     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22913       B = LHS.getOperand(1);
22914     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22915     std::copy(Mask.begin(), Mask.end(), LMask.begin());
22916   } else {
22917     if (LHS.getOpcode() != ISD::UNDEF)
22918       A = LHS;
22919     for (unsigned i = 0; i != NumElts; ++i)
22920       LMask[i] = i;
22921   }
22922
22923   // Likewise, view RHS in the form
22924   //   RHS = VECTOR_SHUFFLE C, D, RMask
22925   SDValue C, D;
22926   SmallVector<int, 16> RMask(NumElts);
22927   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22928     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22929       C = RHS.getOperand(0);
22930     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22931       D = RHS.getOperand(1);
22932     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22933     std::copy(Mask.begin(), Mask.end(), RMask.begin());
22934   } else {
22935     if (RHS.getOpcode() != ISD::UNDEF)
22936       C = RHS;
22937     for (unsigned i = 0; i != NumElts; ++i)
22938       RMask[i] = i;
22939   }
22940
22941   // Check that the shuffles are both shuffling the same vectors.
22942   if (!(A == C && B == D) && !(A == D && B == C))
22943     return false;
22944
22945   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22946   if (!A.getNode() && !B.getNode())
22947     return false;
22948
22949   // If A and B occur in reverse order in RHS, then "swap" them (which means
22950   // rewriting the mask).
22951   if (A != C)
22952     ShuffleVectorSDNode::commuteMask(RMask);
22953
22954   // At this point LHS and RHS are equivalent to
22955   //   LHS = VECTOR_SHUFFLE A, B, LMask
22956   //   RHS = VECTOR_SHUFFLE A, B, RMask
22957   // Check that the masks correspond to performing a horizontal operation.
22958   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22959     for (unsigned i = 0; i != NumLaneElts; ++i) {
22960       int LIdx = LMask[i+l], RIdx = RMask[i+l];
22961
22962       // Ignore any UNDEF components.
22963       if (LIdx < 0 || RIdx < 0 ||
22964           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22965           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22966         continue;
22967
22968       // Check that successive elements are being operated on.  If not, this is
22969       // not a horizontal operation.
22970       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22971       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22972       if (!(LIdx == Index && RIdx == Index + 1) &&
22973           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22974         return false;
22975     }
22976   }
22977
22978   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22979   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22980   return true;
22981 }
22982
22983 /// Do target-specific dag combines on floating point adds.
22984 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22985                                   const X86Subtarget *Subtarget) {
22986   EVT VT = N->getValueType(0);
22987   SDValue LHS = N->getOperand(0);
22988   SDValue RHS = N->getOperand(1);
22989
22990   // Try to synthesize horizontal adds from adds of shuffles.
22991   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22992        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22993       isHorizontalBinOp(LHS, RHS, true))
22994     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22995   return SDValue();
22996 }
22997
22998 /// Do target-specific dag combines on floating point subs.
22999 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23000                                   const X86Subtarget *Subtarget) {
23001   EVT VT = N->getValueType(0);
23002   SDValue LHS = N->getOperand(0);
23003   SDValue RHS = N->getOperand(1);
23004
23005   // Try to synthesize horizontal subs from subs of shuffles.
23006   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23007        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23008       isHorizontalBinOp(LHS, RHS, false))
23009     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23010   return SDValue();
23011 }
23012
23013 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23014 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23015   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23016
23017   // F[X]OR(0.0, x) -> x
23018   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23019     if (C->getValueAPF().isPosZero())
23020       return N->getOperand(1);
23021
23022   // F[X]OR(x, 0.0) -> x
23023   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23024     if (C->getValueAPF().isPosZero())
23025       return N->getOperand(0);
23026   return SDValue();
23027 }
23028
23029 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23030 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23031   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23032
23033   // Only perform optimizations if UnsafeMath is used.
23034   if (!DAG.getTarget().Options.UnsafeFPMath)
23035     return SDValue();
23036
23037   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23038   // into FMINC and FMAXC, which are Commutative operations.
23039   unsigned NewOp = 0;
23040   switch (N->getOpcode()) {
23041     default: llvm_unreachable("unknown opcode");
23042     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23043     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23044   }
23045
23046   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23047                      N->getOperand(0), N->getOperand(1));
23048 }
23049
23050 /// Do target-specific dag combines on X86ISD::FAND nodes.
23051 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23052   // FAND(0.0, x) -> 0.0
23053   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23054     if (C->getValueAPF().isPosZero())
23055       return N->getOperand(0);
23056
23057   // FAND(x, 0.0) -> 0.0
23058   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23059     if (C->getValueAPF().isPosZero())
23060       return N->getOperand(1);
23061
23062   return SDValue();
23063 }
23064
23065 /// Do target-specific dag combines on X86ISD::FANDN nodes
23066 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23067   // FANDN(0.0, x) -> x
23068   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23069     if (C->getValueAPF().isPosZero())
23070       return N->getOperand(1);
23071
23072   // FANDN(x, 0.0) -> 0.0
23073   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23074     if (C->getValueAPF().isPosZero())
23075       return N->getOperand(1);
23076
23077   return SDValue();
23078 }
23079
23080 static SDValue PerformBTCombine(SDNode *N,
23081                                 SelectionDAG &DAG,
23082                                 TargetLowering::DAGCombinerInfo &DCI) {
23083   // BT ignores high bits in the bit index operand.
23084   SDValue Op1 = N->getOperand(1);
23085   if (Op1.hasOneUse()) {
23086     unsigned BitWidth = Op1.getValueSizeInBits();
23087     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23088     APInt KnownZero, KnownOne;
23089     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23090                                           !DCI.isBeforeLegalizeOps());
23091     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23092     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23093         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23094       DCI.CommitTargetLoweringOpt(TLO);
23095   }
23096   return SDValue();
23097 }
23098
23099 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23100   SDValue Op = N->getOperand(0);
23101   if (Op.getOpcode() == ISD::BITCAST)
23102     Op = Op.getOperand(0);
23103   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23104   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23105       VT.getVectorElementType().getSizeInBits() ==
23106       OpVT.getVectorElementType().getSizeInBits()) {
23107     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23108   }
23109   return SDValue();
23110 }
23111
23112 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23113                                                const X86Subtarget *Subtarget) {
23114   EVT VT = N->getValueType(0);
23115   if (!VT.isVector())
23116     return SDValue();
23117
23118   SDValue N0 = N->getOperand(0);
23119   SDValue N1 = N->getOperand(1);
23120   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23121   SDLoc dl(N);
23122
23123   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23124   // both SSE and AVX2 since there is no sign-extended shift right
23125   // operation on a vector with 64-bit elements.
23126   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23127   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23128   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23129       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23130     SDValue N00 = N0.getOperand(0);
23131
23132     // EXTLOAD has a better solution on AVX2,
23133     // it may be replaced with X86ISD::VSEXT node.
23134     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23135       if (!ISD::isNormalLoad(N00.getNode()))
23136         return SDValue();
23137
23138     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23139         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23140                                   N00, N1);
23141       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23142     }
23143   }
23144   return SDValue();
23145 }
23146
23147 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23148                                   TargetLowering::DAGCombinerInfo &DCI,
23149                                   const X86Subtarget *Subtarget) {
23150   SDValue N0 = N->getOperand(0);
23151   EVT VT = N->getValueType(0);
23152
23153   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23154   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23155   // This exposes the sext to the sdivrem lowering, so that it directly extends
23156   // from AH (which we otherwise need to do contortions to access).
23157   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23158       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23159     SDLoc dl(N);
23160     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23161     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23162                             N0.getOperand(0), N0.getOperand(1));
23163     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23164     return R.getValue(1);
23165   }
23166
23167   if (!DCI.isBeforeLegalizeOps())
23168     return SDValue();
23169
23170   if (!Subtarget->hasFp256())
23171     return SDValue();
23172
23173   if (VT.isVector() && VT.getSizeInBits() == 256) {
23174     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23175     if (R.getNode())
23176       return R;
23177   }
23178
23179   return SDValue();
23180 }
23181
23182 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23183                                  const X86Subtarget* Subtarget) {
23184   SDLoc dl(N);
23185   EVT VT = N->getValueType(0);
23186
23187   // Let legalize expand this if it isn't a legal type yet.
23188   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23189     return SDValue();
23190
23191   EVT ScalarVT = VT.getScalarType();
23192   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23193       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23194     return SDValue();
23195
23196   SDValue A = N->getOperand(0);
23197   SDValue B = N->getOperand(1);
23198   SDValue C = N->getOperand(2);
23199
23200   bool NegA = (A.getOpcode() == ISD::FNEG);
23201   bool NegB = (B.getOpcode() == ISD::FNEG);
23202   bool NegC = (C.getOpcode() == ISD::FNEG);
23203
23204   // Negative multiplication when NegA xor NegB
23205   bool NegMul = (NegA != NegB);
23206   if (NegA)
23207     A = A.getOperand(0);
23208   if (NegB)
23209     B = B.getOperand(0);
23210   if (NegC)
23211     C = C.getOperand(0);
23212
23213   unsigned Opcode;
23214   if (!NegMul)
23215     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23216   else
23217     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23218
23219   return DAG.getNode(Opcode, dl, VT, A, B, C);
23220 }
23221
23222 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23223                                   TargetLowering::DAGCombinerInfo &DCI,
23224                                   const X86Subtarget *Subtarget) {
23225   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23226   //           (and (i32 x86isd::setcc_carry), 1)
23227   // This eliminates the zext. This transformation is necessary because
23228   // ISD::SETCC is always legalized to i8.
23229   SDLoc dl(N);
23230   SDValue N0 = N->getOperand(0);
23231   EVT VT = N->getValueType(0);
23232
23233   if (N0.getOpcode() == ISD::AND &&
23234       N0.hasOneUse() &&
23235       N0.getOperand(0).hasOneUse()) {
23236     SDValue N00 = N0.getOperand(0);
23237     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23238       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23239       if (!C || C->getZExtValue() != 1)
23240         return SDValue();
23241       return DAG.getNode(ISD::AND, dl, VT,
23242                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23243                                      N00.getOperand(0), N00.getOperand(1)),
23244                          DAG.getConstant(1, VT));
23245     }
23246   }
23247
23248   if (N0.getOpcode() == ISD::TRUNCATE &&
23249       N0.hasOneUse() &&
23250       N0.getOperand(0).hasOneUse()) {
23251     SDValue N00 = N0.getOperand(0);
23252     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23253       return DAG.getNode(ISD::AND, dl, VT,
23254                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23255                                      N00.getOperand(0), N00.getOperand(1)),
23256                          DAG.getConstant(1, VT));
23257     }
23258   }
23259   if (VT.is256BitVector()) {
23260     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23261     if (R.getNode())
23262       return R;
23263   }
23264
23265   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23266   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23267   // This exposes the zext to the udivrem lowering, so that it directly extends
23268   // from AH (which we otherwise need to do contortions to access).
23269   if (N0.getOpcode() == ISD::UDIVREM &&
23270       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23271       (VT == MVT::i32 || VT == MVT::i64)) {
23272     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23273     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23274                             N0.getOperand(0), N0.getOperand(1));
23275     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23276     return R.getValue(1);
23277   }
23278
23279   return SDValue();
23280 }
23281
23282 // Optimize x == -y --> x+y == 0
23283 //          x != -y --> x+y != 0
23284 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23285                                       const X86Subtarget* Subtarget) {
23286   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23287   SDValue LHS = N->getOperand(0);
23288   SDValue RHS = N->getOperand(1);
23289   EVT VT = N->getValueType(0);
23290   SDLoc DL(N);
23291
23292   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23293     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23294       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23295         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N), LHS.getValueType(), RHS,
23296                                    LHS.getOperand(1));
23297         return DAG.getSetCC(SDLoc(N), N->getValueType(0), addV,
23298                             DAG.getConstant(0, addV.getValueType()), CC);
23299       }
23300   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23301     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23302       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23303         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N), RHS.getValueType(), LHS,
23304                                    RHS.getOperand(1));
23305         return DAG.getSetCC(SDLoc(N), N->getValueType(0), addV,
23306                             DAG.getConstant(0, addV.getValueType()), CC);
23307       }
23308
23309   if (VT.getScalarType() == MVT::i1 &&
23310       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23311     bool IsSEXT0 =
23312         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23313         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23314     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23315
23316     if (!IsSEXT0 || !IsVZero1) {
23317       // Swap the operands and update the condition code.
23318       std::swap(LHS, RHS);
23319       CC = ISD::getSetCCSwappedOperands(CC);
23320
23321       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23322                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23323       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23324     }
23325
23326     if (IsSEXT0 && IsVZero1) {
23327       assert(VT == LHS.getOperand(0).getValueType() &&
23328              "Uexpected operand type");
23329       if (CC == ISD::SETGT)
23330         return DAG.getConstant(0, VT);
23331       if (CC == ISD::SETLE)
23332         return DAG.getConstant(1, VT);
23333       if (CC == ISD::SETEQ || CC == ISD::SETGE)
23334         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23335
23336       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23337              "Unexpected condition code!");
23338       return LHS.getOperand(0);
23339     }
23340   }
23341
23342   return SDValue();
23343 }
23344
23345 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23346                                          SelectionDAG &DAG) {
23347   SDLoc dl(Load);
23348   MVT VT = Load->getSimpleValueType(0);
23349   MVT EVT = VT.getVectorElementType();
23350   SDValue Addr = Load->getOperand(1);
23351   SDValue NewAddr = DAG.getNode(
23352       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23353       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
23354
23355   SDValue NewLoad =
23356       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23357                   DAG.getMachineFunction().getMachineMemOperand(
23358                       Load->getMemOperand(), 0, EVT.getStoreSize()));
23359   return NewLoad;
23360 }
23361
23362 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23363                                       const X86Subtarget *Subtarget) {
23364   SDLoc dl(N);
23365   MVT VT = N->getOperand(1)->getSimpleValueType(0);
23366   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23367          "X86insertps is only defined for v4x32");
23368
23369   SDValue Ld = N->getOperand(1);
23370   if (MayFoldLoad(Ld)) {
23371     // Extract the countS bits from the immediate so we can get the proper
23372     // address when narrowing the vector load to a specific element.
23373     // When the second source op is a memory address, insertps doesn't use
23374     // countS and just gets an f32 from that address.
23375     unsigned DestIndex =
23376         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23377
23378     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23379
23380     // Create this as a scalar to vector to match the instruction pattern.
23381     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23382     // countS bits are ignored when loading from memory on insertps, which
23383     // means we don't need to explicitly set them to 0.
23384     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23385                        LoadScalarToVector, N->getOperand(2));
23386   }
23387   return SDValue();
23388 }
23389
23390 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23391   SDValue V0 = N->getOperand(0);
23392   SDValue V1 = N->getOperand(1);
23393   SDLoc DL(N);
23394   EVT VT = N->getValueType(0);
23395
23396   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23397   // operands and changing the mask to 1. This saves us a bunch of
23398   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23399   // x86InstrInfo knows how to commute this back after instruction selection
23400   // if it would help register allocation.
23401
23402   // TODO: If optimizing for size or a processor that doesn't suffer from
23403   // partial register update stalls, this should be transformed into a MOVSD
23404   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23405
23406   if (VT == MVT::v2f64)
23407     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23408       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23409         SDValue NewMask = DAG.getConstant(1, MVT::i8);
23410         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23411       }
23412
23413   return SDValue();
23414 }
23415
23416 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23417 // as "sbb reg,reg", since it can be extended without zext and produces
23418 // an all-ones bit which is more useful than 0/1 in some cases.
23419 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23420                                MVT VT) {
23421   if (VT == MVT::i8)
23422     return DAG.getNode(ISD::AND, DL, VT,
23423                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23424                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
23425                        DAG.getConstant(1, VT));
23426   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23427   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23428                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23429                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
23430 }
23431
23432 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23433 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23434                                    TargetLowering::DAGCombinerInfo &DCI,
23435                                    const X86Subtarget *Subtarget) {
23436   SDLoc DL(N);
23437   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23438   SDValue EFLAGS = N->getOperand(1);
23439
23440   if (CC == X86::COND_A) {
23441     // Try to convert COND_A into COND_B in an attempt to facilitate
23442     // materializing "setb reg".
23443     //
23444     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23445     // cannot take an immediate as its first operand.
23446     //
23447     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23448         EFLAGS.getValueType().isInteger() &&
23449         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23450       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23451                                    EFLAGS.getNode()->getVTList(),
23452                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23453       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23454       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23455     }
23456   }
23457
23458   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23459   // a zext and produces an all-ones bit which is more useful than 0/1 in some
23460   // cases.
23461   if (CC == X86::COND_B)
23462     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23463
23464   SDValue Flags;
23465
23466   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23467   if (Flags.getNode()) {
23468     SDValue Cond = DAG.getConstant(CC, MVT::i8);
23469     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23470   }
23471
23472   return SDValue();
23473 }
23474
23475 // Optimize branch condition evaluation.
23476 //
23477 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23478                                     TargetLowering::DAGCombinerInfo &DCI,
23479                                     const X86Subtarget *Subtarget) {
23480   SDLoc DL(N);
23481   SDValue Chain = N->getOperand(0);
23482   SDValue Dest = N->getOperand(1);
23483   SDValue EFLAGS = N->getOperand(3);
23484   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23485
23486   SDValue Flags;
23487
23488   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23489   if (Flags.getNode()) {
23490     SDValue Cond = DAG.getConstant(CC, MVT::i8);
23491     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23492                        Flags);
23493   }
23494
23495   return SDValue();
23496 }
23497
23498 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23499                                                          SelectionDAG &DAG) {
23500   // Take advantage of vector comparisons producing 0 or -1 in each lane to
23501   // optimize away operation when it's from a constant.
23502   //
23503   // The general transformation is:
23504   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23505   //       AND(VECTOR_CMP(x,y), constant2)
23506   //    constant2 = UNARYOP(constant)
23507
23508   // Early exit if this isn't a vector operation, the operand of the
23509   // unary operation isn't a bitwise AND, or if the sizes of the operations
23510   // aren't the same.
23511   EVT VT = N->getValueType(0);
23512   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23513       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23514       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23515     return SDValue();
23516
23517   // Now check that the other operand of the AND is a constant. We could
23518   // make the transformation for non-constant splats as well, but it's unclear
23519   // that would be a benefit as it would not eliminate any operations, just
23520   // perform one more step in scalar code before moving to the vector unit.
23521   if (BuildVectorSDNode *BV =
23522           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23523     // Bail out if the vector isn't a constant.
23524     if (!BV->isConstant())
23525       return SDValue();
23526
23527     // Everything checks out. Build up the new and improved node.
23528     SDLoc DL(N);
23529     EVT IntVT = BV->getValueType(0);
23530     // Create a new constant of the appropriate type for the transformed
23531     // DAG.
23532     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23533     // The AND node needs bitcasts to/from an integer vector type around it.
23534     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23535     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23536                                  N->getOperand(0)->getOperand(0), MaskConst);
23537     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23538     return Res;
23539   }
23540
23541   return SDValue();
23542 }
23543
23544 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23545                                         const X86Subtarget *Subtarget) {
23546   // First try to optimize away the conversion entirely when it's
23547   // conditionally from a constant. Vectors only.
23548   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
23549   if (Res != SDValue())
23550     return Res;
23551
23552   // Now move on to more general possibilities.
23553   SDValue Op0 = N->getOperand(0);
23554   EVT InVT = Op0->getValueType(0);
23555
23556   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
23557   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
23558     SDLoc dl(N);
23559     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
23560     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
23561     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
23562   }
23563
23564   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
23565   // a 32-bit target where SSE doesn't support i64->FP operations.
23566   if (Op0.getOpcode() == ISD::LOAD) {
23567     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
23568     EVT VT = Ld->getValueType(0);
23569     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
23570         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
23571         !Subtarget->is64Bit() && VT == MVT::i64) {
23572       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
23573           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
23574       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
23575       return FILDChain;
23576     }
23577   }
23578   return SDValue();
23579 }
23580
23581 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
23582 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
23583                                  X86TargetLowering::DAGCombinerInfo &DCI) {
23584   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
23585   // the result is either zero or one (depending on the input carry bit).
23586   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
23587   if (X86::isZeroNode(N->getOperand(0)) &&
23588       X86::isZeroNode(N->getOperand(1)) &&
23589       // We don't have a good way to replace an EFLAGS use, so only do this when
23590       // dead right now.
23591       SDValue(N, 1).use_empty()) {
23592     SDLoc DL(N);
23593     EVT VT = N->getValueType(0);
23594     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
23595     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
23596                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
23597                                            DAG.getConstant(X86::COND_B,MVT::i8),
23598                                            N->getOperand(2)),
23599                                DAG.getConstant(1, VT));
23600     return DCI.CombineTo(N, Res1, CarryOut);
23601   }
23602
23603   return SDValue();
23604 }
23605
23606 // fold (add Y, (sete  X, 0)) -> adc  0, Y
23607 //      (add Y, (setne X, 0)) -> sbb -1, Y
23608 //      (sub (sete  X, 0), Y) -> sbb  0, Y
23609 //      (sub (setne X, 0), Y) -> adc -1, Y
23610 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
23611   SDLoc DL(N);
23612
23613   // Look through ZExts.
23614   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23615   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23616     return SDValue();
23617
23618   SDValue SetCC = Ext.getOperand(0);
23619   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23620     return SDValue();
23621
23622   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23623   if (CC != X86::COND_E && CC != X86::COND_NE)
23624     return SDValue();
23625
23626   SDValue Cmp = SetCC.getOperand(1);
23627   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23628       !X86::isZeroNode(Cmp.getOperand(1)) ||
23629       !Cmp.getOperand(0).getValueType().isInteger())
23630     return SDValue();
23631
23632   SDValue CmpOp0 = Cmp.getOperand(0);
23633   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23634                                DAG.getConstant(1, CmpOp0.getValueType()));
23635
23636   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23637   if (CC == X86::COND_NE)
23638     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23639                        DL, OtherVal.getValueType(), OtherVal,
23640                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23641   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23642                      DL, OtherVal.getValueType(), OtherVal,
23643                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23644 }
23645
23646 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23647 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23648                                  const X86Subtarget *Subtarget) {
23649   EVT VT = N->getValueType(0);
23650   SDValue Op0 = N->getOperand(0);
23651   SDValue Op1 = N->getOperand(1);
23652
23653   // Try to synthesize horizontal adds from adds of shuffles.
23654   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23655        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23656       isHorizontalBinOp(Op0, Op1, true))
23657     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23658
23659   return OptimizeConditionalInDecrement(N, DAG);
23660 }
23661
23662 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23663                                  const X86Subtarget *Subtarget) {
23664   SDValue Op0 = N->getOperand(0);
23665   SDValue Op1 = N->getOperand(1);
23666
23667   // X86 can't encode an immediate LHS of a sub. See if we can push the
23668   // negation into a preceding instruction.
23669   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23670     // If the RHS of the sub is a XOR with one use and a constant, invert the
23671     // immediate. Then add one to the LHS of the sub so we can turn
23672     // X-Y -> X+~Y+1, saving one register.
23673     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23674         isa<ConstantSDNode>(Op1.getOperand(1))) {
23675       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23676       EVT VT = Op0.getValueType();
23677       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23678                                    Op1.getOperand(0),
23679                                    DAG.getConstant(~XorC, VT));
23680       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23681                          DAG.getConstant(C->getAPIntValue()+1, VT));
23682     }
23683   }
23684
23685   // Try to synthesize horizontal adds from adds of shuffles.
23686   EVT VT = N->getValueType(0);
23687   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23688        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23689       isHorizontalBinOp(Op0, Op1, true))
23690     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23691
23692   return OptimizeConditionalInDecrement(N, DAG);
23693 }
23694
23695 /// performVZEXTCombine - Performs build vector combines
23696 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23697                                    TargetLowering::DAGCombinerInfo &DCI,
23698                                    const X86Subtarget *Subtarget) {
23699   SDLoc DL(N);
23700   MVT VT = N->getSimpleValueType(0);
23701   SDValue Op = N->getOperand(0);
23702   MVT OpVT = Op.getSimpleValueType();
23703   MVT OpEltVT = OpVT.getVectorElementType();
23704   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
23705
23706   // (vzext (bitcast (vzext (x)) -> (vzext x)
23707   SDValue V = Op;
23708   while (V.getOpcode() == ISD::BITCAST)
23709     V = V.getOperand(0);
23710
23711   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
23712     MVT InnerVT = V.getSimpleValueType();
23713     MVT InnerEltVT = InnerVT.getVectorElementType();
23714
23715     // If the element sizes match exactly, we can just do one larger vzext. This
23716     // is always an exact type match as vzext operates on integer types.
23717     if (OpEltVT == InnerEltVT) {
23718       assert(OpVT == InnerVT && "Types must match for vzext!");
23719       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
23720     }
23721
23722     // The only other way we can combine them is if only a single element of the
23723     // inner vzext is used in the input to the outer vzext.
23724     if (InnerEltVT.getSizeInBits() < InputBits)
23725       return SDValue();
23726
23727     // In this case, the inner vzext is completely dead because we're going to
23728     // only look at bits inside of the low element. Just do the outer vzext on
23729     // a bitcast of the input to the inner.
23730     return DAG.getNode(X86ISD::VZEXT, DL, VT,
23731                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
23732   }
23733
23734   // Check if we can bypass extracting and re-inserting an element of an input
23735   // vector. Essentialy:
23736   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
23737   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
23738       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
23739       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
23740     SDValue ExtractedV = V.getOperand(0);
23741     SDValue OrigV = ExtractedV.getOperand(0);
23742     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
23743       if (ExtractIdx->getZExtValue() == 0) {
23744         MVT OrigVT = OrigV.getSimpleValueType();
23745         // Extract a subvector if necessary...
23746         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
23747           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
23748           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
23749                                     OrigVT.getVectorNumElements() / Ratio);
23750           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
23751                               DAG.getIntPtrConstant(0));
23752         }
23753         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
23754         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
23755       }
23756   }
23757
23758   return SDValue();
23759 }
23760
23761 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
23762                                              DAGCombinerInfo &DCI) const {
23763   SelectionDAG &DAG = DCI.DAG;
23764   switch (N->getOpcode()) {
23765   default: break;
23766   case ISD::EXTRACT_VECTOR_ELT:
23767     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23768   case ISD::VSELECT:
23769   case ISD::SELECT:
23770   case X86ISD::SHRUNKBLEND:
23771     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23772   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
23773   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23774   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
23775   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
23776   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
23777   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
23778   case ISD::SHL:
23779   case ISD::SRA:
23780   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
23781   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
23782   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
23783   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
23784   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
23785   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
23786   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
23787   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
23788   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
23789   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
23790   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
23791   case X86ISD::FXOR:
23792   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
23793   case X86ISD::FMIN:
23794   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
23795   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
23796   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
23797   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
23798   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
23799   case ISD::ANY_EXTEND:
23800   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
23801   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
23802   case ISD::SIGN_EXTEND_INREG:
23803     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23804   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23805   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
23806   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23807   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23808   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
23809   case X86ISD::SHUFP:       // Handle all target specific shuffles
23810   case X86ISD::PALIGNR:
23811   case X86ISD::UNPCKH:
23812   case X86ISD::UNPCKL:
23813   case X86ISD::MOVHLPS:
23814   case X86ISD::MOVLHPS:
23815   case X86ISD::PSHUFB:
23816   case X86ISD::PSHUFD:
23817   case X86ISD::PSHUFHW:
23818   case X86ISD::PSHUFLW:
23819   case X86ISD::MOVSS:
23820   case X86ISD::MOVSD:
23821   case X86ISD::VPERMILPI:
23822   case X86ISD::VPERM2X128:
23823   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23824   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
23825   case ISD::INTRINSIC_WO_CHAIN:
23826     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23827   case X86ISD::INSERTPS: {
23828     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
23829       return PerformINSERTPSCombine(N, DAG, Subtarget);
23830     break;
23831   }
23832   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
23833   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23834   }
23835
23836   return SDValue();
23837 }
23838
23839 /// isTypeDesirableForOp - Return true if the target has native support for
23840 /// the specified value type and it is 'desirable' to use the type for the
23841 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23842 /// instruction encodings are longer and some i16 instructions are slow.
23843 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23844   if (!isTypeLegal(VT))
23845     return false;
23846   if (VT != MVT::i16)
23847     return true;
23848
23849   switch (Opc) {
23850   default:
23851     return true;
23852   case ISD::LOAD:
23853   case ISD::SIGN_EXTEND:
23854   case ISD::ZERO_EXTEND:
23855   case ISD::ANY_EXTEND:
23856   case ISD::SHL:
23857   case ISD::SRL:
23858   case ISD::SUB:
23859   case ISD::ADD:
23860   case ISD::MUL:
23861   case ISD::AND:
23862   case ISD::OR:
23863   case ISD::XOR:
23864     return false;
23865   }
23866 }
23867
23868 /// IsDesirableToPromoteOp - This method query the target whether it is
23869 /// beneficial for dag combiner to promote the specified node. If true, it
23870 /// should return the desired promotion type by reference.
23871 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
23872   EVT VT = Op.getValueType();
23873   if (VT != MVT::i16)
23874     return false;
23875
23876   bool Promote = false;
23877   bool Commute = false;
23878   switch (Op.getOpcode()) {
23879   default: break;
23880   case ISD::LOAD: {
23881     LoadSDNode *LD = cast<LoadSDNode>(Op);
23882     // If the non-extending load has a single use and it's not live out, then it
23883     // might be folded.
23884     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
23885                                                      Op.hasOneUse()*/) {
23886       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
23887              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
23888         // The only case where we'd want to promote LOAD (rather then it being
23889         // promoted as an operand is when it's only use is liveout.
23890         if (UI->getOpcode() != ISD::CopyToReg)
23891           return false;
23892       }
23893     }
23894     Promote = true;
23895     break;
23896   }
23897   case ISD::SIGN_EXTEND:
23898   case ISD::ZERO_EXTEND:
23899   case ISD::ANY_EXTEND:
23900     Promote = true;
23901     break;
23902   case ISD::SHL:
23903   case ISD::SRL: {
23904     SDValue N0 = Op.getOperand(0);
23905     // Look out for (store (shl (load), x)).
23906     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
23907       return false;
23908     Promote = true;
23909     break;
23910   }
23911   case ISD::ADD:
23912   case ISD::MUL:
23913   case ISD::AND:
23914   case ISD::OR:
23915   case ISD::XOR:
23916     Commute = true;
23917     // fallthrough
23918   case ISD::SUB: {
23919     SDValue N0 = Op.getOperand(0);
23920     SDValue N1 = Op.getOperand(1);
23921     if (!Commute && MayFoldLoad(N1))
23922       return false;
23923     // Avoid disabling potential load folding opportunities.
23924     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23925       return false;
23926     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23927       return false;
23928     Promote = true;
23929   }
23930   }
23931
23932   PVT = MVT::i32;
23933   return Promote;
23934 }
23935
23936 //===----------------------------------------------------------------------===//
23937 //                           X86 Inline Assembly Support
23938 //===----------------------------------------------------------------------===//
23939
23940 // Helper to match a string separated by whitespace.
23941 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
23942   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
23943
23944   for (StringRef Piece : Pieces) {
23945     if (!S.startswith(Piece)) // Check if the piece matches.
23946       return false;
23947
23948     S = S.substr(Piece.size());
23949     StringRef::size_type Pos = S.find_first_not_of(" \t");
23950     if (Pos == 0) // We matched a prefix.
23951       return false;
23952
23953     S = S.substr(Pos);
23954   }
23955
23956   return S.empty();
23957 }
23958
23959 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
23960
23961   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
23962     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
23963         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
23964         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
23965
23966       if (AsmPieces.size() == 3)
23967         return true;
23968       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
23969         return true;
23970     }
23971   }
23972   return false;
23973 }
23974
23975 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23976   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23977
23978   std::string AsmStr = IA->getAsmString();
23979
23980   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23981   if (!Ty || Ty->getBitWidth() % 16 != 0)
23982     return false;
23983
23984   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23985   SmallVector<StringRef, 4> AsmPieces;
23986   SplitString(AsmStr, AsmPieces, ";\n");
23987
23988   switch (AsmPieces.size()) {
23989   default: return false;
23990   case 1:
23991     // FIXME: this should verify that we are targeting a 486 or better.  If not,
23992     // we will turn this bswap into something that will be lowered to logical
23993     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
23994     // lower so don't worry about this.
23995     // bswap $0
23996     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
23997         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
23998         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
23999         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24000         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24001         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24002       // No need to check constraints, nothing other than the equivalent of
24003       // "=r,0" would be valid here.
24004       return IntrinsicLowering::LowerToByteSwap(CI);
24005     }
24006
24007     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24008     if (CI->getType()->isIntegerTy(16) &&
24009         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24010         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24011          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24012       AsmPieces.clear();
24013       const std::string &ConstraintsStr = IA->getConstraintString();
24014       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24015       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24016       if (clobbersFlagRegisters(AsmPieces))
24017         return IntrinsicLowering::LowerToByteSwap(CI);
24018     }
24019     break;
24020   case 3:
24021     if (CI->getType()->isIntegerTy(32) &&
24022         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24023         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24024         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24025         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24026       AsmPieces.clear();
24027       const std::string &ConstraintsStr = IA->getConstraintString();
24028       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24029       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24030       if (clobbersFlagRegisters(AsmPieces))
24031         return IntrinsicLowering::LowerToByteSwap(CI);
24032     }
24033
24034     if (CI->getType()->isIntegerTy(64)) {
24035       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24036       if (Constraints.size() >= 2 &&
24037           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24038           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24039         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24040         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24041             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24042             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24043           return IntrinsicLowering::LowerToByteSwap(CI);
24044       }
24045     }
24046     break;
24047   }
24048   return false;
24049 }
24050
24051 /// getConstraintType - Given a constraint letter, return the type of
24052 /// constraint it is for this target.
24053 X86TargetLowering::ConstraintType
24054 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24055   if (Constraint.size() == 1) {
24056     switch (Constraint[0]) {
24057     case 'R':
24058     case 'q':
24059     case 'Q':
24060     case 'f':
24061     case 't':
24062     case 'u':
24063     case 'y':
24064     case 'x':
24065     case 'Y':
24066     case 'l':
24067       return C_RegisterClass;
24068     case 'a':
24069     case 'b':
24070     case 'c':
24071     case 'd':
24072     case 'S':
24073     case 'D':
24074     case 'A':
24075       return C_Register;
24076     case 'I':
24077     case 'J':
24078     case 'K':
24079     case 'L':
24080     case 'M':
24081     case 'N':
24082     case 'G':
24083     case 'C':
24084     case 'e':
24085     case 'Z':
24086       return C_Other;
24087     default:
24088       break;
24089     }
24090   }
24091   return TargetLowering::getConstraintType(Constraint);
24092 }
24093
24094 /// Examine constraint type and operand type and determine a weight value.
24095 /// This object must already have been set up with the operand type
24096 /// and the current alternative constraint selected.
24097 TargetLowering::ConstraintWeight
24098   X86TargetLowering::getSingleConstraintMatchWeight(
24099     AsmOperandInfo &info, const char *constraint) const {
24100   ConstraintWeight weight = CW_Invalid;
24101   Value *CallOperandVal = info.CallOperandVal;
24102     // If we don't have a value, we can't do a match,
24103     // but allow it at the lowest weight.
24104   if (!CallOperandVal)
24105     return CW_Default;
24106   Type *type = CallOperandVal->getType();
24107   // Look at the constraint type.
24108   switch (*constraint) {
24109   default:
24110     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24111   case 'R':
24112   case 'q':
24113   case 'Q':
24114   case 'a':
24115   case 'b':
24116   case 'c':
24117   case 'd':
24118   case 'S':
24119   case 'D':
24120   case 'A':
24121     if (CallOperandVal->getType()->isIntegerTy())
24122       weight = CW_SpecificReg;
24123     break;
24124   case 'f':
24125   case 't':
24126   case 'u':
24127     if (type->isFloatingPointTy())
24128       weight = CW_SpecificReg;
24129     break;
24130   case 'y':
24131     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24132       weight = CW_SpecificReg;
24133     break;
24134   case 'x':
24135   case 'Y':
24136     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24137         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24138       weight = CW_Register;
24139     break;
24140   case 'I':
24141     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24142       if (C->getZExtValue() <= 31)
24143         weight = CW_Constant;
24144     }
24145     break;
24146   case 'J':
24147     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24148       if (C->getZExtValue() <= 63)
24149         weight = CW_Constant;
24150     }
24151     break;
24152   case 'K':
24153     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24154       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24155         weight = CW_Constant;
24156     }
24157     break;
24158   case 'L':
24159     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24160       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24161         weight = CW_Constant;
24162     }
24163     break;
24164   case 'M':
24165     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24166       if (C->getZExtValue() <= 3)
24167         weight = CW_Constant;
24168     }
24169     break;
24170   case 'N':
24171     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24172       if (C->getZExtValue() <= 0xff)
24173         weight = CW_Constant;
24174     }
24175     break;
24176   case 'G':
24177   case 'C':
24178     if (dyn_cast<ConstantFP>(CallOperandVal)) {
24179       weight = CW_Constant;
24180     }
24181     break;
24182   case 'e':
24183     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24184       if ((C->getSExtValue() >= -0x80000000LL) &&
24185           (C->getSExtValue() <= 0x7fffffffLL))
24186         weight = CW_Constant;
24187     }
24188     break;
24189   case 'Z':
24190     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24191       if (C->getZExtValue() <= 0xffffffff)
24192         weight = CW_Constant;
24193     }
24194     break;
24195   }
24196   return weight;
24197 }
24198
24199 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24200 /// with another that has more specific requirements based on the type of the
24201 /// corresponding operand.
24202 const char *X86TargetLowering::
24203 LowerXConstraint(EVT ConstraintVT) const {
24204   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24205   // 'f' like normal targets.
24206   if (ConstraintVT.isFloatingPoint()) {
24207     if (Subtarget->hasSSE2())
24208       return "Y";
24209     if (Subtarget->hasSSE1())
24210       return "x";
24211   }
24212
24213   return TargetLowering::LowerXConstraint(ConstraintVT);
24214 }
24215
24216 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24217 /// vector.  If it is invalid, don't add anything to Ops.
24218 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24219                                                      std::string &Constraint,
24220                                                      std::vector<SDValue>&Ops,
24221                                                      SelectionDAG &DAG) const {
24222   SDValue Result;
24223
24224   // Only support length 1 constraints for now.
24225   if (Constraint.length() > 1) return;
24226
24227   char ConstraintLetter = Constraint[0];
24228   switch (ConstraintLetter) {
24229   default: break;
24230   case 'I':
24231     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24232       if (C->getZExtValue() <= 31) {
24233         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24234         break;
24235       }
24236     }
24237     return;
24238   case 'J':
24239     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24240       if (C->getZExtValue() <= 63) {
24241         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24242         break;
24243       }
24244     }
24245     return;
24246   case 'K':
24247     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24248       if (isInt<8>(C->getSExtValue())) {
24249         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24250         break;
24251       }
24252     }
24253     return;
24254   case 'L':
24255     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24256       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24257           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24258         Result = DAG.getTargetConstant(C->getSExtValue(), Op.getValueType());
24259         break;
24260       }
24261     }
24262     return;
24263   case 'M':
24264     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24265       if (C->getZExtValue() <= 3) {
24266         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24267         break;
24268       }
24269     }
24270     return;
24271   case 'N':
24272     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24273       if (C->getZExtValue() <= 255) {
24274         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24275         break;
24276       }
24277     }
24278     return;
24279   case 'O':
24280     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24281       if (C->getZExtValue() <= 127) {
24282         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24283         break;
24284       }
24285     }
24286     return;
24287   case 'e': {
24288     // 32-bit signed value
24289     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24290       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24291                                            C->getSExtValue())) {
24292         // Widen to 64 bits here to get it sign extended.
24293         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
24294         break;
24295       }
24296     // FIXME gcc accepts some relocatable values here too, but only in certain
24297     // memory models; it's complicated.
24298     }
24299     return;
24300   }
24301   case 'Z': {
24302     // 32-bit unsigned value
24303     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24304       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24305                                            C->getZExtValue())) {
24306         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24307         break;
24308       }
24309     }
24310     // FIXME gcc accepts some relocatable values here too, but only in certain
24311     // memory models; it's complicated.
24312     return;
24313   }
24314   case 'i': {
24315     // Literal immediates are always ok.
24316     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24317       // Widen to 64 bits here to get it sign extended.
24318       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
24319       break;
24320     }
24321
24322     // In any sort of PIC mode addresses need to be computed at runtime by
24323     // adding in a register or some sort of table lookup.  These can't
24324     // be used as immediates.
24325     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24326       return;
24327
24328     // If we are in non-pic codegen mode, we allow the address of a global (with
24329     // an optional displacement) to be used with 'i'.
24330     GlobalAddressSDNode *GA = nullptr;
24331     int64_t Offset = 0;
24332
24333     // Match either (GA), (GA+C), (GA+C1+C2), etc.
24334     while (1) {
24335       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24336         Offset += GA->getOffset();
24337         break;
24338       } else if (Op.getOpcode() == ISD::ADD) {
24339         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24340           Offset += C->getZExtValue();
24341           Op = Op.getOperand(0);
24342           continue;
24343         }
24344       } else if (Op.getOpcode() == ISD::SUB) {
24345         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24346           Offset += -C->getZExtValue();
24347           Op = Op.getOperand(0);
24348           continue;
24349         }
24350       }
24351
24352       // Otherwise, this isn't something we can handle, reject it.
24353       return;
24354     }
24355
24356     const GlobalValue *GV = GA->getGlobal();
24357     // If we require an extra load to get this address, as in PIC mode, we
24358     // can't accept it.
24359     if (isGlobalStubReference(
24360             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24361       return;
24362
24363     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24364                                         GA->getValueType(0), Offset);
24365     break;
24366   }
24367   }
24368
24369   if (Result.getNode()) {
24370     Ops.push_back(Result);
24371     return;
24372   }
24373   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24374 }
24375
24376 std::pair<unsigned, const TargetRegisterClass *>
24377 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24378                                                 const std::string &Constraint,
24379                                                 MVT VT) const {
24380   // First, see if this is a constraint that directly corresponds to an LLVM
24381   // register class.
24382   if (Constraint.size() == 1) {
24383     // GCC Constraint Letters
24384     switch (Constraint[0]) {
24385     default: break;
24386       // TODO: Slight differences here in allocation order and leaving
24387       // RIP in the class. Do they matter any more here than they do
24388       // in the normal allocation?
24389     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24390       if (Subtarget->is64Bit()) {
24391         if (VT == MVT::i32 || VT == MVT::f32)
24392           return std::make_pair(0U, &X86::GR32RegClass);
24393         if (VT == MVT::i16)
24394           return std::make_pair(0U, &X86::GR16RegClass);
24395         if (VT == MVT::i8 || VT == MVT::i1)
24396           return std::make_pair(0U, &X86::GR8RegClass);
24397         if (VT == MVT::i64 || VT == MVT::f64)
24398           return std::make_pair(0U, &X86::GR64RegClass);
24399         break;
24400       }
24401       // 32-bit fallthrough
24402     case 'Q':   // Q_REGS
24403       if (VT == MVT::i32 || VT == MVT::f32)
24404         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24405       if (VT == MVT::i16)
24406         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24407       if (VT == MVT::i8 || VT == MVT::i1)
24408         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24409       if (VT == MVT::i64)
24410         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24411       break;
24412     case 'r':   // GENERAL_REGS
24413     case 'l':   // INDEX_REGS
24414       if (VT == MVT::i8 || VT == MVT::i1)
24415         return std::make_pair(0U, &X86::GR8RegClass);
24416       if (VT == MVT::i16)
24417         return std::make_pair(0U, &X86::GR16RegClass);
24418       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24419         return std::make_pair(0U, &X86::GR32RegClass);
24420       return std::make_pair(0U, &X86::GR64RegClass);
24421     case 'R':   // LEGACY_REGS
24422       if (VT == MVT::i8 || VT == MVT::i1)
24423         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24424       if (VT == MVT::i16)
24425         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24426       if (VT == MVT::i32 || !Subtarget->is64Bit())
24427         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24428       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24429     case 'f':  // FP Stack registers.
24430       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24431       // value to the correct fpstack register class.
24432       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24433         return std::make_pair(0U, &X86::RFP32RegClass);
24434       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24435         return std::make_pair(0U, &X86::RFP64RegClass);
24436       return std::make_pair(0U, &X86::RFP80RegClass);
24437     case 'y':   // MMX_REGS if MMX allowed.
24438       if (!Subtarget->hasMMX()) break;
24439       return std::make_pair(0U, &X86::VR64RegClass);
24440     case 'Y':   // SSE_REGS if SSE2 allowed
24441       if (!Subtarget->hasSSE2()) break;
24442       // FALL THROUGH.
24443     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24444       if (!Subtarget->hasSSE1()) break;
24445
24446       switch (VT.SimpleTy) {
24447       default: break;
24448       // Scalar SSE types.
24449       case MVT::f32:
24450       case MVT::i32:
24451         return std::make_pair(0U, &X86::FR32RegClass);
24452       case MVT::f64:
24453       case MVT::i64:
24454         return std::make_pair(0U, &X86::FR64RegClass);
24455       // Vector types.
24456       case MVT::v16i8:
24457       case MVT::v8i16:
24458       case MVT::v4i32:
24459       case MVT::v2i64:
24460       case MVT::v4f32:
24461       case MVT::v2f64:
24462         return std::make_pair(0U, &X86::VR128RegClass);
24463       // AVX types.
24464       case MVT::v32i8:
24465       case MVT::v16i16:
24466       case MVT::v8i32:
24467       case MVT::v4i64:
24468       case MVT::v8f32:
24469       case MVT::v4f64:
24470         return std::make_pair(0U, &X86::VR256RegClass);
24471       case MVT::v8f64:
24472       case MVT::v16f32:
24473       case MVT::v16i32:
24474       case MVT::v8i64:
24475         return std::make_pair(0U, &X86::VR512RegClass);
24476       }
24477       break;
24478     }
24479   }
24480
24481   // Use the default implementation in TargetLowering to convert the register
24482   // constraint into a member of a register class.
24483   std::pair<unsigned, const TargetRegisterClass*> Res;
24484   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24485
24486   // Not found as a standard register?
24487   if (!Res.second) {
24488     // Map st(0) -> st(7) -> ST0
24489     if (Constraint.size() == 7 && Constraint[0] == '{' &&
24490         tolower(Constraint[1]) == 's' &&
24491         tolower(Constraint[2]) == 't' &&
24492         Constraint[3] == '(' &&
24493         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24494         Constraint[5] == ')' &&
24495         Constraint[6] == '}') {
24496
24497       Res.first = X86::FP0+Constraint[4]-'0';
24498       Res.second = &X86::RFP80RegClass;
24499       return Res;
24500     }
24501
24502     // GCC allows "st(0)" to be called just plain "st".
24503     if (StringRef("{st}").equals_lower(Constraint)) {
24504       Res.first = X86::FP0;
24505       Res.second = &X86::RFP80RegClass;
24506       return Res;
24507     }
24508
24509     // flags -> EFLAGS
24510     if (StringRef("{flags}").equals_lower(Constraint)) {
24511       Res.first = X86::EFLAGS;
24512       Res.second = &X86::CCRRegClass;
24513       return Res;
24514     }
24515
24516     // 'A' means EAX + EDX.
24517     if (Constraint == "A") {
24518       Res.first = X86::EAX;
24519       Res.second = &X86::GR32_ADRegClass;
24520       return Res;
24521     }
24522     return Res;
24523   }
24524
24525   // Otherwise, check to see if this is a register class of the wrong value
24526   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24527   // turn into {ax},{dx}.
24528   if (Res.second->hasType(VT))
24529     return Res;   // Correct type already, nothing to do.
24530
24531   // All of the single-register GCC register classes map their values onto
24532   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
24533   // really want an 8-bit or 32-bit register, map to the appropriate register
24534   // class and return the appropriate register.
24535   if (Res.second == &X86::GR16RegClass) {
24536     if (VT == MVT::i8 || VT == MVT::i1) {
24537       unsigned DestReg = 0;
24538       switch (Res.first) {
24539       default: break;
24540       case X86::AX: DestReg = X86::AL; break;
24541       case X86::DX: DestReg = X86::DL; break;
24542       case X86::CX: DestReg = X86::CL; break;
24543       case X86::BX: DestReg = X86::BL; break;
24544       }
24545       if (DestReg) {
24546         Res.first = DestReg;
24547         Res.second = &X86::GR8RegClass;
24548       }
24549     } else if (VT == MVT::i32 || VT == MVT::f32) {
24550       unsigned DestReg = 0;
24551       switch (Res.first) {
24552       default: break;
24553       case X86::AX: DestReg = X86::EAX; break;
24554       case X86::DX: DestReg = X86::EDX; break;
24555       case X86::CX: DestReg = X86::ECX; break;
24556       case X86::BX: DestReg = X86::EBX; break;
24557       case X86::SI: DestReg = X86::ESI; break;
24558       case X86::DI: DestReg = X86::EDI; break;
24559       case X86::BP: DestReg = X86::EBP; break;
24560       case X86::SP: DestReg = X86::ESP; break;
24561       }
24562       if (DestReg) {
24563         Res.first = DestReg;
24564         Res.second = &X86::GR32RegClass;
24565       }
24566     } else if (VT == MVT::i64 || VT == MVT::f64) {
24567       unsigned DestReg = 0;
24568       switch (Res.first) {
24569       default: break;
24570       case X86::AX: DestReg = X86::RAX; break;
24571       case X86::DX: DestReg = X86::RDX; break;
24572       case X86::CX: DestReg = X86::RCX; break;
24573       case X86::BX: DestReg = X86::RBX; break;
24574       case X86::SI: DestReg = X86::RSI; break;
24575       case X86::DI: DestReg = X86::RDI; break;
24576       case X86::BP: DestReg = X86::RBP; break;
24577       case X86::SP: DestReg = X86::RSP; break;
24578       }
24579       if (DestReg) {
24580         Res.first = DestReg;
24581         Res.second = &X86::GR64RegClass;
24582       }
24583     }
24584   } else if (Res.second == &X86::FR32RegClass ||
24585              Res.second == &X86::FR64RegClass ||
24586              Res.second == &X86::VR128RegClass ||
24587              Res.second == &X86::VR256RegClass ||
24588              Res.second == &X86::FR32XRegClass ||
24589              Res.second == &X86::FR64XRegClass ||
24590              Res.second == &X86::VR128XRegClass ||
24591              Res.second == &X86::VR256XRegClass ||
24592              Res.second == &X86::VR512RegClass) {
24593     // Handle references to XMM physical registers that got mapped into the
24594     // wrong class.  This can happen with constraints like {xmm0} where the
24595     // target independent register mapper will just pick the first match it can
24596     // find, ignoring the required type.
24597
24598     if (VT == MVT::f32 || VT == MVT::i32)
24599       Res.second = &X86::FR32RegClass;
24600     else if (VT == MVT::f64 || VT == MVT::i64)
24601       Res.second = &X86::FR64RegClass;
24602     else if (X86::VR128RegClass.hasType(VT))
24603       Res.second = &X86::VR128RegClass;
24604     else if (X86::VR256RegClass.hasType(VT))
24605       Res.second = &X86::VR256RegClass;
24606     else if (X86::VR512RegClass.hasType(VT))
24607       Res.second = &X86::VR512RegClass;
24608   }
24609
24610   return Res;
24611 }
24612
24613 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
24614                                             Type *Ty) const {
24615   // Scaling factors are not free at all.
24616   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
24617   // will take 2 allocations in the out of order engine instead of 1
24618   // for plain addressing mode, i.e. inst (reg1).
24619   // E.g.,
24620   // vaddps (%rsi,%drx), %ymm0, %ymm1
24621   // Requires two allocations (one for the load, one for the computation)
24622   // whereas:
24623   // vaddps (%rsi), %ymm0, %ymm1
24624   // Requires just 1 allocation, i.e., freeing allocations for other operations
24625   // and having less micro operations to execute.
24626   //
24627   // For some X86 architectures, this is even worse because for instance for
24628   // stores, the complex addressing mode forces the instruction to use the
24629   // "load" ports instead of the dedicated "store" port.
24630   // E.g., on Haswell:
24631   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
24632   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
24633   if (isLegalAddressingMode(AM, Ty))
24634     // Scale represents reg2 * scale, thus account for 1
24635     // as soon as we use a second register.
24636     return AM.Scale != 0;
24637   return -1;
24638 }
24639
24640 bool X86TargetLowering::isTargetFTOL() const {
24641   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
24642 }