dc5c0d1e352bd31c4517e400d089c4d91471f3d1
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
71                                      const X86Subtarget &STI)
72     : TargetLowering(TM), Subtarget(&STI) {
73   X86ScalarSSEf64 = Subtarget->hasSSE2();
74   X86ScalarSSEf32 = Subtarget->hasSSE1();
75   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
76
77   // Set up the TargetLowering object.
78   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
79
80   // X86 is weird. It always uses i8 for shift amounts and setcc results.
81   setBooleanContents(ZeroOrOneBooleanContent);
82   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
83   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
84
85   // For 64-bit, since we have so many registers, use the ILP scheduler.
86   // For 32-bit, use the register pressure specific scheduling.
87   // For Atom, always use ILP scheduling.
88   if (Subtarget->isAtom())
89     setSchedulingPreference(Sched::ILP);
90   else if (Subtarget->is64Bit())
91     setSchedulingPreference(Sched::ILP);
92   else
93     setSchedulingPreference(Sched::RegPressure);
94   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
95   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
96
97   // Bypass expensive divides on Atom when compiling with O2.
98   if (TM.getOptLevel() >= CodeGenOpt::Default) {
99     if (Subtarget->hasSlowDivide32())
100       addBypassSlowDiv(32, 8);
101     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
102       addBypassSlowDiv(64, 16);
103   }
104
105   if (Subtarget->isTargetKnownWindowsMSVC()) {
106     // Setup Windows compiler runtime calls.
107     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
108     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
109     setLibcallName(RTLIB::SREM_I64, "_allrem");
110     setLibcallName(RTLIB::UREM_I64, "_aullrem");
111     setLibcallName(RTLIB::MUL_I64, "_allmul");
112     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
113     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
114     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
115     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
116     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
117   }
118
119   if (Subtarget->isTargetDarwin()) {
120     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
121     setUseUnderscoreSetJmp(false);
122     setUseUnderscoreLongJmp(false);
123   } else if (Subtarget->isTargetWindowsGNU()) {
124     // MS runtime is weird: it exports _setjmp, but longjmp!
125     setUseUnderscoreSetJmp(true);
126     setUseUnderscoreLongJmp(false);
127   } else {
128     setUseUnderscoreSetJmp(true);
129     setUseUnderscoreLongJmp(true);
130   }
131
132   // Set up the register classes.
133   addRegisterClass(MVT::i8, &X86::GR8RegClass);
134   addRegisterClass(MVT::i16, &X86::GR16RegClass);
135   addRegisterClass(MVT::i32, &X86::GR32RegClass);
136   if (Subtarget->is64Bit())
137     addRegisterClass(MVT::i64, &X86::GR64RegClass);
138
139   for (MVT VT : MVT::integer_valuetypes())
140     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
141
142   // We don't accept any truncstore of integer registers.
143   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
144   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
145   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
146   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
147   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
148   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
149
150   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
151
152   // SETOEQ and SETUNE require checking two conditions.
153   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
154   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
155   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
156   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
157   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
158   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
159
160   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
161   // operation.
162   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
163   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
164   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
165
166   if (Subtarget->is64Bit()) {
167     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
168     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
169   } else if (!Subtarget->useSoftFloat()) {
170     // We have an algorithm for SSE2->double, and we turn this into a
171     // 64-bit FILD followed by conditional FADD for other targets.
172     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
173     // We have an algorithm for SSE2, and we turn this into a 64-bit
174     // FILD for other targets.
175     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
176   }
177
178   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
179   // this operation.
180   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
181   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
182
183   if (!Subtarget->useSoftFloat()) {
184     // SSE has no i16 to fp conversion, only i32
185     if (X86ScalarSSEf32) {
186       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
187       // f32 and f64 cases are Legal, f80 case is not
188       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
189     } else {
190       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
191       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
192     }
193   } else {
194     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
195     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
196   }
197
198   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
199   // are Legal, f80 is custom lowered.
200   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
201   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
202
203   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
204   // this operation.
205   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
206   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
207
208   if (X86ScalarSSEf32) {
209     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
210     // f32 and f64 cases are Legal, f80 case is not
211     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
212   } else {
213     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
214     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
215   }
216
217   // Handle FP_TO_UINT by promoting the destination to a larger signed
218   // conversion.
219   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
220   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
221   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
222
223   if (Subtarget->is64Bit()) {
224     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
225       // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
226       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
227       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Custom);
228     } else {
229       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
230       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Expand);
231     }
232   } else if (!Subtarget->useSoftFloat()) {
233     // Since AVX is a superset of SSE3, only check for SSE here.
234     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
235       // Expand FP_TO_UINT into a select.
236       // FIXME: We would like to use a Custom expander here eventually to do
237       // the optimal thing for SSE vs. the default expansion in the legalizer.
238       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
239     else
240       // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
241       // With SSE3 we can use fisttpll to convert to a signed i64; without
242       // SSE, we're stuck with a fistpll.
243       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
244
245     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
246   }
247
248   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
249   if (!X86ScalarSSEf64) {
250     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
251     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
252     if (Subtarget->is64Bit()) {
253       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
254       // Without SSE, i64->f64 goes through memory.
255       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
256     }
257   }
258
259   // Scalar integer divide and remainder are lowered to use operations that
260   // produce two results, to match the available instructions. This exposes
261   // the two-result form to trivial CSE, which is able to combine x/y and x%y
262   // into a single instruction.
263   //
264   // Scalar integer multiply-high is also lowered to use two-result
265   // operations, to match the available instructions. However, plain multiply
266   // (low) operations are left as Legal, as there are single-result
267   // instructions for this in x86. Using the two-result multiply instructions
268   // when both high and low results are needed must be arranged by dagcombine.
269   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
270     MVT VT = IntVTs[i];
271     setOperationAction(ISD::MULHS, VT, Expand);
272     setOperationAction(ISD::MULHU, VT, Expand);
273     setOperationAction(ISD::SDIV, VT, Expand);
274     setOperationAction(ISD::UDIV, VT, Expand);
275     setOperationAction(ISD::SREM, VT, Expand);
276     setOperationAction(ISD::UREM, VT, Expand);
277
278     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
279     setOperationAction(ISD::ADDC, VT, Custom);
280     setOperationAction(ISD::ADDE, VT, Custom);
281     setOperationAction(ISD::SUBC, VT, Custom);
282     setOperationAction(ISD::SUBE, VT, Custom);
283   }
284
285   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
286   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
287   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
288   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
289   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
290   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
291   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
292   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
293   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
294   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
295   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
296   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
297   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
298   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
299   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
300   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
301   if (Subtarget->is64Bit())
302     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
303   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
304   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
305   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
306   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
307
308   if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
309     // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
310     // is. We should promote the value to 64-bits to solve this.
311     // This is what the CRT headers do - `fmodf` is an inline header
312     // function casting to f64 and calling `fmod`.
313     setOperationAction(ISD::FREM           , MVT::f32  , Promote);
314   } else {
315     setOperationAction(ISD::FREM           , MVT::f32  , Expand);
316   }
317
318   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
319   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
320   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
321
322   // Promote the i8 variants and force them on up to i32 which has a shorter
323   // encoding.
324   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
325   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
326   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
327   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
328   if (Subtarget->hasBMI()) {
329     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
330     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
331     if (Subtarget->is64Bit())
332       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
333   } else {
334     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
335     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
336     if (Subtarget->is64Bit())
337       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
338   }
339
340   if (Subtarget->hasLZCNT()) {
341     // When promoting the i8 variants, force them to i32 for a shorter
342     // encoding.
343     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
344     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
345     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
346     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
347     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
348     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
349     if (Subtarget->is64Bit())
350       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
351   } else {
352     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
353     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
354     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
355     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
356     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
357     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
358     if (Subtarget->is64Bit()) {
359       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
360       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
361     }
362   }
363
364   // Special handling for half-precision floating point conversions.
365   // If we don't have F16C support, then lower half float conversions
366   // into library calls.
367   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
368     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
369     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
370   }
371
372   // There's never any support for operations beyond MVT::f32.
373   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
374   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
375   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
376   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
377
378   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
379   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
380   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
381   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
382   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
383   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
384
385   if (Subtarget->hasPOPCNT()) {
386     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
387   } else {
388     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
389     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
390     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
391     if (Subtarget->is64Bit())
392       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
393   }
394
395   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
396
397   if (!Subtarget->hasMOVBE())
398     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
399
400   // These should be promoted to a larger select which is supported.
401   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
402   // X86 wants to expand cmov itself.
403   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
404   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
405   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
406   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
407   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
408   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
409   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
410   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
411   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
412   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
413   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
414   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
415   if (Subtarget->is64Bit()) {
416     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
417     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
418   }
419   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
420   setOperationAction(ISD::CATCHRET        , MVT::Other, Custom);
421   setOperationAction(ISD::CLEANUPRET      , MVT::Other, Custom);
422   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
423   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
424   // support continuation, user-level threading, and etc.. As a result, no
425   // other SjLj exception interfaces are implemented and please don't build
426   // your own exception handling based on them.
427   // LLVM/Clang supports zero-cost DWARF exception handling.
428   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
429   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
430
431   // Darwin ABI issue.
432   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
433   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
434   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
435   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
436   if (Subtarget->is64Bit())
437     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
438   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
439   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
440   if (Subtarget->is64Bit()) {
441     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
442     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
443     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
444     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
445     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
446   }
447   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
448   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
449   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
450   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
451   if (Subtarget->is64Bit()) {
452     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
453     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
454     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
455   }
456
457   if (Subtarget->hasSSE1())
458     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
459
460   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
461
462   // Expand certain atomics
463   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
464     MVT VT = IntVTs[i];
465     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
466     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
467     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
468   }
469
470   if (Subtarget->hasCmpxchg16b()) {
471     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
472   }
473
474   // FIXME - use subtarget debug flags
475   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
476       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
477     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
478   }
479
480   if (Subtarget->isTarget64BitLP64()) {
481     setExceptionPointerRegister(X86::RAX);
482     setExceptionSelectorRegister(X86::RDX);
483   } else {
484     setExceptionPointerRegister(X86::EAX);
485     setExceptionSelectorRegister(X86::EDX);
486   }
487   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
488   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
489
490   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
491   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
492
493   setOperationAction(ISD::TRAP, MVT::Other, Legal);
494   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
495
496   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
497   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
498   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
499   if (Subtarget->is64Bit()) {
500     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
501     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
502   } else {
503     // TargetInfo::CharPtrBuiltinVaList
504     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
505     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
506   }
507
508   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
509   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
510
511   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
512
513   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
514   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
515   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
516
517   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
518     // f32 and f64 use SSE.
519     // Set up the FP register classes.
520     addRegisterClass(MVT::f32, &X86::FR32RegClass);
521     addRegisterClass(MVT::f64, &X86::FR64RegClass);
522
523     // Use ANDPD to simulate FABS.
524     setOperationAction(ISD::FABS , MVT::f64, Custom);
525     setOperationAction(ISD::FABS , MVT::f32, Custom);
526
527     // Use XORP to simulate FNEG.
528     setOperationAction(ISD::FNEG , MVT::f64, Custom);
529     setOperationAction(ISD::FNEG , MVT::f32, Custom);
530
531     // Use ANDPD and ORPD to simulate FCOPYSIGN.
532     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
533     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
534
535     // Lower this to FGETSIGNx86 plus an AND.
536     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
537     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
538
539     // We don't support sin/cos/fmod
540     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
541     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
542     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
543     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
544     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
545     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
546
547     // Expand FP immediates into loads from the stack, except for the special
548     // cases we handle.
549     addLegalFPImmediate(APFloat(+0.0)); // xorpd
550     addLegalFPImmediate(APFloat(+0.0f)); // xorps
551   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
552     // Use SSE for f32, x87 for f64.
553     // Set up the FP register classes.
554     addRegisterClass(MVT::f32, &X86::FR32RegClass);
555     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
556
557     // Use ANDPS to simulate FABS.
558     setOperationAction(ISD::FABS , MVT::f32, Custom);
559
560     // Use XORP to simulate FNEG.
561     setOperationAction(ISD::FNEG , MVT::f32, Custom);
562
563     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
564
565     // Use ANDPS and ORPS to simulate FCOPYSIGN.
566     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
567     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
568
569     // We don't support sin/cos/fmod
570     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
571     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
572     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
573
574     // Special cases we handle for FP constants.
575     addLegalFPImmediate(APFloat(+0.0f)); // xorps
576     addLegalFPImmediate(APFloat(+0.0)); // FLD0
577     addLegalFPImmediate(APFloat(+1.0)); // FLD1
578     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
579     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
580
581     if (!TM.Options.UnsafeFPMath) {
582       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
583       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
584       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
585     }
586   } else if (!Subtarget->useSoftFloat()) {
587     // f32 and f64 in x87.
588     // Set up the FP register classes.
589     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
590     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
591
592     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
593     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
594     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
595     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
596
597     if (!TM.Options.UnsafeFPMath) {
598       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
599       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
600       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
601       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
602       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
603       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
604     }
605     addLegalFPImmediate(APFloat(+0.0)); // FLD0
606     addLegalFPImmediate(APFloat(+1.0)); // FLD1
607     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
608     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
609     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
610     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
611     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
612     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
613   }
614
615   // We don't support FMA.
616   setOperationAction(ISD::FMA, MVT::f64, Expand);
617   setOperationAction(ISD::FMA, MVT::f32, Expand);
618
619   // Long double always uses X87.
620   if (!Subtarget->useSoftFloat()) {
621     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
622     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
623     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
624     {
625       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
626       addLegalFPImmediate(TmpFlt);  // FLD0
627       TmpFlt.changeSign();
628       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
629
630       bool ignored;
631       APFloat TmpFlt2(+1.0);
632       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
633                       &ignored);
634       addLegalFPImmediate(TmpFlt2);  // FLD1
635       TmpFlt2.changeSign();
636       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
637     }
638
639     if (!TM.Options.UnsafeFPMath) {
640       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
641       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
642       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
643     }
644
645     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
646     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
647     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
648     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
649     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
650     setOperationAction(ISD::FMA, MVT::f80, Expand);
651   }
652
653   // Always use a library call for pow.
654   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
655   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
656   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
657
658   setOperationAction(ISD::FLOG, MVT::f80, Expand);
659   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
660   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
661   setOperationAction(ISD::FEXP, MVT::f80, Expand);
662   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
663   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
664   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
665
666   // First set operation action for all vector types to either promote
667   // (for widening) or expand (for scalarization). Then we will selectively
668   // turn on ones that can be effectively codegen'd.
669   for (MVT VT : MVT::vector_valuetypes()) {
670     setOperationAction(ISD::ADD , VT, Expand);
671     setOperationAction(ISD::SUB , VT, Expand);
672     setOperationAction(ISD::FADD, VT, Expand);
673     setOperationAction(ISD::FNEG, VT, Expand);
674     setOperationAction(ISD::FSUB, VT, Expand);
675     setOperationAction(ISD::MUL , VT, Expand);
676     setOperationAction(ISD::FMUL, VT, Expand);
677     setOperationAction(ISD::SDIV, VT, Expand);
678     setOperationAction(ISD::UDIV, VT, Expand);
679     setOperationAction(ISD::FDIV, VT, Expand);
680     setOperationAction(ISD::SREM, VT, Expand);
681     setOperationAction(ISD::UREM, VT, Expand);
682     setOperationAction(ISD::LOAD, VT, Expand);
683     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
684     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
685     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
686     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
687     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
688     setOperationAction(ISD::FABS, VT, Expand);
689     setOperationAction(ISD::FSIN, VT, Expand);
690     setOperationAction(ISD::FSINCOS, VT, Expand);
691     setOperationAction(ISD::FCOS, VT, Expand);
692     setOperationAction(ISD::FSINCOS, VT, Expand);
693     setOperationAction(ISD::FREM, VT, Expand);
694     setOperationAction(ISD::FMA,  VT, Expand);
695     setOperationAction(ISD::FPOWI, VT, Expand);
696     setOperationAction(ISD::FSQRT, VT, Expand);
697     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
698     setOperationAction(ISD::FFLOOR, VT, Expand);
699     setOperationAction(ISD::FCEIL, VT, Expand);
700     setOperationAction(ISD::FTRUNC, VT, Expand);
701     setOperationAction(ISD::FRINT, VT, Expand);
702     setOperationAction(ISD::FNEARBYINT, VT, Expand);
703     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
704     setOperationAction(ISD::MULHS, VT, Expand);
705     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
706     setOperationAction(ISD::MULHU, VT, Expand);
707     setOperationAction(ISD::SDIVREM, VT, Expand);
708     setOperationAction(ISD::UDIVREM, VT, Expand);
709     setOperationAction(ISD::FPOW, VT, Expand);
710     setOperationAction(ISD::CTPOP, VT, Expand);
711     setOperationAction(ISD::CTTZ, VT, Expand);
712     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
713     setOperationAction(ISD::CTLZ, VT, Expand);
714     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
715     setOperationAction(ISD::SHL, VT, Expand);
716     setOperationAction(ISD::SRA, VT, Expand);
717     setOperationAction(ISD::SRL, VT, Expand);
718     setOperationAction(ISD::ROTL, VT, Expand);
719     setOperationAction(ISD::ROTR, VT, Expand);
720     setOperationAction(ISD::BSWAP, VT, Expand);
721     setOperationAction(ISD::SETCC, VT, Expand);
722     setOperationAction(ISD::FLOG, VT, Expand);
723     setOperationAction(ISD::FLOG2, VT, Expand);
724     setOperationAction(ISD::FLOG10, VT, Expand);
725     setOperationAction(ISD::FEXP, VT, Expand);
726     setOperationAction(ISD::FEXP2, VT, Expand);
727     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
728     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
729     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
730     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
731     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
732     setOperationAction(ISD::TRUNCATE, VT, Expand);
733     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
734     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
735     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
736     setOperationAction(ISD::VSELECT, VT, Expand);
737     setOperationAction(ISD::SELECT_CC, VT, Expand);
738     for (MVT InnerVT : MVT::vector_valuetypes()) {
739       setTruncStoreAction(InnerVT, VT, Expand);
740
741       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
742       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
743
744       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
745       // types, we have to deal with them whether we ask for Expansion or not.
746       // Setting Expand causes its own optimisation problems though, so leave
747       // them legal.
748       if (VT.getVectorElementType() == MVT::i1)
749         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
750
751       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
752       // split/scalarized right now.
753       if (VT.getVectorElementType() == MVT::f16)
754         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
755     }
756   }
757
758   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
759   // with -msoft-float, disable use of MMX as well.
760   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
761     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
762     // No operations on x86mmx supported, everything uses intrinsics.
763   }
764
765   // MMX-sized vectors (other than x86mmx) are expected to be expanded
766   // into smaller operations.
767   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
768     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
769     setOperationAction(ISD::AND,                MMXTy,      Expand);
770     setOperationAction(ISD::OR,                 MMXTy,      Expand);
771     setOperationAction(ISD::XOR,                MMXTy,      Expand);
772     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
773     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
774     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
775   }
776   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
777
778   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
779     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
780
781     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
783     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
784     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
785     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
786     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
787     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
788     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
789     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
790     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
791     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
792     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
793     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
794     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
795   }
796
797   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
798     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
799
800     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
801     // registers cannot be used even for integer operations.
802     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
803     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
804     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
805     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
806
807     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
808     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
809     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
810     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
811     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
812     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
813     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
814     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
815     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
816     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
817     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
818     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
819     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
820     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
821     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
822     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
823     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
825     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
826     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
828     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
829     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
830
831     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
832     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
833     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
834     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
835
836     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
837     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
838     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
839     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
840
841     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
842     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
843     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
844     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
845     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
846
847     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
848     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
849     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
850     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
851
852     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
853     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
854       MVT VT = (MVT::SimpleValueType)i;
855       // Do not attempt to custom lower non-power-of-2 vectors
856       if (!isPowerOf2_32(VT.getVectorNumElements()))
857         continue;
858       // Do not attempt to custom lower non-128-bit vectors
859       if (!VT.is128BitVector())
860         continue;
861       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
862       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
863       setOperationAction(ISD::VSELECT,            VT, Custom);
864       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
865     }
866
867     // We support custom legalizing of sext and anyext loads for specific
868     // memory vector types which we can load as a scalar (or sequence of
869     // scalars) and extend in-register to a legal 128-bit vector type. For sext
870     // loads these must work with a single scalar load.
871     for (MVT VT : MVT::integer_vector_valuetypes()) {
872       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
873       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
874       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
875       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
878       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
879       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
880       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
881     }
882
883     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
884     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
885     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
886     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
887     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
888     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
889     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
890     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
891
892     if (Subtarget->is64Bit()) {
893       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
894       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
895     }
896
897     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
898     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
899       MVT VT = (MVT::SimpleValueType)i;
900
901       // Do not attempt to promote non-128-bit vectors
902       if (!VT.is128BitVector())
903         continue;
904
905       setOperationAction(ISD::AND,    VT, Promote);
906       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
907       setOperationAction(ISD::OR,     VT, Promote);
908       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
909       setOperationAction(ISD::XOR,    VT, Promote);
910       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
911       setOperationAction(ISD::LOAD,   VT, Promote);
912       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
913       setOperationAction(ISD::SELECT, VT, Promote);
914       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
915     }
916
917     // Custom lower v2i64 and v2f64 selects.
918     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
919     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
920     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
921     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
922
923     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
924     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
925
926     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
927
928     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
929     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
930     // As there is no 64-bit GPR available, we need build a special custom
931     // sequence to convert from v2i32 to v2f32.
932     if (!Subtarget->is64Bit())
933       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
934
935     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
936     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
937
938     for (MVT VT : MVT::fp_vector_valuetypes())
939       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
940
941     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
942     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
943     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
944   }
945
946   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
947     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
948       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
949       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
950       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
951       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
952       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
953     }
954
955     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
956     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
957     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
958     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
959     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
960     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
961     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
962     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
963
964     // FIXME: Do we need to handle scalar-to-vector here?
965     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
966
967     // We directly match byte blends in the backend as they match the VSELECT
968     // condition form.
969     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
970
971     // SSE41 brings specific instructions for doing vector sign extend even in
972     // cases where we don't have SRA.
973     for (MVT VT : MVT::integer_vector_valuetypes()) {
974       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
975       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
976       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
977     }
978
979     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
980     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
981     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
982     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
983     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
984     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
985     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
986
987     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
988     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
989     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
990     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
991     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
992     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
993
994     // i8 and i16 vectors are custom because the source register and source
995     // source memory operand types are not the same width.  f32 vectors are
996     // custom since the immediate controlling the insert encodes additional
997     // information.
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
999     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1000     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1001     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1002
1003     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1004     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1005     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1006     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1007
1008     // FIXME: these should be Legal, but that's only for the case where
1009     // the index is constant.  For now custom expand to deal with that.
1010     if (Subtarget->is64Bit()) {
1011       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1012       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1013     }
1014   }
1015
1016   if (Subtarget->hasSSE2()) {
1017     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1018     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1019     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1020
1021     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1022     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1023
1024     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1025     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1026
1027     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1028     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1029
1030     // In the customized shift lowering, the legal cases in AVX2 will be
1031     // recognized.
1032     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1033     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1034
1035     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1036     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1037
1038     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1039     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1040   }
1041
1042   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1043     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1044     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1045     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1046     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1047     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1048     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1049
1050     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1051     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1052     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1053
1054     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1055     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1056     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1057     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1058     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1059     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1060     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1061     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1062     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1063     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1064     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1065     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1066
1067     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1068     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1069     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1070     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1071     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1072     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1073     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1074     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1075     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1076     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1077     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1078     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1079
1080     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1081     // even though v8i16 is a legal type.
1082     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1083     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1084     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1085
1086     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1087     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1088     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1089
1090     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1091     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1092
1093     for (MVT VT : MVT::fp_vector_valuetypes())
1094       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1095
1096     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1097     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1098
1099     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1100     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1101
1102     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1103     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1104
1105     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1106     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1107     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1108     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1109
1110     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1111     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1112     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1113
1114     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1115     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1116     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1117     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1118     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1119     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1120     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1121     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1122     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1123     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1124     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1125     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1126
1127     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1128     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1129     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1130     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1131
1132     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1133       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1134       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1135       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1136       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1137       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1138       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1139     }
1140
1141     if (Subtarget->hasInt256()) {
1142       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1143       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1144       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1145       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1146
1147       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1148       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1149       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1150       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1151
1152       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1153       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1154       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1155       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1156
1157       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1158       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1159       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1160       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1161
1162       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1163       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1164       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1165       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1166       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1167       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1168       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1169       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1170       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1171       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1172       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1173       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1174
1175       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1176       // when we have a 256bit-wide blend with immediate.
1177       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1178
1179       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1180       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1181       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1182       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1183       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1184       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1185       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1186
1187       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1188       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1189       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1190       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1191       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1192       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1193     } else {
1194       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1195       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1196       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1197       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1198
1199       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1200       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1201       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1202       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1203
1204       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1205       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1206       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1207       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1208
1209       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1210       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1211       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1212       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1213       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1214       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1215       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1216       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1217       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1218       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1219       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1220       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1221     }
1222
1223     // In the customized shift lowering, the legal cases in AVX2 will be
1224     // recognized.
1225     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1226     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1227
1228     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1229     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1230
1231     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1232     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1233
1234     // Custom lower several nodes for 256-bit types.
1235     for (MVT VT : MVT::vector_valuetypes()) {
1236       if (VT.getScalarSizeInBits() >= 32) {
1237         setOperationAction(ISD::MLOAD,  VT, Legal);
1238         setOperationAction(ISD::MSTORE, VT, Legal);
1239       }
1240       // Extract subvector is special because the value type
1241       // (result) is 128-bit but the source is 256-bit wide.
1242       if (VT.is128BitVector()) {
1243         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1244       }
1245       // Do not attempt to custom lower other non-256-bit vectors
1246       if (!VT.is256BitVector())
1247         continue;
1248
1249       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1250       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1251       setOperationAction(ISD::VSELECT,            VT, Custom);
1252       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1253       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1254       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1255       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1256       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1257     }
1258
1259     if (Subtarget->hasInt256())
1260       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1261
1262
1263     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1264     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1265       MVT VT = (MVT::SimpleValueType)i;
1266
1267       // Do not attempt to promote non-256-bit vectors
1268       if (!VT.is256BitVector())
1269         continue;
1270
1271       setOperationAction(ISD::AND,    VT, Promote);
1272       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1273       setOperationAction(ISD::OR,     VT, Promote);
1274       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1275       setOperationAction(ISD::XOR,    VT, Promote);
1276       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1277       setOperationAction(ISD::LOAD,   VT, Promote);
1278       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1279       setOperationAction(ISD::SELECT, VT, Promote);
1280       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1281     }
1282   }
1283
1284   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1285     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1286     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1287     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1288     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1289
1290     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1291     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1292     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1293
1294     for (MVT VT : MVT::fp_vector_valuetypes())
1295       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1296
1297     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1298     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1299     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1300     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1301     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1302     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1303     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1304     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1305     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1306     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1307     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1308     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1309
1310     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1311     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1312     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1313     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1314     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1315     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1316     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1317     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1318     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1319     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1320     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1321     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1322     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1323
1324     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1325     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1326     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1327     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1328     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1329     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1330
1331     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1332     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1333     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1334     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1335     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1336     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1337     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1338     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1339
1340     // FIXME:  [US]INT_TO_FP are not legal for f80.
1341     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1342     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1343     if (Subtarget->is64Bit()) {
1344       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1345       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1346     }
1347     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1348     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1349     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1350     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1351     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1352     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1353     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1354     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1355     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1356     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1357     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1358     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1359     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1360     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1361     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1362     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1363
1364     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1365     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1366     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1367     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1368     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1369     if (Subtarget->hasVLX()){
1370       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1371       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1372       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1373       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1374       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1375
1376       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1377       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1378       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1379       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1380       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1381     }
1382     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1383     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1384     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1385     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1386     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1387     if (Subtarget->hasDQI()) {
1388       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1389       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1390
1391       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1392       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1393       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1394       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1395       if (Subtarget->hasVLX()) {
1396         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1397         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1398         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1399         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1400         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1401         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1402         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1403         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1404       }
1405     }
1406     if (Subtarget->hasVLX()) {
1407       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1408       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1409       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1410       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1411       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1412       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1413       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1414       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1415     }
1416     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1417     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1418     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1419     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1420     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1421     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1422     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1423     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1424     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1425     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1426     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1427     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1428     if (Subtarget->hasDQI()) {
1429       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1430       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1431     }
1432     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1433     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1434     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1435     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1436     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1437     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1438     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1439     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1440     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1441     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1442
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1444     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1445     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1446     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1447     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1448
1449     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1450     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1451
1452     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1453
1454     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1455     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1456     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1457     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1458     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1459     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1460     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1461     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1462     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1463     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1464     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1465
1466     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1467     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1468     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1469     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1470     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1471     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1472     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1473     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1474
1475     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1476     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1477
1478     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1479     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1480
1481     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1482
1483     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1484     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1485
1486     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1487     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1488
1489     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1490     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1491
1492     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1493     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1494     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1495     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1496     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1497     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1498
1499     if (Subtarget->hasCDI()) {
1500       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1501       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1502       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64, Legal);
1503       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Legal);
1504     }
1505     if (Subtarget->hasVLX() && Subtarget->hasCDI()) {
1506       setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1507       setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1508       setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1509       setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1510       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Legal);
1511       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Legal);
1512       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Legal);
1513       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Legal);
1514     }
1515     if (Subtarget->hasDQI()) {
1516       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1517       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1518       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1519     }
1520     // Custom lower several nodes.
1521     for (MVT VT : MVT::vector_valuetypes()) {
1522       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1523       if (EltSize == 1) {
1524         setOperationAction(ISD::AND, VT, Legal);
1525         setOperationAction(ISD::OR,  VT, Legal);
1526         setOperationAction(ISD::XOR,  VT, Legal);
1527       }
1528       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1529         setOperationAction(ISD::MGATHER,  VT, Custom);
1530         setOperationAction(ISD::MSCATTER, VT, Custom);
1531       }
1532       // Extract subvector is special because the value type
1533       // (result) is 256/128-bit but the source is 512-bit wide.
1534       if (VT.is128BitVector() || VT.is256BitVector()) {
1535         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1536       }
1537       if (VT.getVectorElementType() == MVT::i1)
1538         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1539
1540       // Do not attempt to custom lower other non-512-bit vectors
1541       if (!VT.is512BitVector())
1542         continue;
1543
1544       if (EltSize >= 32) {
1545         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1546         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1547         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1548         setOperationAction(ISD::VSELECT,             VT, Legal);
1549         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1550         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1551         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1552         setOperationAction(ISD::MLOAD,               VT, Legal);
1553         setOperationAction(ISD::MSTORE,              VT, Legal);
1554       }
1555     }
1556     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1557       MVT VT = (MVT::SimpleValueType)i;
1558
1559       // Do not attempt to promote non-512-bit vectors.
1560       if (!VT.is512BitVector())
1561         continue;
1562
1563       setOperationAction(ISD::SELECT, VT, Promote);
1564       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1565     }
1566   }// has  AVX-512
1567
1568   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1569     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1570     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1571
1572     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1573     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1574
1575     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1576     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1577     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1578     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1579     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1580     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1581     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1582     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1583     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1584     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1585     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1586     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Legal);
1587     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Legal);
1588     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1589     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1590     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1591     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1592     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1593     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1594     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1595     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1596     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1597     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1598     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1599     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1600     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1601     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1602     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1603     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1604     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1605     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1606     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1607     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1608
1609     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1610     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1611     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1612     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1613     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1614     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1615     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1616     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1617
1618     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1619     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1620     if (Subtarget->hasVLX())
1621       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1622
1623     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1624       const MVT VT = (MVT::SimpleValueType)i;
1625
1626       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1627
1628       // Do not attempt to promote non-512-bit vectors.
1629       if (!VT.is512BitVector())
1630         continue;
1631
1632       if (EltSize < 32) {
1633         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1634         setOperationAction(ISD::VSELECT,             VT, Legal);
1635       }
1636     }
1637   }
1638
1639   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1640     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1641     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1642
1643     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1644     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1645     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1646     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1647     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1648     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1649     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1650     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1651     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1652     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1653     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1654     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1655
1656     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1657     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1658     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1659     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1660     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1661     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1662     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1663     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1664
1665     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1666     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1667     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1668     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1669     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1670     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1671     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1672     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1673   }
1674
1675   // We want to custom lower some of our intrinsics.
1676   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1677   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1678   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1679   if (!Subtarget->is64Bit())
1680     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1681
1682   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1683   // handle type legalization for these operations here.
1684   //
1685   // FIXME: We really should do custom legalization for addition and
1686   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1687   // than generic legalization for 64-bit multiplication-with-overflow, though.
1688   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1689     // Add/Sub/Mul with overflow operations are custom lowered.
1690     MVT VT = IntVTs[i];
1691     setOperationAction(ISD::SADDO, VT, Custom);
1692     setOperationAction(ISD::UADDO, VT, Custom);
1693     setOperationAction(ISD::SSUBO, VT, Custom);
1694     setOperationAction(ISD::USUBO, VT, Custom);
1695     setOperationAction(ISD::SMULO, VT, Custom);
1696     setOperationAction(ISD::UMULO, VT, Custom);
1697   }
1698
1699
1700   if (!Subtarget->is64Bit()) {
1701     // These libcalls are not available in 32-bit.
1702     setLibcallName(RTLIB::SHL_I128, nullptr);
1703     setLibcallName(RTLIB::SRL_I128, nullptr);
1704     setLibcallName(RTLIB::SRA_I128, nullptr);
1705   }
1706
1707   // Combine sin / cos into one node or libcall if possible.
1708   if (Subtarget->hasSinCos()) {
1709     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1710     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1711     if (Subtarget->isTargetDarwin()) {
1712       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1713       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1714       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1715       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1716     }
1717   }
1718
1719   if (Subtarget->isTargetWin64()) {
1720     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1721     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1722     setOperationAction(ISD::SREM, MVT::i128, Custom);
1723     setOperationAction(ISD::UREM, MVT::i128, Custom);
1724     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1725     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1726   }
1727
1728   // We have target-specific dag combine patterns for the following nodes:
1729   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1730   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1731   setTargetDAGCombine(ISD::BITCAST);
1732   setTargetDAGCombine(ISD::VSELECT);
1733   setTargetDAGCombine(ISD::SELECT);
1734   setTargetDAGCombine(ISD::SHL);
1735   setTargetDAGCombine(ISD::SRA);
1736   setTargetDAGCombine(ISD::SRL);
1737   setTargetDAGCombine(ISD::OR);
1738   setTargetDAGCombine(ISD::AND);
1739   setTargetDAGCombine(ISD::ADD);
1740   setTargetDAGCombine(ISD::FADD);
1741   setTargetDAGCombine(ISD::FSUB);
1742   setTargetDAGCombine(ISD::FMA);
1743   setTargetDAGCombine(ISD::SUB);
1744   setTargetDAGCombine(ISD::LOAD);
1745   setTargetDAGCombine(ISD::MLOAD);
1746   setTargetDAGCombine(ISD::STORE);
1747   setTargetDAGCombine(ISD::MSTORE);
1748   setTargetDAGCombine(ISD::ZERO_EXTEND);
1749   setTargetDAGCombine(ISD::ANY_EXTEND);
1750   setTargetDAGCombine(ISD::SIGN_EXTEND);
1751   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1752   setTargetDAGCombine(ISD::SINT_TO_FP);
1753   setTargetDAGCombine(ISD::UINT_TO_FP);
1754   setTargetDAGCombine(ISD::SETCC);
1755   setTargetDAGCombine(ISD::BUILD_VECTOR);
1756   setTargetDAGCombine(ISD::MUL);
1757   setTargetDAGCombine(ISD::XOR);
1758
1759   computeRegisterProperties(Subtarget->getRegisterInfo());
1760
1761   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1762   MaxStoresPerMemsetOptSize = 8;
1763   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1764   MaxStoresPerMemcpyOptSize = 4;
1765   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1766   MaxStoresPerMemmoveOptSize = 4;
1767   setPrefLoopAlignment(4); // 2^4 bytes.
1768
1769   // Predictable cmov don't hurt on atom because it's in-order.
1770   PredictableSelectIsExpensive = !Subtarget->isAtom();
1771   EnableExtLdPromotion = true;
1772   setPrefFunctionAlignment(4); // 2^4 bytes.
1773
1774   verifyIntrinsicTables();
1775 }
1776
1777 // This has so far only been implemented for 64-bit MachO.
1778 bool X86TargetLowering::useLoadStackGuardNode() const {
1779   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1780 }
1781
1782 TargetLoweringBase::LegalizeTypeAction
1783 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1784   if (ExperimentalVectorWideningLegalization &&
1785       VT.getVectorNumElements() != 1 &&
1786       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1787     return TypeWidenVector;
1788
1789   return TargetLoweringBase::getPreferredVectorAction(VT);
1790 }
1791
1792 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1793                                           EVT VT) const {
1794   if (!VT.isVector())
1795     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1796
1797   const unsigned NumElts = VT.getVectorNumElements();
1798   const EVT EltVT = VT.getVectorElementType();
1799   if (VT.is512BitVector()) {
1800     if (Subtarget->hasAVX512())
1801       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1802           EltVT == MVT::f32 || EltVT == MVT::f64)
1803         switch(NumElts) {
1804         case  8: return MVT::v8i1;
1805         case 16: return MVT::v16i1;
1806       }
1807     if (Subtarget->hasBWI())
1808       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1809         switch(NumElts) {
1810         case 32: return MVT::v32i1;
1811         case 64: return MVT::v64i1;
1812       }
1813   }
1814
1815   if (VT.is256BitVector() || VT.is128BitVector()) {
1816     if (Subtarget->hasVLX())
1817       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1818           EltVT == MVT::f32 || EltVT == MVT::f64)
1819         switch(NumElts) {
1820         case 2: return MVT::v2i1;
1821         case 4: return MVT::v4i1;
1822         case 8: return MVT::v8i1;
1823       }
1824     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1825       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1826         switch(NumElts) {
1827         case  8: return MVT::v8i1;
1828         case 16: return MVT::v16i1;
1829         case 32: return MVT::v32i1;
1830       }
1831   }
1832
1833   return VT.changeVectorElementTypeToInteger();
1834 }
1835
1836 /// Helper for getByValTypeAlignment to determine
1837 /// the desired ByVal argument alignment.
1838 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1839   if (MaxAlign == 16)
1840     return;
1841   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1842     if (VTy->getBitWidth() == 128)
1843       MaxAlign = 16;
1844   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1845     unsigned EltAlign = 0;
1846     getMaxByValAlign(ATy->getElementType(), EltAlign);
1847     if (EltAlign > MaxAlign)
1848       MaxAlign = EltAlign;
1849   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1850     for (auto *EltTy : STy->elements()) {
1851       unsigned EltAlign = 0;
1852       getMaxByValAlign(EltTy, EltAlign);
1853       if (EltAlign > MaxAlign)
1854         MaxAlign = EltAlign;
1855       if (MaxAlign == 16)
1856         break;
1857     }
1858   }
1859 }
1860
1861 /// Return the desired alignment for ByVal aggregate
1862 /// function arguments in the caller parameter area. For X86, aggregates
1863 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1864 /// are at 4-byte boundaries.
1865 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1866                                                   const DataLayout &DL) const {
1867   if (Subtarget->is64Bit()) {
1868     // Max of 8 and alignment of type.
1869     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1870     if (TyAlign > 8)
1871       return TyAlign;
1872     return 8;
1873   }
1874
1875   unsigned Align = 4;
1876   if (Subtarget->hasSSE1())
1877     getMaxByValAlign(Ty, Align);
1878   return Align;
1879 }
1880
1881 /// Returns the target specific optimal type for load
1882 /// and store operations as a result of memset, memcpy, and memmove
1883 /// lowering. If DstAlign is zero that means it's safe to destination
1884 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1885 /// means there isn't a need to check it against alignment requirement,
1886 /// probably because the source does not need to be loaded. If 'IsMemset' is
1887 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1888 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1889 /// source is constant so it does not need to be loaded.
1890 /// It returns EVT::Other if the type should be determined using generic
1891 /// target-independent logic.
1892 EVT
1893 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1894                                        unsigned DstAlign, unsigned SrcAlign,
1895                                        bool IsMemset, bool ZeroMemset,
1896                                        bool MemcpyStrSrc,
1897                                        MachineFunction &MF) const {
1898   const Function *F = MF.getFunction();
1899   if ((!IsMemset || ZeroMemset) &&
1900       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1901     if (Size >= 16 &&
1902         (!Subtarget->isUnalignedMem16Slow() ||
1903          ((DstAlign == 0 || DstAlign >= 16) &&
1904           (SrcAlign == 0 || SrcAlign >= 16)))) {
1905       if (Size >= 32) {
1906         // FIXME: Check if unaligned 32-byte accesses are slow.
1907         if (Subtarget->hasInt256())
1908           return MVT::v8i32;
1909         if (Subtarget->hasFp256())
1910           return MVT::v8f32;
1911       }
1912       if (Subtarget->hasSSE2())
1913         return MVT::v4i32;
1914       if (Subtarget->hasSSE1())
1915         return MVT::v4f32;
1916     } else if (!MemcpyStrSrc && Size >= 8 &&
1917                !Subtarget->is64Bit() &&
1918                Subtarget->hasSSE2()) {
1919       // Do not use f64 to lower memcpy if source is string constant. It's
1920       // better to use i32 to avoid the loads.
1921       return MVT::f64;
1922     }
1923   }
1924   // This is a compromise. If we reach here, unaligned accesses may be slow on
1925   // this target. However, creating smaller, aligned accesses could be even
1926   // slower and would certainly be a lot more code.
1927   if (Subtarget->is64Bit() && Size >= 8)
1928     return MVT::i64;
1929   return MVT::i32;
1930 }
1931
1932 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1933   if (VT == MVT::f32)
1934     return X86ScalarSSEf32;
1935   else if (VT == MVT::f64)
1936     return X86ScalarSSEf64;
1937   return true;
1938 }
1939
1940 bool
1941 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1942                                                   unsigned,
1943                                                   unsigned,
1944                                                   bool *Fast) const {
1945   if (Fast) {
1946     switch (VT.getSizeInBits()) {
1947     default:
1948       // 8-byte and under are always assumed to be fast.
1949       *Fast = true;
1950       break;
1951     case 128:
1952       *Fast = !Subtarget->isUnalignedMem16Slow();
1953       break;
1954     case 256:
1955       *Fast = !Subtarget->isUnalignedMem32Slow();
1956       break;
1957     // TODO: What about AVX-512 (512-bit) accesses?
1958     }
1959   }
1960   // Misaligned accesses of any size are always allowed.
1961   return true;
1962 }
1963
1964 /// Return the entry encoding for a jump table in the
1965 /// current function.  The returned value is a member of the
1966 /// MachineJumpTableInfo::JTEntryKind enum.
1967 unsigned X86TargetLowering::getJumpTableEncoding() const {
1968   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1969   // symbol.
1970   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1971       Subtarget->isPICStyleGOT())
1972     return MachineJumpTableInfo::EK_Custom32;
1973
1974   // Otherwise, use the normal jump table encoding heuristics.
1975   return TargetLowering::getJumpTableEncoding();
1976 }
1977
1978 bool X86TargetLowering::useSoftFloat() const {
1979   return Subtarget->useSoftFloat();
1980 }
1981
1982 const MCExpr *
1983 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1984                                              const MachineBasicBlock *MBB,
1985                                              unsigned uid,MCContext &Ctx) const{
1986   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1987          Subtarget->isPICStyleGOT());
1988   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1989   // entries.
1990   return MCSymbolRefExpr::create(MBB->getSymbol(),
1991                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1992 }
1993
1994 /// Returns relocation base for the given PIC jumptable.
1995 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1996                                                     SelectionDAG &DAG) const {
1997   if (!Subtarget->is64Bit())
1998     // This doesn't have SDLoc associated with it, but is not really the
1999     // same as a Register.
2000     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2001                        getPointerTy(DAG.getDataLayout()));
2002   return Table;
2003 }
2004
2005 /// This returns the relocation base for the given PIC jumptable,
2006 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2007 const MCExpr *X86TargetLowering::
2008 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2009                              MCContext &Ctx) const {
2010   // X86-64 uses RIP relative addressing based on the jump table label.
2011   if (Subtarget->isPICStyleRIPRel())
2012     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2013
2014   // Otherwise, the reference is relative to the PIC base.
2015   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2016 }
2017
2018 std::pair<const TargetRegisterClass *, uint8_t>
2019 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2020                                            MVT VT) const {
2021   const TargetRegisterClass *RRC = nullptr;
2022   uint8_t Cost = 1;
2023   switch (VT.SimpleTy) {
2024   default:
2025     return TargetLowering::findRepresentativeClass(TRI, VT);
2026   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2027     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2028     break;
2029   case MVT::x86mmx:
2030     RRC = &X86::VR64RegClass;
2031     break;
2032   case MVT::f32: case MVT::f64:
2033   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2034   case MVT::v4f32: case MVT::v2f64:
2035   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2036   case MVT::v4f64:
2037     RRC = &X86::VR128RegClass;
2038     break;
2039   }
2040   return std::make_pair(RRC, Cost);
2041 }
2042
2043 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2044                                                unsigned &Offset) const {
2045   if (!Subtarget->isTargetLinux())
2046     return false;
2047
2048   if (Subtarget->is64Bit()) {
2049     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2050     Offset = 0x28;
2051     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2052       AddressSpace = 256;
2053     else
2054       AddressSpace = 257;
2055   } else {
2056     // %gs:0x14 on i386
2057     Offset = 0x14;
2058     AddressSpace = 256;
2059   }
2060   return true;
2061 }
2062
2063 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2064                                             unsigned DestAS) const {
2065   assert(SrcAS != DestAS && "Expected different address spaces!");
2066
2067   return SrcAS < 256 && DestAS < 256;
2068 }
2069
2070 //===----------------------------------------------------------------------===//
2071 //               Return Value Calling Convention Implementation
2072 //===----------------------------------------------------------------------===//
2073
2074 #include "X86GenCallingConv.inc"
2075
2076 bool
2077 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2078                                   MachineFunction &MF, bool isVarArg,
2079                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2080                         LLVMContext &Context) const {
2081   SmallVector<CCValAssign, 16> RVLocs;
2082   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2083   return CCInfo.CheckReturn(Outs, RetCC_X86);
2084 }
2085
2086 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2087   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2088   return ScratchRegs;
2089 }
2090
2091 SDValue
2092 X86TargetLowering::LowerReturn(SDValue Chain,
2093                                CallingConv::ID CallConv, bool isVarArg,
2094                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2095                                const SmallVectorImpl<SDValue> &OutVals,
2096                                SDLoc dl, SelectionDAG &DAG) const {
2097   MachineFunction &MF = DAG.getMachineFunction();
2098   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2099
2100   SmallVector<CCValAssign, 16> RVLocs;
2101   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2102   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2103
2104   SDValue Flag;
2105   SmallVector<SDValue, 6> RetOps;
2106   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2107   // Operand #1 = Bytes To Pop
2108   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2109                    MVT::i16));
2110
2111   // Copy the result values into the output registers.
2112   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2113     CCValAssign &VA = RVLocs[i];
2114     assert(VA.isRegLoc() && "Can only return in registers!");
2115     SDValue ValToCopy = OutVals[i];
2116     EVT ValVT = ValToCopy.getValueType();
2117
2118     // Promote values to the appropriate types.
2119     if (VA.getLocInfo() == CCValAssign::SExt)
2120       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2121     else if (VA.getLocInfo() == CCValAssign::ZExt)
2122       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2123     else if (VA.getLocInfo() == CCValAssign::AExt) {
2124       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2125         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2126       else
2127         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2128     }
2129     else if (VA.getLocInfo() == CCValAssign::BCvt)
2130       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2131
2132     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2133            "Unexpected FP-extend for return value.");
2134
2135     // If this is x86-64, and we disabled SSE, we can't return FP values,
2136     // or SSE or MMX vectors.
2137     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2138          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2139           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2140       report_fatal_error("SSE register return with SSE disabled");
2141     }
2142     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2143     // llvm-gcc has never done it right and no one has noticed, so this
2144     // should be OK for now.
2145     if (ValVT == MVT::f64 &&
2146         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2147       report_fatal_error("SSE2 register return with SSE2 disabled");
2148
2149     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2150     // the RET instruction and handled by the FP Stackifier.
2151     if (VA.getLocReg() == X86::FP0 ||
2152         VA.getLocReg() == X86::FP1) {
2153       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2154       // change the value to the FP stack register class.
2155       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2156         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2157       RetOps.push_back(ValToCopy);
2158       // Don't emit a copytoreg.
2159       continue;
2160     }
2161
2162     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2163     // which is returned in RAX / RDX.
2164     if (Subtarget->is64Bit()) {
2165       if (ValVT == MVT::x86mmx) {
2166         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2167           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2168           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2169                                   ValToCopy);
2170           // If we don't have SSE2 available, convert to v4f32 so the generated
2171           // register is legal.
2172           if (!Subtarget->hasSSE2())
2173             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2174         }
2175       }
2176     }
2177
2178     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2179     Flag = Chain.getValue(1);
2180     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2181   }
2182
2183   // All x86 ABIs require that for returning structs by value we copy
2184   // the sret argument into %rax/%eax (depending on ABI) for the return.
2185   // We saved the argument into a virtual register in the entry block,
2186   // so now we copy the value out and into %rax/%eax.
2187   //
2188   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2189   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2190   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2191   // either case FuncInfo->setSRetReturnReg() will have been called.
2192   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2193     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2194                                      getPointerTy(MF.getDataLayout()));
2195
2196     unsigned RetValReg
2197         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2198           X86::RAX : X86::EAX;
2199     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2200     Flag = Chain.getValue(1);
2201
2202     // RAX/EAX now acts like a return value.
2203     RetOps.push_back(
2204         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2205   }
2206
2207   RetOps[0] = Chain;  // Update chain.
2208
2209   // Add the flag if we have it.
2210   if (Flag.getNode())
2211     RetOps.push_back(Flag);
2212
2213   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2214 }
2215
2216 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2217   if (N->getNumValues() != 1)
2218     return false;
2219   if (!N->hasNUsesOfValue(1, 0))
2220     return false;
2221
2222   SDValue TCChain = Chain;
2223   SDNode *Copy = *N->use_begin();
2224   if (Copy->getOpcode() == ISD::CopyToReg) {
2225     // If the copy has a glue operand, we conservatively assume it isn't safe to
2226     // perform a tail call.
2227     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2228       return false;
2229     TCChain = Copy->getOperand(0);
2230   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2231     return false;
2232
2233   bool HasRet = false;
2234   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2235        UI != UE; ++UI) {
2236     if (UI->getOpcode() != X86ISD::RET_FLAG)
2237       return false;
2238     // If we are returning more than one value, we can definitely
2239     // not make a tail call see PR19530
2240     if (UI->getNumOperands() > 4)
2241       return false;
2242     if (UI->getNumOperands() == 4 &&
2243         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2244       return false;
2245     HasRet = true;
2246   }
2247
2248   if (!HasRet)
2249     return false;
2250
2251   Chain = TCChain;
2252   return true;
2253 }
2254
2255 EVT
2256 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2257                                             ISD::NodeType ExtendKind) const {
2258   MVT ReturnMVT;
2259   // TODO: Is this also valid on 32-bit?
2260   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2261     ReturnMVT = MVT::i8;
2262   else
2263     ReturnMVT = MVT::i32;
2264
2265   EVT MinVT = getRegisterType(Context, ReturnMVT);
2266   return VT.bitsLT(MinVT) ? MinVT : VT;
2267 }
2268
2269 /// Lower the result values of a call into the
2270 /// appropriate copies out of appropriate physical registers.
2271 ///
2272 SDValue
2273 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2274                                    CallingConv::ID CallConv, bool isVarArg,
2275                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2276                                    SDLoc dl, SelectionDAG &DAG,
2277                                    SmallVectorImpl<SDValue> &InVals) const {
2278
2279   // Assign locations to each value returned by this call.
2280   SmallVector<CCValAssign, 16> RVLocs;
2281   bool Is64Bit = Subtarget->is64Bit();
2282   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2283                  *DAG.getContext());
2284   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2285
2286   // Copy all of the result registers out of their specified physreg.
2287   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2288     CCValAssign &VA = RVLocs[i];
2289     EVT CopyVT = VA.getLocVT();
2290
2291     // If this is x86-64, and we disabled SSE, we can't return FP values
2292     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2293         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2294       report_fatal_error("SSE register return with SSE disabled");
2295     }
2296
2297     // If we prefer to use the value in xmm registers, copy it out as f80 and
2298     // use a truncate to move it from fp stack reg to xmm reg.
2299     bool RoundAfterCopy = false;
2300     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2301         isScalarFPTypeInSSEReg(VA.getValVT())) {
2302       CopyVT = MVT::f80;
2303       RoundAfterCopy = (CopyVT != VA.getLocVT());
2304     }
2305
2306     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2307                                CopyVT, InFlag).getValue(1);
2308     SDValue Val = Chain.getValue(0);
2309
2310     if (RoundAfterCopy)
2311       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2312                         // This truncation won't change the value.
2313                         DAG.getIntPtrConstant(1, dl));
2314
2315     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2316       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2317
2318     InFlag = Chain.getValue(2);
2319     InVals.push_back(Val);
2320   }
2321
2322   return Chain;
2323 }
2324
2325 //===----------------------------------------------------------------------===//
2326 //                C & StdCall & Fast Calling Convention implementation
2327 //===----------------------------------------------------------------------===//
2328 //  StdCall calling convention seems to be standard for many Windows' API
2329 //  routines and around. It differs from C calling convention just a little:
2330 //  callee should clean up the stack, not caller. Symbols should be also
2331 //  decorated in some fancy way :) It doesn't support any vector arguments.
2332 //  For info on fast calling convention see Fast Calling Convention (tail call)
2333 //  implementation LowerX86_32FastCCCallTo.
2334
2335 /// CallIsStructReturn - Determines whether a call uses struct return
2336 /// semantics.
2337 enum StructReturnType {
2338   NotStructReturn,
2339   RegStructReturn,
2340   StackStructReturn
2341 };
2342 static StructReturnType
2343 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2344   if (Outs.empty())
2345     return NotStructReturn;
2346
2347   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2348   if (!Flags.isSRet())
2349     return NotStructReturn;
2350   if (Flags.isInReg())
2351     return RegStructReturn;
2352   return StackStructReturn;
2353 }
2354
2355 /// Determines whether a function uses struct return semantics.
2356 static StructReturnType
2357 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2358   if (Ins.empty())
2359     return NotStructReturn;
2360
2361   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2362   if (!Flags.isSRet())
2363     return NotStructReturn;
2364   if (Flags.isInReg())
2365     return RegStructReturn;
2366   return StackStructReturn;
2367 }
2368
2369 /// Make a copy of an aggregate at address specified by "Src" to address
2370 /// "Dst" with size and alignment information specified by the specific
2371 /// parameter attribute. The copy will be passed as a byval function parameter.
2372 static SDValue
2373 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2374                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2375                           SDLoc dl) {
2376   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2377
2378   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2379                        /*isVolatile*/false, /*AlwaysInline=*/true,
2380                        /*isTailCall*/false,
2381                        MachinePointerInfo(), MachinePointerInfo());
2382 }
2383
2384 /// Return true if the calling convention is one that
2385 /// supports tail call optimization.
2386 static bool IsTailCallConvention(CallingConv::ID CC) {
2387   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2388           CC == CallingConv::HiPE);
2389 }
2390
2391 /// \brief Return true if the calling convention is a C calling convention.
2392 static bool IsCCallConvention(CallingConv::ID CC) {
2393   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2394           CC == CallingConv::X86_64_SysV);
2395 }
2396
2397 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2398   auto Attr =
2399       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2400   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2401     return false;
2402
2403   CallSite CS(CI);
2404   CallingConv::ID CalleeCC = CS.getCallingConv();
2405   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2406     return false;
2407
2408   return true;
2409 }
2410
2411 /// Return true if the function is being made into
2412 /// a tailcall target by changing its ABI.
2413 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2414                                    bool GuaranteedTailCallOpt) {
2415   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2416 }
2417
2418 SDValue
2419 X86TargetLowering::LowerMemArgument(SDValue Chain,
2420                                     CallingConv::ID CallConv,
2421                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2422                                     SDLoc dl, SelectionDAG &DAG,
2423                                     const CCValAssign &VA,
2424                                     MachineFrameInfo *MFI,
2425                                     unsigned i) const {
2426   // Create the nodes corresponding to a load from this parameter slot.
2427   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2428   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2429       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2430   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2431   EVT ValVT;
2432
2433   // If value is passed by pointer we have address passed instead of the value
2434   // itself.
2435   bool ExtendedInMem = VA.isExtInLoc() &&
2436     VA.getValVT().getScalarType() == MVT::i1;
2437
2438   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2439     ValVT = VA.getLocVT();
2440   else
2441     ValVT = VA.getValVT();
2442
2443   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2444   // changed with more analysis.
2445   // In case of tail call optimization mark all arguments mutable. Since they
2446   // could be overwritten by lowering of arguments in case of a tail call.
2447   if (Flags.isByVal()) {
2448     unsigned Bytes = Flags.getByValSize();
2449     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2450     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2451     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2452   } else {
2453     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2454                                     VA.getLocMemOffset(), isImmutable);
2455     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2456     SDValue Val = DAG.getLoad(
2457         ValVT, dl, Chain, FIN,
2458         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2459         false, false, 0);
2460     return ExtendedInMem ?
2461       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2462   }
2463 }
2464
2465 // FIXME: Get this from tablegen.
2466 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2467                                                 const X86Subtarget *Subtarget) {
2468   assert(Subtarget->is64Bit());
2469
2470   if (Subtarget->isCallingConvWin64(CallConv)) {
2471     static const MCPhysReg GPR64ArgRegsWin64[] = {
2472       X86::RCX, X86::RDX, X86::R8,  X86::R9
2473     };
2474     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2475   }
2476
2477   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2478     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2479   };
2480   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2481 }
2482
2483 // FIXME: Get this from tablegen.
2484 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2485                                                 CallingConv::ID CallConv,
2486                                                 const X86Subtarget *Subtarget) {
2487   assert(Subtarget->is64Bit());
2488   if (Subtarget->isCallingConvWin64(CallConv)) {
2489     // The XMM registers which might contain var arg parameters are shadowed
2490     // in their paired GPR.  So we only need to save the GPR to their home
2491     // slots.
2492     // TODO: __vectorcall will change this.
2493     return None;
2494   }
2495
2496   const Function *Fn = MF.getFunction();
2497   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2498   bool isSoftFloat = Subtarget->useSoftFloat();
2499   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2500          "SSE register cannot be used when SSE is disabled!");
2501   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2502     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2503     // registers.
2504     return None;
2505
2506   static const MCPhysReg XMMArgRegs64Bit[] = {
2507     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2508     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2509   };
2510   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2511 }
2512
2513 SDValue
2514 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2515                                         CallingConv::ID CallConv,
2516                                         bool isVarArg,
2517                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2518                                         SDLoc dl,
2519                                         SelectionDAG &DAG,
2520                                         SmallVectorImpl<SDValue> &InVals)
2521                                           const {
2522   MachineFunction &MF = DAG.getMachineFunction();
2523   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2524   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2525
2526   const Function* Fn = MF.getFunction();
2527   if (Fn->hasExternalLinkage() &&
2528       Subtarget->isTargetCygMing() &&
2529       Fn->getName() == "main")
2530     FuncInfo->setForceFramePointer(true);
2531
2532   MachineFrameInfo *MFI = MF.getFrameInfo();
2533   bool Is64Bit = Subtarget->is64Bit();
2534   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2535
2536   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2537          "Var args not supported with calling convention fastcc, ghc or hipe");
2538
2539   // Assign locations to all of the incoming arguments.
2540   SmallVector<CCValAssign, 16> ArgLocs;
2541   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2542
2543   // Allocate shadow area for Win64
2544   if (IsWin64)
2545     CCInfo.AllocateStack(32, 8);
2546
2547   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2548
2549   unsigned LastVal = ~0U;
2550   SDValue ArgValue;
2551   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2552     CCValAssign &VA = ArgLocs[i];
2553     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2554     // places.
2555     assert(VA.getValNo() != LastVal &&
2556            "Don't support value assigned to multiple locs yet");
2557     (void)LastVal;
2558     LastVal = VA.getValNo();
2559
2560     if (VA.isRegLoc()) {
2561       EVT RegVT = VA.getLocVT();
2562       const TargetRegisterClass *RC;
2563       if (RegVT == MVT::i32)
2564         RC = &X86::GR32RegClass;
2565       else if (Is64Bit && RegVT == MVT::i64)
2566         RC = &X86::GR64RegClass;
2567       else if (RegVT == MVT::f32)
2568         RC = &X86::FR32RegClass;
2569       else if (RegVT == MVT::f64)
2570         RC = &X86::FR64RegClass;
2571       else if (RegVT.is512BitVector())
2572         RC = &X86::VR512RegClass;
2573       else if (RegVT.is256BitVector())
2574         RC = &X86::VR256RegClass;
2575       else if (RegVT.is128BitVector())
2576         RC = &X86::VR128RegClass;
2577       else if (RegVT == MVT::x86mmx)
2578         RC = &X86::VR64RegClass;
2579       else if (RegVT == MVT::i1)
2580         RC = &X86::VK1RegClass;
2581       else if (RegVT == MVT::v8i1)
2582         RC = &X86::VK8RegClass;
2583       else if (RegVT == MVT::v16i1)
2584         RC = &X86::VK16RegClass;
2585       else if (RegVT == MVT::v32i1)
2586         RC = &X86::VK32RegClass;
2587       else if (RegVT == MVT::v64i1)
2588         RC = &X86::VK64RegClass;
2589       else
2590         llvm_unreachable("Unknown argument type!");
2591
2592       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2593       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2594
2595       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2596       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2597       // right size.
2598       if (VA.getLocInfo() == CCValAssign::SExt)
2599         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2600                                DAG.getValueType(VA.getValVT()));
2601       else if (VA.getLocInfo() == CCValAssign::ZExt)
2602         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2603                                DAG.getValueType(VA.getValVT()));
2604       else if (VA.getLocInfo() == CCValAssign::BCvt)
2605         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2606
2607       if (VA.isExtInLoc()) {
2608         // Handle MMX values passed in XMM regs.
2609         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2610           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2611         else
2612           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2613       }
2614     } else {
2615       assert(VA.isMemLoc());
2616       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2617     }
2618
2619     // If value is passed via pointer - do a load.
2620     if (VA.getLocInfo() == CCValAssign::Indirect)
2621       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2622                              MachinePointerInfo(), false, false, false, 0);
2623
2624     InVals.push_back(ArgValue);
2625   }
2626
2627   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2628     // All x86 ABIs require that for returning structs by value we copy the
2629     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2630     // the argument into a virtual register so that we can access it from the
2631     // return points.
2632     if (Ins[i].Flags.isSRet()) {
2633       unsigned Reg = FuncInfo->getSRetReturnReg();
2634       if (!Reg) {
2635         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2636         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2637         FuncInfo->setSRetReturnReg(Reg);
2638       }
2639       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2640       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2641       break;
2642     }
2643   }
2644
2645   unsigned StackSize = CCInfo.getNextStackOffset();
2646   // Align stack specially for tail calls.
2647   if (FuncIsMadeTailCallSafe(CallConv,
2648                              MF.getTarget().Options.GuaranteedTailCallOpt))
2649     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2650
2651   // If the function takes variable number of arguments, make a frame index for
2652   // the start of the first vararg value... for expansion of llvm.va_start. We
2653   // can skip this if there are no va_start calls.
2654   if (MFI->hasVAStart() &&
2655       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2656                    CallConv != CallingConv::X86_ThisCall))) {
2657     FuncInfo->setVarArgsFrameIndex(
2658         MFI->CreateFixedObject(1, StackSize, true));
2659   }
2660
2661   MachineModuleInfo &MMI = MF.getMMI();
2662   const Function *WinEHParent = nullptr;
2663   if (MMI.hasWinEHFuncInfo(Fn))
2664     WinEHParent = MMI.getWinEHParent(Fn);
2665   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2666
2667   // Figure out if XMM registers are in use.
2668   assert(!(Subtarget->useSoftFloat() &&
2669            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2670          "SSE register cannot be used when SSE is disabled!");
2671
2672   // 64-bit calling conventions support varargs and register parameters, so we
2673   // have to do extra work to spill them in the prologue.
2674   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2675     // Find the first unallocated argument registers.
2676     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2677     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2678     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2679     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2680     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2681            "SSE register cannot be used when SSE is disabled!");
2682
2683     // Gather all the live in physical registers.
2684     SmallVector<SDValue, 6> LiveGPRs;
2685     SmallVector<SDValue, 8> LiveXMMRegs;
2686     SDValue ALVal;
2687     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2688       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2689       LiveGPRs.push_back(
2690           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2691     }
2692     if (!ArgXMMs.empty()) {
2693       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2694       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2695       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2696         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2697         LiveXMMRegs.push_back(
2698             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2699       }
2700     }
2701
2702     if (IsWin64) {
2703       // Get to the caller-allocated home save location.  Add 8 to account
2704       // for the return address.
2705       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2706       FuncInfo->setRegSaveFrameIndex(
2707           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2708       // Fixup to set vararg frame on shadow area (4 x i64).
2709       if (NumIntRegs < 4)
2710         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2711     } else {
2712       // For X86-64, if there are vararg parameters that are passed via
2713       // registers, then we must store them to their spots on the stack so
2714       // they may be loaded by deferencing the result of va_next.
2715       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2716       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2717       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2718           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2719     }
2720
2721     // Store the integer parameter registers.
2722     SmallVector<SDValue, 8> MemOps;
2723     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2724                                       getPointerTy(DAG.getDataLayout()));
2725     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2726     for (SDValue Val : LiveGPRs) {
2727       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2728                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2729       SDValue Store =
2730           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2731                        MachinePointerInfo::getFixedStack(
2732                            DAG.getMachineFunction(),
2733                            FuncInfo->getRegSaveFrameIndex(), Offset),
2734                        false, false, 0);
2735       MemOps.push_back(Store);
2736       Offset += 8;
2737     }
2738
2739     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2740       // Now store the XMM (fp + vector) parameter registers.
2741       SmallVector<SDValue, 12> SaveXMMOps;
2742       SaveXMMOps.push_back(Chain);
2743       SaveXMMOps.push_back(ALVal);
2744       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2745                              FuncInfo->getRegSaveFrameIndex(), dl));
2746       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2747                              FuncInfo->getVarArgsFPOffset(), dl));
2748       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2749                         LiveXMMRegs.end());
2750       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2751                                    MVT::Other, SaveXMMOps));
2752     }
2753
2754     if (!MemOps.empty())
2755       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2756   }
2757
2758   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2759     // Find the largest legal vector type.
2760     MVT VecVT = MVT::Other;
2761     // FIXME: Only some x86_32 calling conventions support AVX512.
2762     if (Subtarget->hasAVX512() &&
2763         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2764                      CallConv == CallingConv::Intel_OCL_BI)))
2765       VecVT = MVT::v16f32;
2766     else if (Subtarget->hasAVX())
2767       VecVT = MVT::v8f32;
2768     else if (Subtarget->hasSSE2())
2769       VecVT = MVT::v4f32;
2770
2771     // We forward some GPRs and some vector types.
2772     SmallVector<MVT, 2> RegParmTypes;
2773     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2774     RegParmTypes.push_back(IntVT);
2775     if (VecVT != MVT::Other)
2776       RegParmTypes.push_back(VecVT);
2777
2778     // Compute the set of forwarded registers. The rest are scratch.
2779     SmallVectorImpl<ForwardedRegister> &Forwards =
2780         FuncInfo->getForwardedMustTailRegParms();
2781     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2782
2783     // Conservatively forward AL on x86_64, since it might be used for varargs.
2784     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2785       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2786       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2787     }
2788
2789     // Copy all forwards from physical to virtual registers.
2790     for (ForwardedRegister &F : Forwards) {
2791       // FIXME: Can we use a less constrained schedule?
2792       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2793       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2794       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2795     }
2796   }
2797
2798   // Some CCs need callee pop.
2799   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2800                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2801     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2802   } else {
2803     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2804     // If this is an sret function, the return should pop the hidden pointer.
2805     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2806         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2807         argsAreStructReturn(Ins) == StackStructReturn)
2808       FuncInfo->setBytesToPopOnReturn(4);
2809   }
2810
2811   if (!Is64Bit) {
2812     // RegSaveFrameIndex is X86-64 only.
2813     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2814     if (CallConv == CallingConv::X86_FastCall ||
2815         CallConv == CallingConv::X86_ThisCall)
2816       // fastcc functions can't have varargs.
2817       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2818   }
2819
2820   FuncInfo->setArgumentStackSize(StackSize);
2821
2822   if (IsWinEHParent) {
2823     if (Is64Bit) {
2824       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2825       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2826       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2827       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2828       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2829                            MachinePointerInfo::getFixedStack(
2830                                DAG.getMachineFunction(), UnwindHelpFI),
2831                            /*isVolatile=*/true,
2832                            /*isNonTemporal=*/false, /*Alignment=*/0);
2833     } else {
2834       // Functions using Win32 EH are considered to have opaque SP adjustments
2835       // to force local variables to be addressed from the frame or base
2836       // pointers.
2837       MFI->setHasOpaqueSPAdjustment(true);
2838     }
2839   }
2840
2841   return Chain;
2842 }
2843
2844 SDValue
2845 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2846                                     SDValue StackPtr, SDValue Arg,
2847                                     SDLoc dl, SelectionDAG &DAG,
2848                                     const CCValAssign &VA,
2849                                     ISD::ArgFlagsTy Flags) const {
2850   unsigned LocMemOffset = VA.getLocMemOffset();
2851   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2852   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2853                        StackPtr, PtrOff);
2854   if (Flags.isByVal())
2855     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2856
2857   return DAG.getStore(
2858       Chain, dl, Arg, PtrOff,
2859       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2860       false, false, 0);
2861 }
2862
2863 /// Emit a load of return address if tail call
2864 /// optimization is performed and it is required.
2865 SDValue
2866 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2867                                            SDValue &OutRetAddr, SDValue Chain,
2868                                            bool IsTailCall, bool Is64Bit,
2869                                            int FPDiff, SDLoc dl) const {
2870   // Adjust the Return address stack slot.
2871   EVT VT = getPointerTy(DAG.getDataLayout());
2872   OutRetAddr = getReturnAddressFrameIndex(DAG);
2873
2874   // Load the "old" Return address.
2875   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2876                            false, false, false, 0);
2877   return SDValue(OutRetAddr.getNode(), 1);
2878 }
2879
2880 /// Emit a store of the return address if tail call
2881 /// optimization is performed and it is required (FPDiff!=0).
2882 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2883                                         SDValue Chain, SDValue RetAddrFrIdx,
2884                                         EVT PtrVT, unsigned SlotSize,
2885                                         int FPDiff, SDLoc dl) {
2886   // Store the return address to the appropriate stack slot.
2887   if (!FPDiff) return Chain;
2888   // Calculate the new stack slot for the return address.
2889   int NewReturnAddrFI =
2890     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2891                                          false);
2892   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2893   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2894                        MachinePointerInfo::getFixedStack(
2895                            DAG.getMachineFunction(), NewReturnAddrFI),
2896                        false, false, 0);
2897   return Chain;
2898 }
2899
2900 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2901 /// operation of specified width.
2902 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2903                        SDValue V2) {
2904   unsigned NumElems = VT.getVectorNumElements();
2905   SmallVector<int, 8> Mask;
2906   Mask.push_back(NumElems);
2907   for (unsigned i = 1; i != NumElems; ++i)
2908     Mask.push_back(i);
2909   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2910 }
2911
2912 SDValue
2913 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2914                              SmallVectorImpl<SDValue> &InVals) const {
2915   SelectionDAG &DAG                     = CLI.DAG;
2916   SDLoc &dl                             = CLI.DL;
2917   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2918   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2919   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2920   SDValue Chain                         = CLI.Chain;
2921   SDValue Callee                        = CLI.Callee;
2922   CallingConv::ID CallConv              = CLI.CallConv;
2923   bool &isTailCall                      = CLI.IsTailCall;
2924   bool isVarArg                         = CLI.IsVarArg;
2925
2926   MachineFunction &MF = DAG.getMachineFunction();
2927   bool Is64Bit        = Subtarget->is64Bit();
2928   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2929   StructReturnType SR = callIsStructReturn(Outs);
2930   bool IsSibcall      = false;
2931   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2932   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2933
2934   if (Attr.getValueAsString() == "true")
2935     isTailCall = false;
2936
2937   if (Subtarget->isPICStyleGOT() &&
2938       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2939     // If we are using a GOT, disable tail calls to external symbols with
2940     // default visibility. Tail calling such a symbol requires using a GOT
2941     // relocation, which forces early binding of the symbol. This breaks code
2942     // that require lazy function symbol resolution. Using musttail or
2943     // GuaranteedTailCallOpt will override this.
2944     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2945     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2946                G->getGlobal()->hasDefaultVisibility()))
2947       isTailCall = false;
2948   }
2949
2950   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2951   if (IsMustTail) {
2952     // Force this to be a tail call.  The verifier rules are enough to ensure
2953     // that we can lower this successfully without moving the return address
2954     // around.
2955     isTailCall = true;
2956   } else if (isTailCall) {
2957     // Check if it's really possible to do a tail call.
2958     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2959                     isVarArg, SR != NotStructReturn,
2960                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2961                     Outs, OutVals, Ins, DAG);
2962
2963     // Sibcalls are automatically detected tailcalls which do not require
2964     // ABI changes.
2965     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2966       IsSibcall = true;
2967
2968     if (isTailCall)
2969       ++NumTailCalls;
2970   }
2971
2972   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2973          "Var args not supported with calling convention fastcc, ghc or hipe");
2974
2975   // Analyze operands of the call, assigning locations to each operand.
2976   SmallVector<CCValAssign, 16> ArgLocs;
2977   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2978
2979   // Allocate shadow area for Win64
2980   if (IsWin64)
2981     CCInfo.AllocateStack(32, 8);
2982
2983   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2984
2985   // Get a count of how many bytes are to be pushed on the stack.
2986   unsigned NumBytes = CCInfo.getNextStackOffset();
2987   if (IsSibcall)
2988     // This is a sibcall. The memory operands are available in caller's
2989     // own caller's stack.
2990     NumBytes = 0;
2991   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2992            IsTailCallConvention(CallConv))
2993     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2994
2995   int FPDiff = 0;
2996   if (isTailCall && !IsSibcall && !IsMustTail) {
2997     // Lower arguments at fp - stackoffset + fpdiff.
2998     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2999
3000     FPDiff = NumBytesCallerPushed - NumBytes;
3001
3002     // Set the delta of movement of the returnaddr stackslot.
3003     // But only set if delta is greater than previous delta.
3004     if (FPDiff < X86Info->getTCReturnAddrDelta())
3005       X86Info->setTCReturnAddrDelta(FPDiff);
3006   }
3007
3008   unsigned NumBytesToPush = NumBytes;
3009   unsigned NumBytesToPop = NumBytes;
3010
3011   // If we have an inalloca argument, all stack space has already been allocated
3012   // for us and be right at the top of the stack.  We don't support multiple
3013   // arguments passed in memory when using inalloca.
3014   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3015     NumBytesToPush = 0;
3016     if (!ArgLocs.back().isMemLoc())
3017       report_fatal_error("cannot use inalloca attribute on a register "
3018                          "parameter");
3019     if (ArgLocs.back().getLocMemOffset() != 0)
3020       report_fatal_error("any parameter with the inalloca attribute must be "
3021                          "the only memory argument");
3022   }
3023
3024   if (!IsSibcall)
3025     Chain = DAG.getCALLSEQ_START(
3026         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3027
3028   SDValue RetAddrFrIdx;
3029   // Load return address for tail calls.
3030   if (isTailCall && FPDiff)
3031     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3032                                     Is64Bit, FPDiff, dl);
3033
3034   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3035   SmallVector<SDValue, 8> MemOpChains;
3036   SDValue StackPtr;
3037
3038   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3039   // of tail call optimization arguments are handle later.
3040   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3041   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3042     // Skip inalloca arguments, they have already been written.
3043     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3044     if (Flags.isInAlloca())
3045       continue;
3046
3047     CCValAssign &VA = ArgLocs[i];
3048     EVT RegVT = VA.getLocVT();
3049     SDValue Arg = OutVals[i];
3050     bool isByVal = Flags.isByVal();
3051
3052     // Promote the value if needed.
3053     switch (VA.getLocInfo()) {
3054     default: llvm_unreachable("Unknown loc info!");
3055     case CCValAssign::Full: break;
3056     case CCValAssign::SExt:
3057       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3058       break;
3059     case CCValAssign::ZExt:
3060       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3061       break;
3062     case CCValAssign::AExt:
3063       if (Arg.getValueType().isVector() &&
3064           Arg.getValueType().getScalarType() == MVT::i1)
3065         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3066       else if (RegVT.is128BitVector()) {
3067         // Special case: passing MMX values in XMM registers.
3068         Arg = DAG.getBitcast(MVT::i64, Arg);
3069         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3070         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3071       } else
3072         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3073       break;
3074     case CCValAssign::BCvt:
3075       Arg = DAG.getBitcast(RegVT, Arg);
3076       break;
3077     case CCValAssign::Indirect: {
3078       // Store the argument.
3079       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3080       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3081       Chain = DAG.getStore(
3082           Chain, dl, Arg, SpillSlot,
3083           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3084           false, false, 0);
3085       Arg = SpillSlot;
3086       break;
3087     }
3088     }
3089
3090     if (VA.isRegLoc()) {
3091       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3092       if (isVarArg && IsWin64) {
3093         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3094         // shadow reg if callee is a varargs function.
3095         unsigned ShadowReg = 0;
3096         switch (VA.getLocReg()) {
3097         case X86::XMM0: ShadowReg = X86::RCX; break;
3098         case X86::XMM1: ShadowReg = X86::RDX; break;
3099         case X86::XMM2: ShadowReg = X86::R8; break;
3100         case X86::XMM3: ShadowReg = X86::R9; break;
3101         }
3102         if (ShadowReg)
3103           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3104       }
3105     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3106       assert(VA.isMemLoc());
3107       if (!StackPtr.getNode())
3108         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3109                                       getPointerTy(DAG.getDataLayout()));
3110       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3111                                              dl, DAG, VA, Flags));
3112     }
3113   }
3114
3115   if (!MemOpChains.empty())
3116     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3117
3118   if (Subtarget->isPICStyleGOT()) {
3119     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3120     // GOT pointer.
3121     if (!isTailCall) {
3122       RegsToPass.push_back(std::make_pair(
3123           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3124                                           getPointerTy(DAG.getDataLayout()))));
3125     } else {
3126       // If we are tail calling and generating PIC/GOT style code load the
3127       // address of the callee into ECX. The value in ecx is used as target of
3128       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3129       // for tail calls on PIC/GOT architectures. Normally we would just put the
3130       // address of GOT into ebx and then call target@PLT. But for tail calls
3131       // ebx would be restored (since ebx is callee saved) before jumping to the
3132       // target@PLT.
3133
3134       // Note: The actual moving to ECX is done further down.
3135       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3136       if (G && !G->getGlobal()->hasLocalLinkage() &&
3137           G->getGlobal()->hasDefaultVisibility())
3138         Callee = LowerGlobalAddress(Callee, DAG);
3139       else if (isa<ExternalSymbolSDNode>(Callee))
3140         Callee = LowerExternalSymbol(Callee, DAG);
3141     }
3142   }
3143
3144   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3145     // From AMD64 ABI document:
3146     // For calls that may call functions that use varargs or stdargs
3147     // (prototype-less calls or calls to functions containing ellipsis (...) in
3148     // the declaration) %al is used as hidden argument to specify the number
3149     // of SSE registers used. The contents of %al do not need to match exactly
3150     // the number of registers, but must be an ubound on the number of SSE
3151     // registers used and is in the range 0 - 8 inclusive.
3152
3153     // Count the number of XMM registers allocated.
3154     static const MCPhysReg XMMArgRegs[] = {
3155       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3156       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3157     };
3158     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3159     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3160            && "SSE registers cannot be used when SSE is disabled");
3161
3162     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3163                                         DAG.getConstant(NumXMMRegs, dl,
3164                                                         MVT::i8)));
3165   }
3166
3167   if (isVarArg && IsMustTail) {
3168     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3169     for (const auto &F : Forwards) {
3170       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3171       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3172     }
3173   }
3174
3175   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3176   // don't need this because the eligibility check rejects calls that require
3177   // shuffling arguments passed in memory.
3178   if (!IsSibcall && isTailCall) {
3179     // Force all the incoming stack arguments to be loaded from the stack
3180     // before any new outgoing arguments are stored to the stack, because the
3181     // outgoing stack slots may alias the incoming argument stack slots, and
3182     // the alias isn't otherwise explicit. This is slightly more conservative
3183     // than necessary, because it means that each store effectively depends
3184     // on every argument instead of just those arguments it would clobber.
3185     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3186
3187     SmallVector<SDValue, 8> MemOpChains2;
3188     SDValue FIN;
3189     int FI = 0;
3190     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3191       CCValAssign &VA = ArgLocs[i];
3192       if (VA.isRegLoc())
3193         continue;
3194       assert(VA.isMemLoc());
3195       SDValue Arg = OutVals[i];
3196       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3197       // Skip inalloca arguments.  They don't require any work.
3198       if (Flags.isInAlloca())
3199         continue;
3200       // Create frame index.
3201       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3202       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3203       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3204       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3205
3206       if (Flags.isByVal()) {
3207         // Copy relative to framepointer.
3208         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3209         if (!StackPtr.getNode())
3210           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3211                                         getPointerTy(DAG.getDataLayout()));
3212         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3213                              StackPtr, Source);
3214
3215         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3216                                                          ArgChain,
3217                                                          Flags, DAG, dl));
3218       } else {
3219         // Store relative to framepointer.
3220         MemOpChains2.push_back(DAG.getStore(
3221             ArgChain, dl, Arg, FIN,
3222             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3223             false, false, 0));
3224       }
3225     }
3226
3227     if (!MemOpChains2.empty())
3228       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3229
3230     // Store the return address to the appropriate stack slot.
3231     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3232                                      getPointerTy(DAG.getDataLayout()),
3233                                      RegInfo->getSlotSize(), FPDiff, dl);
3234   }
3235
3236   // Build a sequence of copy-to-reg nodes chained together with token chain
3237   // and flag operands which copy the outgoing args into registers.
3238   SDValue InFlag;
3239   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3240     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3241                              RegsToPass[i].second, InFlag);
3242     InFlag = Chain.getValue(1);
3243   }
3244
3245   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3246     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3247     // In the 64-bit large code model, we have to make all calls
3248     // through a register, since the call instruction's 32-bit
3249     // pc-relative offset may not be large enough to hold the whole
3250     // address.
3251   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3252     // If the callee is a GlobalAddress node (quite common, every direct call
3253     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3254     // it.
3255     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3256
3257     // We should use extra load for direct calls to dllimported functions in
3258     // non-JIT mode.
3259     const GlobalValue *GV = G->getGlobal();
3260     if (!GV->hasDLLImportStorageClass()) {
3261       unsigned char OpFlags = 0;
3262       bool ExtraLoad = false;
3263       unsigned WrapperKind = ISD::DELETED_NODE;
3264
3265       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3266       // external symbols most go through the PLT in PIC mode.  If the symbol
3267       // has hidden or protected visibility, or if it is static or local, then
3268       // we don't need to use the PLT - we can directly call it.
3269       if (Subtarget->isTargetELF() &&
3270           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3271           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3272         OpFlags = X86II::MO_PLT;
3273       } else if (Subtarget->isPICStyleStubAny() &&
3274                  !GV->isStrongDefinitionForLinker() &&
3275                  (!Subtarget->getTargetTriple().isMacOSX() ||
3276                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3277         // PC-relative references to external symbols should go through $stub,
3278         // unless we're building with the leopard linker or later, which
3279         // automatically synthesizes these stubs.
3280         OpFlags = X86II::MO_DARWIN_STUB;
3281       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3282                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3283         // If the function is marked as non-lazy, generate an indirect call
3284         // which loads from the GOT directly. This avoids runtime overhead
3285         // at the cost of eager binding (and one extra byte of encoding).
3286         OpFlags = X86II::MO_GOTPCREL;
3287         WrapperKind = X86ISD::WrapperRIP;
3288         ExtraLoad = true;
3289       }
3290
3291       Callee = DAG.getTargetGlobalAddress(
3292           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3293
3294       // Add a wrapper if needed.
3295       if (WrapperKind != ISD::DELETED_NODE)
3296         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3297                              getPointerTy(DAG.getDataLayout()), Callee);
3298       // Add extra indirection if needed.
3299       if (ExtraLoad)
3300         Callee = DAG.getLoad(
3301             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3302             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3303             false, 0);
3304     }
3305   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3306     unsigned char OpFlags = 0;
3307
3308     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3309     // external symbols should go through the PLT.
3310     if (Subtarget->isTargetELF() &&
3311         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3312       OpFlags = X86II::MO_PLT;
3313     } else if (Subtarget->isPICStyleStubAny() &&
3314                (!Subtarget->getTargetTriple().isMacOSX() ||
3315                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3316       // PC-relative references to external symbols should go through $stub,
3317       // unless we're building with the leopard linker or later, which
3318       // automatically synthesizes these stubs.
3319       OpFlags = X86II::MO_DARWIN_STUB;
3320     }
3321
3322     Callee = DAG.getTargetExternalSymbol(
3323         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3324   } else if (Subtarget->isTarget64BitILP32() &&
3325              Callee->getValueType(0) == MVT::i32) {
3326     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3327     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3328   }
3329
3330   // Returns a chain & a flag for retval copy to use.
3331   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3332   SmallVector<SDValue, 8> Ops;
3333
3334   if (!IsSibcall && isTailCall) {
3335     Chain = DAG.getCALLSEQ_END(Chain,
3336                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3337                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3338     InFlag = Chain.getValue(1);
3339   }
3340
3341   Ops.push_back(Chain);
3342   Ops.push_back(Callee);
3343
3344   if (isTailCall)
3345     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3346
3347   // Add argument registers to the end of the list so that they are known live
3348   // into the call.
3349   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3350     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3351                                   RegsToPass[i].second.getValueType()));
3352
3353   // Add a register mask operand representing the call-preserved registers.
3354   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3355   assert(Mask && "Missing call preserved mask for calling convention");
3356
3357   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3358   // the function clobbers all registers. If an exception is thrown, the runtime
3359   // will not restore CSRs.
3360   // FIXME: Model this more precisely so that we can register allocate across
3361   // the normal edge and spill and fill across the exceptional edge.
3362   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3363     const Function *CallerFn = MF.getFunction();
3364     EHPersonality Pers =
3365         CallerFn->hasPersonalityFn()
3366             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3367             : EHPersonality::Unknown;
3368     if (isMSVCEHPersonality(Pers))
3369       Mask = RegInfo->getNoPreservedMask();
3370   }
3371
3372   Ops.push_back(DAG.getRegisterMask(Mask));
3373
3374   if (InFlag.getNode())
3375     Ops.push_back(InFlag);
3376
3377   if (isTailCall) {
3378     // We used to do:
3379     //// If this is the first return lowered for this function, add the regs
3380     //// to the liveout set for the function.
3381     // This isn't right, although it's probably harmless on x86; liveouts
3382     // should be computed from returns not tail calls.  Consider a void
3383     // function making a tail call to a function returning int.
3384     MF.getFrameInfo()->setHasTailCall();
3385     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3386   }
3387
3388   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3389   InFlag = Chain.getValue(1);
3390
3391   // Create the CALLSEQ_END node.
3392   unsigned NumBytesForCalleeToPop;
3393   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3394                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3395     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3396   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3397            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3398            SR == StackStructReturn)
3399     // If this is a call to a struct-return function, the callee
3400     // pops the hidden struct pointer, so we have to push it back.
3401     // This is common for Darwin/X86, Linux & Mingw32 targets.
3402     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3403     NumBytesForCalleeToPop = 4;
3404   else
3405     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3406
3407   // Returns a flag for retval copy to use.
3408   if (!IsSibcall) {
3409     Chain = DAG.getCALLSEQ_END(Chain,
3410                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3411                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3412                                                      true),
3413                                InFlag, dl);
3414     InFlag = Chain.getValue(1);
3415   }
3416
3417   // Handle result values, copying them out of physregs into vregs that we
3418   // return.
3419   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3420                          Ins, dl, DAG, InVals);
3421 }
3422
3423 //===----------------------------------------------------------------------===//
3424 //                Fast Calling Convention (tail call) implementation
3425 //===----------------------------------------------------------------------===//
3426
3427 //  Like std call, callee cleans arguments, convention except that ECX is
3428 //  reserved for storing the tail called function address. Only 2 registers are
3429 //  free for argument passing (inreg). Tail call optimization is performed
3430 //  provided:
3431 //                * tailcallopt is enabled
3432 //                * caller/callee are fastcc
3433 //  On X86_64 architecture with GOT-style position independent code only local
3434 //  (within module) calls are supported at the moment.
3435 //  To keep the stack aligned according to platform abi the function
3436 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3437 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3438 //  If a tail called function callee has more arguments than the caller the
3439 //  caller needs to make sure that there is room to move the RETADDR to. This is
3440 //  achieved by reserving an area the size of the argument delta right after the
3441 //  original RETADDR, but before the saved framepointer or the spilled registers
3442 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3443 //  stack layout:
3444 //    arg1
3445 //    arg2
3446 //    RETADDR
3447 //    [ new RETADDR
3448 //      move area ]
3449 //    (possible EBP)
3450 //    ESI
3451 //    EDI
3452 //    local1 ..
3453
3454 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3455 /// requirement.
3456 unsigned
3457 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3458                                                SelectionDAG& DAG) const {
3459   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3460   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3461   unsigned StackAlignment = TFI.getStackAlignment();
3462   uint64_t AlignMask = StackAlignment - 1;
3463   int64_t Offset = StackSize;
3464   unsigned SlotSize = RegInfo->getSlotSize();
3465   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3466     // Number smaller than 12 so just add the difference.
3467     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3468   } else {
3469     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3470     Offset = ((~AlignMask) & Offset) + StackAlignment +
3471       (StackAlignment-SlotSize);
3472   }
3473   return Offset;
3474 }
3475
3476 /// Return true if the given stack call argument is already available in the
3477 /// same position (relatively) of the caller's incoming argument stack.
3478 static
3479 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3480                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3481                          const X86InstrInfo *TII) {
3482   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3483   int FI = INT_MAX;
3484   if (Arg.getOpcode() == ISD::CopyFromReg) {
3485     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3486     if (!TargetRegisterInfo::isVirtualRegister(VR))
3487       return false;
3488     MachineInstr *Def = MRI->getVRegDef(VR);
3489     if (!Def)
3490       return false;
3491     if (!Flags.isByVal()) {
3492       if (!TII->isLoadFromStackSlot(Def, FI))
3493         return false;
3494     } else {
3495       unsigned Opcode = Def->getOpcode();
3496       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3497            Opcode == X86::LEA64_32r) &&
3498           Def->getOperand(1).isFI()) {
3499         FI = Def->getOperand(1).getIndex();
3500         Bytes = Flags.getByValSize();
3501       } else
3502         return false;
3503     }
3504   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3505     if (Flags.isByVal())
3506       // ByVal argument is passed in as a pointer but it's now being
3507       // dereferenced. e.g.
3508       // define @foo(%struct.X* %A) {
3509       //   tail call @bar(%struct.X* byval %A)
3510       // }
3511       return false;
3512     SDValue Ptr = Ld->getBasePtr();
3513     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3514     if (!FINode)
3515       return false;
3516     FI = FINode->getIndex();
3517   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3518     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3519     FI = FINode->getIndex();
3520     Bytes = Flags.getByValSize();
3521   } else
3522     return false;
3523
3524   assert(FI != INT_MAX);
3525   if (!MFI->isFixedObjectIndex(FI))
3526     return false;
3527   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3528 }
3529
3530 /// Check whether the call is eligible for tail call optimization. Targets
3531 /// that want to do tail call optimization should implement this function.
3532 bool
3533 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3534                                                      CallingConv::ID CalleeCC,
3535                                                      bool isVarArg,
3536                                                      bool isCalleeStructRet,
3537                                                      bool isCallerStructRet,
3538                                                      Type *RetTy,
3539                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3540                                     const SmallVectorImpl<SDValue> &OutVals,
3541                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3542                                                      SelectionDAG &DAG) const {
3543   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3544     return false;
3545
3546   // If -tailcallopt is specified, make fastcc functions tail-callable.
3547   const MachineFunction &MF = DAG.getMachineFunction();
3548   const Function *CallerF = MF.getFunction();
3549
3550   // If the function return type is x86_fp80 and the callee return type is not,
3551   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3552   // perform a tailcall optimization here.
3553   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3554     return false;
3555
3556   CallingConv::ID CallerCC = CallerF->getCallingConv();
3557   bool CCMatch = CallerCC == CalleeCC;
3558   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3559   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3560
3561   // Win64 functions have extra shadow space for argument homing. Don't do the
3562   // sibcall if the caller and callee have mismatched expectations for this
3563   // space.
3564   if (IsCalleeWin64 != IsCallerWin64)
3565     return false;
3566
3567   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3568     if (IsTailCallConvention(CalleeCC) && CCMatch)
3569       return true;
3570     return false;
3571   }
3572
3573   // Look for obvious safe cases to perform tail call optimization that do not
3574   // require ABI changes. This is what gcc calls sibcall.
3575
3576   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3577   // emit a special epilogue.
3578   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3579   if (RegInfo->needsStackRealignment(MF))
3580     return false;
3581
3582   // Also avoid sibcall optimization if either caller or callee uses struct
3583   // return semantics.
3584   if (isCalleeStructRet || isCallerStructRet)
3585     return false;
3586
3587   // An stdcall/thiscall caller is expected to clean up its arguments; the
3588   // callee isn't going to do that.
3589   // FIXME: this is more restrictive than needed. We could produce a tailcall
3590   // when the stack adjustment matches. For example, with a thiscall that takes
3591   // only one argument.
3592   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3593                    CallerCC == CallingConv::X86_ThisCall))
3594     return false;
3595
3596   // Do not sibcall optimize vararg calls unless all arguments are passed via
3597   // registers.
3598   if (isVarArg && !Outs.empty()) {
3599
3600     // Optimizing for varargs on Win64 is unlikely to be safe without
3601     // additional testing.
3602     if (IsCalleeWin64 || IsCallerWin64)
3603       return false;
3604
3605     SmallVector<CCValAssign, 16> ArgLocs;
3606     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3607                    *DAG.getContext());
3608
3609     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3610     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3611       if (!ArgLocs[i].isRegLoc())
3612         return false;
3613   }
3614
3615   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3616   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3617   // this into a sibcall.
3618   bool Unused = false;
3619   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3620     if (!Ins[i].Used) {
3621       Unused = true;
3622       break;
3623     }
3624   }
3625   if (Unused) {
3626     SmallVector<CCValAssign, 16> RVLocs;
3627     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3628                    *DAG.getContext());
3629     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3630     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3631       CCValAssign &VA = RVLocs[i];
3632       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3633         return false;
3634     }
3635   }
3636
3637   // If the calling conventions do not match, then we'd better make sure the
3638   // results are returned in the same way as what the caller expects.
3639   if (!CCMatch) {
3640     SmallVector<CCValAssign, 16> RVLocs1;
3641     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3642                     *DAG.getContext());
3643     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3644
3645     SmallVector<CCValAssign, 16> RVLocs2;
3646     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3647                     *DAG.getContext());
3648     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3649
3650     if (RVLocs1.size() != RVLocs2.size())
3651       return false;
3652     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3653       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3654         return false;
3655       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3656         return false;
3657       if (RVLocs1[i].isRegLoc()) {
3658         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3659           return false;
3660       } else {
3661         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3662           return false;
3663       }
3664     }
3665   }
3666
3667   // If the callee takes no arguments then go on to check the results of the
3668   // call.
3669   if (!Outs.empty()) {
3670     // Check if stack adjustment is needed. For now, do not do this if any
3671     // argument is passed on the stack.
3672     SmallVector<CCValAssign, 16> ArgLocs;
3673     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3674                    *DAG.getContext());
3675
3676     // Allocate shadow area for Win64
3677     if (IsCalleeWin64)
3678       CCInfo.AllocateStack(32, 8);
3679
3680     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3681     if (CCInfo.getNextStackOffset()) {
3682       MachineFunction &MF = DAG.getMachineFunction();
3683       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3684         return false;
3685
3686       // Check if the arguments are already laid out in the right way as
3687       // the caller's fixed stack objects.
3688       MachineFrameInfo *MFI = MF.getFrameInfo();
3689       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3690       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3691       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3692         CCValAssign &VA = ArgLocs[i];
3693         SDValue Arg = OutVals[i];
3694         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3695         if (VA.getLocInfo() == CCValAssign::Indirect)
3696           return false;
3697         if (!VA.isRegLoc()) {
3698           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3699                                    MFI, MRI, TII))
3700             return false;
3701         }
3702       }
3703     }
3704
3705     // If the tailcall address may be in a register, then make sure it's
3706     // possible to register allocate for it. In 32-bit, the call address can
3707     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3708     // callee-saved registers are restored. These happen to be the same
3709     // registers used to pass 'inreg' arguments so watch out for those.
3710     if (!Subtarget->is64Bit() &&
3711         ((!isa<GlobalAddressSDNode>(Callee) &&
3712           !isa<ExternalSymbolSDNode>(Callee)) ||
3713          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3714       unsigned NumInRegs = 0;
3715       // In PIC we need an extra register to formulate the address computation
3716       // for the callee.
3717       unsigned MaxInRegs =
3718         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3719
3720       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3721         CCValAssign &VA = ArgLocs[i];
3722         if (!VA.isRegLoc())
3723           continue;
3724         unsigned Reg = VA.getLocReg();
3725         switch (Reg) {
3726         default: break;
3727         case X86::EAX: case X86::EDX: case X86::ECX:
3728           if (++NumInRegs == MaxInRegs)
3729             return false;
3730           break;
3731         }
3732       }
3733     }
3734   }
3735
3736   return true;
3737 }
3738
3739 FastISel *
3740 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3741                                   const TargetLibraryInfo *libInfo) const {
3742   return X86::createFastISel(funcInfo, libInfo);
3743 }
3744
3745 //===----------------------------------------------------------------------===//
3746 //                           Other Lowering Hooks
3747 //===----------------------------------------------------------------------===//
3748
3749 static bool MayFoldLoad(SDValue Op) {
3750   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3751 }
3752
3753 static bool MayFoldIntoStore(SDValue Op) {
3754   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3755 }
3756
3757 static bool isTargetShuffle(unsigned Opcode) {
3758   switch(Opcode) {
3759   default: return false;
3760   case X86ISD::BLENDI:
3761   case X86ISD::PSHUFB:
3762   case X86ISD::PSHUFD:
3763   case X86ISD::PSHUFHW:
3764   case X86ISD::PSHUFLW:
3765   case X86ISD::SHUFP:
3766   case X86ISD::PALIGNR:
3767   case X86ISD::MOVLHPS:
3768   case X86ISD::MOVLHPD:
3769   case X86ISD::MOVHLPS:
3770   case X86ISD::MOVLPS:
3771   case X86ISD::MOVLPD:
3772   case X86ISD::MOVSHDUP:
3773   case X86ISD::MOVSLDUP:
3774   case X86ISD::MOVDDUP:
3775   case X86ISD::MOVSS:
3776   case X86ISD::MOVSD:
3777   case X86ISD::UNPCKL:
3778   case X86ISD::UNPCKH:
3779   case X86ISD::VPERMILPI:
3780   case X86ISD::VPERM2X128:
3781   case X86ISD::VPERMI:
3782   case X86ISD::VPERMV:
3783   case X86ISD::VPERMV3:
3784     return true;
3785   }
3786 }
3787
3788 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3789                                     SDValue V1, unsigned TargetMask,
3790                                     SelectionDAG &DAG) {
3791   switch(Opc) {
3792   default: llvm_unreachable("Unknown x86 shuffle node");
3793   case X86ISD::PSHUFD:
3794   case X86ISD::PSHUFHW:
3795   case X86ISD::PSHUFLW:
3796   case X86ISD::VPERMILPI:
3797   case X86ISD::VPERMI:
3798     return DAG.getNode(Opc, dl, VT, V1,
3799                        DAG.getConstant(TargetMask, dl, MVT::i8));
3800   }
3801 }
3802
3803 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3804                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3805   switch(Opc) {
3806   default: llvm_unreachable("Unknown x86 shuffle node");
3807   case X86ISD::MOVLHPS:
3808   case X86ISD::MOVLHPD:
3809   case X86ISD::MOVHLPS:
3810   case X86ISD::MOVLPS:
3811   case X86ISD::MOVLPD:
3812   case X86ISD::MOVSS:
3813   case X86ISD::MOVSD:
3814   case X86ISD::UNPCKL:
3815   case X86ISD::UNPCKH:
3816     return DAG.getNode(Opc, dl, VT, V1, V2);
3817   }
3818 }
3819
3820 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3821   MachineFunction &MF = DAG.getMachineFunction();
3822   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3823   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3824   int ReturnAddrIndex = FuncInfo->getRAIndex();
3825
3826   if (ReturnAddrIndex == 0) {
3827     // Set up a frame object for the return address.
3828     unsigned SlotSize = RegInfo->getSlotSize();
3829     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3830                                                            -(int64_t)SlotSize,
3831                                                            false);
3832     FuncInfo->setRAIndex(ReturnAddrIndex);
3833   }
3834
3835   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3836 }
3837
3838 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3839                                        bool hasSymbolicDisplacement) {
3840   // Offset should fit into 32 bit immediate field.
3841   if (!isInt<32>(Offset))
3842     return false;
3843
3844   // If we don't have a symbolic displacement - we don't have any extra
3845   // restrictions.
3846   if (!hasSymbolicDisplacement)
3847     return true;
3848
3849   // FIXME: Some tweaks might be needed for medium code model.
3850   if (M != CodeModel::Small && M != CodeModel::Kernel)
3851     return false;
3852
3853   // For small code model we assume that latest object is 16MB before end of 31
3854   // bits boundary. We may also accept pretty large negative constants knowing
3855   // that all objects are in the positive half of address space.
3856   if (M == CodeModel::Small && Offset < 16*1024*1024)
3857     return true;
3858
3859   // For kernel code model we know that all object resist in the negative half
3860   // of 32bits address space. We may not accept negative offsets, since they may
3861   // be just off and we may accept pretty large positive ones.
3862   if (M == CodeModel::Kernel && Offset >= 0)
3863     return true;
3864
3865   return false;
3866 }
3867
3868 /// Determines whether the callee is required to pop its own arguments.
3869 /// Callee pop is necessary to support tail calls.
3870 bool X86::isCalleePop(CallingConv::ID CallingConv,
3871                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3872   switch (CallingConv) {
3873   default:
3874     return false;
3875   case CallingConv::X86_StdCall:
3876   case CallingConv::X86_FastCall:
3877   case CallingConv::X86_ThisCall:
3878     return !is64Bit;
3879   case CallingConv::Fast:
3880   case CallingConv::GHC:
3881   case CallingConv::HiPE:
3882     if (IsVarArg)
3883       return false;
3884     return TailCallOpt;
3885   }
3886 }
3887
3888 /// \brief Return true if the condition is an unsigned comparison operation.
3889 static bool isX86CCUnsigned(unsigned X86CC) {
3890   switch (X86CC) {
3891   default: llvm_unreachable("Invalid integer condition!");
3892   case X86::COND_E:     return true;
3893   case X86::COND_G:     return false;
3894   case X86::COND_GE:    return false;
3895   case X86::COND_L:     return false;
3896   case X86::COND_LE:    return false;
3897   case X86::COND_NE:    return true;
3898   case X86::COND_B:     return true;
3899   case X86::COND_A:     return true;
3900   case X86::COND_BE:    return true;
3901   case X86::COND_AE:    return true;
3902   }
3903   llvm_unreachable("covered switch fell through?!");
3904 }
3905
3906 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3907 /// condition code, returning the condition code and the LHS/RHS of the
3908 /// comparison to make.
3909 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3910                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3911   if (!isFP) {
3912     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3913       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3914         // X > -1   -> X == 0, jump !sign.
3915         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3916         return X86::COND_NS;
3917       }
3918       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3919         // X < 0   -> X == 0, jump on sign.
3920         return X86::COND_S;
3921       }
3922       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3923         // X < 1   -> X <= 0
3924         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3925         return X86::COND_LE;
3926       }
3927     }
3928
3929     switch (SetCCOpcode) {
3930     default: llvm_unreachable("Invalid integer condition!");
3931     case ISD::SETEQ:  return X86::COND_E;
3932     case ISD::SETGT:  return X86::COND_G;
3933     case ISD::SETGE:  return X86::COND_GE;
3934     case ISD::SETLT:  return X86::COND_L;
3935     case ISD::SETLE:  return X86::COND_LE;
3936     case ISD::SETNE:  return X86::COND_NE;
3937     case ISD::SETULT: return X86::COND_B;
3938     case ISD::SETUGT: return X86::COND_A;
3939     case ISD::SETULE: return X86::COND_BE;
3940     case ISD::SETUGE: return X86::COND_AE;
3941     }
3942   }
3943
3944   // First determine if it is required or is profitable to flip the operands.
3945
3946   // If LHS is a foldable load, but RHS is not, flip the condition.
3947   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3948       !ISD::isNON_EXTLoad(RHS.getNode())) {
3949     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3950     std::swap(LHS, RHS);
3951   }
3952
3953   switch (SetCCOpcode) {
3954   default: break;
3955   case ISD::SETOLT:
3956   case ISD::SETOLE:
3957   case ISD::SETUGT:
3958   case ISD::SETUGE:
3959     std::swap(LHS, RHS);
3960     break;
3961   }
3962
3963   // On a floating point condition, the flags are set as follows:
3964   // ZF  PF  CF   op
3965   //  0 | 0 | 0 | X > Y
3966   //  0 | 0 | 1 | X < Y
3967   //  1 | 0 | 0 | X == Y
3968   //  1 | 1 | 1 | unordered
3969   switch (SetCCOpcode) {
3970   default: llvm_unreachable("Condcode should be pre-legalized away");
3971   case ISD::SETUEQ:
3972   case ISD::SETEQ:   return X86::COND_E;
3973   case ISD::SETOLT:              // flipped
3974   case ISD::SETOGT:
3975   case ISD::SETGT:   return X86::COND_A;
3976   case ISD::SETOLE:              // flipped
3977   case ISD::SETOGE:
3978   case ISD::SETGE:   return X86::COND_AE;
3979   case ISD::SETUGT:              // flipped
3980   case ISD::SETULT:
3981   case ISD::SETLT:   return X86::COND_B;
3982   case ISD::SETUGE:              // flipped
3983   case ISD::SETULE:
3984   case ISD::SETLE:   return X86::COND_BE;
3985   case ISD::SETONE:
3986   case ISD::SETNE:   return X86::COND_NE;
3987   case ISD::SETUO:   return X86::COND_P;
3988   case ISD::SETO:    return X86::COND_NP;
3989   case ISD::SETOEQ:
3990   case ISD::SETUNE:  return X86::COND_INVALID;
3991   }
3992 }
3993
3994 /// Is there a floating point cmov for the specific X86 condition code?
3995 /// Current x86 isa includes the following FP cmov instructions:
3996 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3997 static bool hasFPCMov(unsigned X86CC) {
3998   switch (X86CC) {
3999   default:
4000     return false;
4001   case X86::COND_B:
4002   case X86::COND_BE:
4003   case X86::COND_E:
4004   case X86::COND_P:
4005   case X86::COND_A:
4006   case X86::COND_AE:
4007   case X86::COND_NE:
4008   case X86::COND_NP:
4009     return true;
4010   }
4011 }
4012
4013 /// Returns true if the target can instruction select the
4014 /// specified FP immediate natively. If false, the legalizer will
4015 /// materialize the FP immediate as a load from a constant pool.
4016 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4017   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4018     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4019       return true;
4020   }
4021   return false;
4022 }
4023
4024 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4025                                               ISD::LoadExtType ExtTy,
4026                                               EVT NewVT) const {
4027   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4028   // relocation target a movq or addq instruction: don't let the load shrink.
4029   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4030   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4031     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4032       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4033   return true;
4034 }
4035
4036 /// \brief Returns true if it is beneficial to convert a load of a constant
4037 /// to just the constant itself.
4038 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4039                                                           Type *Ty) const {
4040   assert(Ty->isIntegerTy());
4041
4042   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4043   if (BitSize == 0 || BitSize > 64)
4044     return false;
4045   return true;
4046 }
4047
4048 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4049                                                 unsigned Index) const {
4050   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4051     return false;
4052
4053   return (Index == 0 || Index == ResVT.getVectorNumElements());
4054 }
4055
4056 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4057   // Speculate cttz only if we can directly use TZCNT.
4058   return Subtarget->hasBMI();
4059 }
4060
4061 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4062   // Speculate ctlz only if we can directly use LZCNT.
4063   return Subtarget->hasLZCNT();
4064 }
4065
4066 /// Return true if every element in Mask, beginning
4067 /// from position Pos and ending in Pos+Size is undef.
4068 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4069   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4070     if (0 <= Mask[i])
4071       return false;
4072   return true;
4073 }
4074
4075 /// Return true if Val is undef or if its value falls within the
4076 /// specified range (L, H].
4077 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4078   return (Val < 0) || (Val >= Low && Val < Hi);
4079 }
4080
4081 /// Val is either less than zero (undef) or equal to the specified value.
4082 static bool isUndefOrEqual(int Val, int CmpVal) {
4083   return (Val < 0 || Val == CmpVal);
4084 }
4085
4086 /// Return true if every element in Mask, beginning
4087 /// from position Pos and ending in Pos+Size, falls within the specified
4088 /// sequential range (Low, Low+Size]. or is undef.
4089 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4090                                        unsigned Pos, unsigned Size, int Low) {
4091   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4092     if (!isUndefOrEqual(Mask[i], Low))
4093       return false;
4094   return true;
4095 }
4096
4097 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4098 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4099 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4100   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4101   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4102     return false;
4103
4104   // The index should be aligned on a vecWidth-bit boundary.
4105   uint64_t Index =
4106     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4107
4108   MVT VT = N->getSimpleValueType(0);
4109   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4110   bool Result = (Index * ElSize) % vecWidth == 0;
4111
4112   return Result;
4113 }
4114
4115 /// Return true if the specified INSERT_SUBVECTOR
4116 /// operand specifies a subvector insert that is suitable for input to
4117 /// insertion of 128 or 256-bit subvectors
4118 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4119   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4120   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4121     return false;
4122   // The index should be aligned on a vecWidth-bit boundary.
4123   uint64_t Index =
4124     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4125
4126   MVT VT = N->getSimpleValueType(0);
4127   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4128   bool Result = (Index * ElSize) % vecWidth == 0;
4129
4130   return Result;
4131 }
4132
4133 bool X86::isVINSERT128Index(SDNode *N) {
4134   return isVINSERTIndex(N, 128);
4135 }
4136
4137 bool X86::isVINSERT256Index(SDNode *N) {
4138   return isVINSERTIndex(N, 256);
4139 }
4140
4141 bool X86::isVEXTRACT128Index(SDNode *N) {
4142   return isVEXTRACTIndex(N, 128);
4143 }
4144
4145 bool X86::isVEXTRACT256Index(SDNode *N) {
4146   return isVEXTRACTIndex(N, 256);
4147 }
4148
4149 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4150   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4151   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4152     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4153
4154   uint64_t Index =
4155     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4156
4157   MVT VecVT = N->getOperand(0).getSimpleValueType();
4158   MVT ElVT = VecVT.getVectorElementType();
4159
4160   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4161   return Index / NumElemsPerChunk;
4162 }
4163
4164 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4165   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4166   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4167     llvm_unreachable("Illegal insert subvector for VINSERT");
4168
4169   uint64_t Index =
4170     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4171
4172   MVT VecVT = N->getSimpleValueType(0);
4173   MVT ElVT = VecVT.getVectorElementType();
4174
4175   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4176   return Index / NumElemsPerChunk;
4177 }
4178
4179 /// Return the appropriate immediate to extract the specified
4180 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4181 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4182   return getExtractVEXTRACTImmediate(N, 128);
4183 }
4184
4185 /// Return the appropriate immediate to extract the specified
4186 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4187 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4188   return getExtractVEXTRACTImmediate(N, 256);
4189 }
4190
4191 /// Return the appropriate immediate to insert at the specified
4192 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4193 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4194   return getInsertVINSERTImmediate(N, 128);
4195 }
4196
4197 /// Return the appropriate immediate to insert at the specified
4198 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4199 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4200   return getInsertVINSERTImmediate(N, 256);
4201 }
4202
4203 /// Returns true if Elt is a constant integer zero
4204 static bool isZero(SDValue V) {
4205   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4206   return C && C->isNullValue();
4207 }
4208
4209 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4210 bool X86::isZeroNode(SDValue Elt) {
4211   if (isZero(Elt))
4212     return true;
4213   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4214     return CFP->getValueAPF().isPosZero();
4215   return false;
4216 }
4217
4218 /// Returns a vector of specified type with all zero elements.
4219 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4220                              SelectionDAG &DAG, SDLoc dl) {
4221   assert(VT.isVector() && "Expected a vector type");
4222
4223   // Always build SSE zero vectors as <4 x i32> bitcasted
4224   // to their dest type. This ensures they get CSE'd.
4225   SDValue Vec;
4226   if (VT.is128BitVector()) {  // SSE
4227     if (Subtarget->hasSSE2()) {  // SSE2
4228       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4229       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4230     } else { // SSE1
4231       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4232       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4233     }
4234   } else if (VT.is256BitVector()) { // AVX
4235     if (Subtarget->hasInt256()) { // AVX2
4236       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4237       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4238       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4239     } else {
4240       // 256-bit logic and arithmetic instructions in AVX are all
4241       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4242       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4243       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4244       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4245     }
4246   } else if (VT.is512BitVector()) { // AVX-512
4247       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4248       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4249                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4250       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4251   } else if (VT.getScalarType() == MVT::i1) {
4252
4253     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4254             && "Unexpected vector type");
4255     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4256             && "Unexpected vector type");
4257     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4258     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4259     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4260   } else
4261     llvm_unreachable("Unexpected vector type");
4262
4263   return DAG.getBitcast(VT, Vec);
4264 }
4265
4266 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4267                                 SelectionDAG &DAG, SDLoc dl,
4268                                 unsigned vectorWidth) {
4269   assert((vectorWidth == 128 || vectorWidth == 256) &&
4270          "Unsupported vector width");
4271   EVT VT = Vec.getValueType();
4272   EVT ElVT = VT.getVectorElementType();
4273   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4274   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4275                                   VT.getVectorNumElements()/Factor);
4276
4277   // Extract from UNDEF is UNDEF.
4278   if (Vec.getOpcode() == ISD::UNDEF)
4279     return DAG.getUNDEF(ResultVT);
4280
4281   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4282   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4283
4284   // This is the index of the first element of the vectorWidth-bit chunk
4285   // we want.
4286   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4287                                * ElemsPerChunk);
4288
4289   // If the input is a buildvector just emit a smaller one.
4290   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4291     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4292                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4293                                     ElemsPerChunk));
4294
4295   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4296   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4297 }
4298
4299 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4300 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4301 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4302 /// instructions or a simple subregister reference. Idx is an index in the
4303 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4304 /// lowering EXTRACT_VECTOR_ELT operations easier.
4305 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4306                                    SelectionDAG &DAG, SDLoc dl) {
4307   assert((Vec.getValueType().is256BitVector() ||
4308           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4309   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4310 }
4311
4312 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4313 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4314                                    SelectionDAG &DAG, SDLoc dl) {
4315   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4316   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4317 }
4318
4319 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4320                                unsigned IdxVal, SelectionDAG &DAG,
4321                                SDLoc dl, unsigned vectorWidth) {
4322   assert((vectorWidth == 128 || vectorWidth == 256) &&
4323          "Unsupported vector width");
4324   // Inserting UNDEF is Result
4325   if (Vec.getOpcode() == ISD::UNDEF)
4326     return Result;
4327   EVT VT = Vec.getValueType();
4328   EVT ElVT = VT.getVectorElementType();
4329   EVT ResultVT = Result.getValueType();
4330
4331   // Insert the relevant vectorWidth bits.
4332   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4333
4334   // This is the index of the first element of the vectorWidth-bit chunk
4335   // we want.
4336   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4337                                * ElemsPerChunk);
4338
4339   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4340   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4341 }
4342
4343 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4344 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4345 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4346 /// simple superregister reference.  Idx is an index in the 128 bits
4347 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4348 /// lowering INSERT_VECTOR_ELT operations easier.
4349 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4350                                   SelectionDAG &DAG, SDLoc dl) {
4351   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4352
4353   // For insertion into the zero index (low half) of a 256-bit vector, it is
4354   // more efficient to generate a blend with immediate instead of an insert*128.
4355   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4356   // extend the subvector to the size of the result vector. Make sure that
4357   // we are not recursing on that node by checking for undef here.
4358   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4359       Result.getOpcode() != ISD::UNDEF) {
4360     EVT ResultVT = Result.getValueType();
4361     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4362     SDValue Undef = DAG.getUNDEF(ResultVT);
4363     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4364                                  Vec, ZeroIndex);
4365
4366     // The blend instruction, and therefore its mask, depend on the data type.
4367     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4368     if (ScalarType.isFloatingPoint()) {
4369       // Choose either vblendps (float) or vblendpd (double).
4370       unsigned ScalarSize = ScalarType.getSizeInBits();
4371       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4372       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4373       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4374       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4375     }
4376
4377     const X86Subtarget &Subtarget =
4378     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4379
4380     // AVX2 is needed for 256-bit integer blend support.
4381     // Integers must be cast to 32-bit because there is only vpblendd;
4382     // vpblendw can't be used for this because it has a handicapped mask.
4383
4384     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4385     // is still more efficient than using the wrong domain vinsertf128 that
4386     // will be created by InsertSubVector().
4387     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4388
4389     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4390     Vec256 = DAG.getBitcast(CastVT, Vec256);
4391     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4392     return DAG.getBitcast(ResultVT, Vec256);
4393   }
4394
4395   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4396 }
4397
4398 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4399                                   SelectionDAG &DAG, SDLoc dl) {
4400   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4401   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4402 }
4403
4404 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4405 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4406 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4407 /// large BUILD_VECTORS.
4408 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4409                                    unsigned NumElems, SelectionDAG &DAG,
4410                                    SDLoc dl) {
4411   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4412   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4413 }
4414
4415 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4416                                    unsigned NumElems, SelectionDAG &DAG,
4417                                    SDLoc dl) {
4418   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4419   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4420 }
4421
4422 /// Returns a vector of specified type with all bits set.
4423 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4424 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4425 /// Then bitcast to their original type, ensuring they get CSE'd.
4426 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4427                              SelectionDAG &DAG, SDLoc dl) {
4428   assert(VT.isVector() && "Expected a vector type");
4429
4430   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4431   SDValue Vec;
4432   if (VT.is512BitVector()) {
4433     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4434                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4435     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4436   } else if (VT.is256BitVector()) {
4437     if (Subtarget->hasInt256()) { // AVX2
4438       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4439       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4440     } else { // AVX
4441       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4442       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4443     }
4444   } else if (VT.is128BitVector()) {
4445     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4446   } else
4447     llvm_unreachable("Unexpected vector type");
4448
4449   return DAG.getBitcast(VT, Vec);
4450 }
4451
4452 /// Returns a vector_shuffle node for an unpackl operation.
4453 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4454                           SDValue V2) {
4455   unsigned NumElems = VT.getVectorNumElements();
4456   SmallVector<int, 8> Mask;
4457   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4458     Mask.push_back(i);
4459     Mask.push_back(i + NumElems);
4460   }
4461   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4462 }
4463
4464 /// Returns a vector_shuffle node for an unpackh operation.
4465 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4466                           SDValue V2) {
4467   unsigned NumElems = VT.getVectorNumElements();
4468   SmallVector<int, 8> Mask;
4469   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4470     Mask.push_back(i + Half);
4471     Mask.push_back(i + NumElems + Half);
4472   }
4473   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4474 }
4475
4476 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4477 /// This produces a shuffle where the low element of V2 is swizzled into the
4478 /// zero/undef vector, landing at element Idx.
4479 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4480 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4481                                            bool IsZero,
4482                                            const X86Subtarget *Subtarget,
4483                                            SelectionDAG &DAG) {
4484   MVT VT = V2.getSimpleValueType();
4485   SDValue V1 = IsZero
4486     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4487   unsigned NumElems = VT.getVectorNumElements();
4488   SmallVector<int, 16> MaskVec;
4489   for (unsigned i = 0; i != NumElems; ++i)
4490     // If this is the insertion idx, put the low elt of V2 here.
4491     MaskVec.push_back(i == Idx ? NumElems : i);
4492   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4493 }
4494
4495 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4496 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4497 /// uses one source. Note that this will set IsUnary for shuffles which use a
4498 /// single input multiple times, and in those cases it will
4499 /// adjust the mask to only have indices within that single input.
4500 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4501 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4502                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4503   unsigned NumElems = VT.getVectorNumElements();
4504   SDValue ImmN;
4505
4506   IsUnary = false;
4507   bool IsFakeUnary = false;
4508   switch(N->getOpcode()) {
4509   case X86ISD::BLENDI:
4510     ImmN = N->getOperand(N->getNumOperands()-1);
4511     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4512     break;
4513   case X86ISD::SHUFP:
4514     ImmN = N->getOperand(N->getNumOperands()-1);
4515     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4516     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4517     break;
4518   case X86ISD::UNPCKH:
4519     DecodeUNPCKHMask(VT, Mask);
4520     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4521     break;
4522   case X86ISD::UNPCKL:
4523     DecodeUNPCKLMask(VT, Mask);
4524     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4525     break;
4526   case X86ISD::MOVHLPS:
4527     DecodeMOVHLPSMask(NumElems, Mask);
4528     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4529     break;
4530   case X86ISD::MOVLHPS:
4531     DecodeMOVLHPSMask(NumElems, Mask);
4532     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4533     break;
4534   case X86ISD::PALIGNR:
4535     ImmN = N->getOperand(N->getNumOperands()-1);
4536     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4537     break;
4538   case X86ISD::PSHUFD:
4539   case X86ISD::VPERMILPI:
4540     ImmN = N->getOperand(N->getNumOperands()-1);
4541     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4542     IsUnary = true;
4543     break;
4544   case X86ISD::PSHUFHW:
4545     ImmN = N->getOperand(N->getNumOperands()-1);
4546     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4547     IsUnary = true;
4548     break;
4549   case X86ISD::PSHUFLW:
4550     ImmN = N->getOperand(N->getNumOperands()-1);
4551     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4552     IsUnary = true;
4553     break;
4554   case X86ISD::PSHUFB: {
4555     IsUnary = true;
4556     SDValue MaskNode = N->getOperand(1);
4557     while (MaskNode->getOpcode() == ISD::BITCAST)
4558       MaskNode = MaskNode->getOperand(0);
4559
4560     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4561       // If we have a build-vector, then things are easy.
4562       EVT VT = MaskNode.getValueType();
4563       assert(VT.isVector() &&
4564              "Can't produce a non-vector with a build_vector!");
4565       if (!VT.isInteger())
4566         return false;
4567
4568       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4569
4570       SmallVector<uint64_t, 32> RawMask;
4571       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4572         SDValue Op = MaskNode->getOperand(i);
4573         if (Op->getOpcode() == ISD::UNDEF) {
4574           RawMask.push_back((uint64_t)SM_SentinelUndef);
4575           continue;
4576         }
4577         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4578         if (!CN)
4579           return false;
4580         APInt MaskElement = CN->getAPIntValue();
4581
4582         // We now have to decode the element which could be any integer size and
4583         // extract each byte of it.
4584         for (int j = 0; j < NumBytesPerElement; ++j) {
4585           // Note that this is x86 and so always little endian: the low byte is
4586           // the first byte of the mask.
4587           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4588           MaskElement = MaskElement.lshr(8);
4589         }
4590       }
4591       DecodePSHUFBMask(RawMask, Mask);
4592       break;
4593     }
4594
4595     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4596     if (!MaskLoad)
4597       return false;
4598
4599     SDValue Ptr = MaskLoad->getBasePtr();
4600     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4601         Ptr->getOpcode() == X86ISD::WrapperRIP)
4602       Ptr = Ptr->getOperand(0);
4603
4604     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4605     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4606       return false;
4607
4608     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4609       DecodePSHUFBMask(C, Mask);
4610       if (Mask.empty())
4611         return false;
4612       break;
4613     }
4614
4615     return false;
4616   }
4617   case X86ISD::VPERMI:
4618     ImmN = N->getOperand(N->getNumOperands()-1);
4619     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4620     IsUnary = true;
4621     break;
4622   case X86ISD::MOVSS:
4623   case X86ISD::MOVSD:
4624     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4625     break;
4626   case X86ISD::VPERM2X128:
4627     ImmN = N->getOperand(N->getNumOperands()-1);
4628     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4629     if (Mask.empty()) return false;
4630     // Mask only contains negative index if an element is zero.
4631     if (std::any_of(Mask.begin(), Mask.end(),
4632                     [](int M){ return M == SM_SentinelZero; }))
4633       return false;
4634     break;
4635   case X86ISD::MOVSLDUP:
4636     DecodeMOVSLDUPMask(VT, Mask);
4637     IsUnary = true;
4638     break;
4639   case X86ISD::MOVSHDUP:
4640     DecodeMOVSHDUPMask(VT, Mask);
4641     IsUnary = true;
4642     break;
4643   case X86ISD::MOVDDUP:
4644     DecodeMOVDDUPMask(VT, Mask);
4645     IsUnary = true;
4646     break;
4647   case X86ISD::MOVLHPD:
4648   case X86ISD::MOVLPD:
4649   case X86ISD::MOVLPS:
4650     // Not yet implemented
4651     return false;
4652   case X86ISD::VPERMV: {
4653     IsUnary = true;
4654     SDValue MaskNode = N->getOperand(0);
4655     while (MaskNode->getOpcode() == ISD::BITCAST)
4656       MaskNode = MaskNode->getOperand(0);
4657
4658     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4659     SmallVector<uint64_t, 32> RawMask;
4660     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4661       // If we have a build-vector, then things are easy.
4662       assert(MaskNode.getValueType().isInteger() &&
4663              MaskNode.getValueType().getVectorNumElements() ==
4664              VT.getVectorNumElements());
4665
4666       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4667         SDValue Op = MaskNode->getOperand(i);
4668         if (Op->getOpcode() == ISD::UNDEF)
4669           RawMask.push_back((uint64_t)SM_SentinelUndef);
4670         else if (isa<ConstantSDNode>(Op)) {
4671           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4672           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4673         } else
4674           return false;
4675       }
4676       DecodeVPERMVMask(RawMask, Mask);
4677       break;
4678     }
4679     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4680       unsigned NumEltsInMask = MaskNode->getNumOperands();
4681       MaskNode = MaskNode->getOperand(0);
4682       auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4683       if (CN) {
4684         APInt MaskEltValue = CN->getAPIntValue();
4685         for (unsigned i = 0; i < NumEltsInMask; ++i)
4686           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4687         DecodeVPERMVMask(RawMask, Mask);
4688         break;
4689       }
4690       // It may be a scalar load
4691     }
4692
4693     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4694     if (!MaskLoad)
4695       return false;
4696
4697     SDValue Ptr = MaskLoad->getBasePtr();
4698     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4699         Ptr->getOpcode() == X86ISD::WrapperRIP)
4700       Ptr = Ptr->getOperand(0);
4701
4702     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4703     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4704       return false;
4705
4706     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4707     if (C) {
4708       DecodeVPERMVMask(C, VT, Mask);
4709       if (Mask.empty())
4710         return false;
4711       break;
4712     }
4713     return false;
4714   }
4715   case X86ISD::VPERMV3: {
4716     IsUnary = false;
4717     SDValue MaskNode = N->getOperand(1);
4718     while (MaskNode->getOpcode() == ISD::BITCAST)
4719       MaskNode = MaskNode->getOperand(1);
4720
4721     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4722       // If we have a build-vector, then things are easy.
4723       assert(MaskNode.getValueType().isInteger() &&
4724              MaskNode.getValueType().getVectorNumElements() ==
4725              VT.getVectorNumElements());
4726
4727       SmallVector<uint64_t, 32> RawMask;
4728       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4729
4730       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4731         SDValue Op = MaskNode->getOperand(i);
4732         if (Op->getOpcode() == ISD::UNDEF)
4733           RawMask.push_back((uint64_t)SM_SentinelUndef);
4734         else {
4735           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4736           if (!CN)
4737             return false;
4738           APInt MaskElement = CN->getAPIntValue();
4739           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4740         }
4741       }
4742       DecodeVPERMV3Mask(RawMask, Mask);
4743       break;
4744     }
4745
4746     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4747     if (!MaskLoad)
4748       return false;
4749
4750     SDValue Ptr = MaskLoad->getBasePtr();
4751     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4752         Ptr->getOpcode() == X86ISD::WrapperRIP)
4753       Ptr = Ptr->getOperand(0);
4754
4755     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4756     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4757       return false;
4758
4759     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4760     if (C) {
4761       DecodeVPERMV3Mask(C, VT, Mask);
4762       if (Mask.empty())
4763         return false;
4764       break;
4765     }
4766     return false;
4767   }
4768   default: llvm_unreachable("unknown target shuffle node");
4769   }
4770
4771   // If we have a fake unary shuffle, the shuffle mask is spread across two
4772   // inputs that are actually the same node. Re-map the mask to always point
4773   // into the first input.
4774   if (IsFakeUnary)
4775     for (int &M : Mask)
4776       if (M >= (int)Mask.size())
4777         M -= Mask.size();
4778
4779   return true;
4780 }
4781
4782 /// Returns the scalar element that will make up the ith
4783 /// element of the result of the vector shuffle.
4784 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4785                                    unsigned Depth) {
4786   if (Depth == 6)
4787     return SDValue();  // Limit search depth.
4788
4789   SDValue V = SDValue(N, 0);
4790   EVT VT = V.getValueType();
4791   unsigned Opcode = V.getOpcode();
4792
4793   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4794   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4795     int Elt = SV->getMaskElt(Index);
4796
4797     if (Elt < 0)
4798       return DAG.getUNDEF(VT.getVectorElementType());
4799
4800     unsigned NumElems = VT.getVectorNumElements();
4801     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4802                                          : SV->getOperand(1);
4803     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4804   }
4805
4806   // Recurse into target specific vector shuffles to find scalars.
4807   if (isTargetShuffle(Opcode)) {
4808     MVT ShufVT = V.getSimpleValueType();
4809     unsigned NumElems = ShufVT.getVectorNumElements();
4810     SmallVector<int, 16> ShuffleMask;
4811     bool IsUnary;
4812
4813     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4814       return SDValue();
4815
4816     int Elt = ShuffleMask[Index];
4817     if (Elt < 0)
4818       return DAG.getUNDEF(ShufVT.getVectorElementType());
4819
4820     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4821                                          : N->getOperand(1);
4822     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4823                                Depth+1);
4824   }
4825
4826   // Actual nodes that may contain scalar elements
4827   if (Opcode == ISD::BITCAST) {
4828     V = V.getOperand(0);
4829     EVT SrcVT = V.getValueType();
4830     unsigned NumElems = VT.getVectorNumElements();
4831
4832     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4833       return SDValue();
4834   }
4835
4836   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4837     return (Index == 0) ? V.getOperand(0)
4838                         : DAG.getUNDEF(VT.getVectorElementType());
4839
4840   if (V.getOpcode() == ISD::BUILD_VECTOR)
4841     return V.getOperand(Index);
4842
4843   return SDValue();
4844 }
4845
4846 /// Custom lower build_vector of v16i8.
4847 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4848                                        unsigned NumNonZero, unsigned NumZero,
4849                                        SelectionDAG &DAG,
4850                                        const X86Subtarget* Subtarget,
4851                                        const TargetLowering &TLI) {
4852   if (NumNonZero > 8)
4853     return SDValue();
4854
4855   SDLoc dl(Op);
4856   SDValue V;
4857   bool First = true;
4858
4859   // SSE4.1 - use PINSRB to insert each byte directly.
4860   if (Subtarget->hasSSE41()) {
4861     for (unsigned i = 0; i < 16; ++i) {
4862       bool isNonZero = (NonZeros & (1 << i)) != 0;
4863       if (isNonZero) {
4864         if (First) {
4865           if (NumZero)
4866             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4867           else
4868             V = DAG.getUNDEF(MVT::v16i8);
4869           First = false;
4870         }
4871         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4872                         MVT::v16i8, V, Op.getOperand(i),
4873                         DAG.getIntPtrConstant(i, dl));
4874       }
4875     }
4876
4877     return V;
4878   }
4879
4880   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4881   for (unsigned i = 0; i < 16; ++i) {
4882     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4883     if (ThisIsNonZero && First) {
4884       if (NumZero)
4885         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4886       else
4887         V = DAG.getUNDEF(MVT::v8i16);
4888       First = false;
4889     }
4890
4891     if ((i & 1) != 0) {
4892       SDValue ThisElt, LastElt;
4893       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4894       if (LastIsNonZero) {
4895         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4896                               MVT::i16, Op.getOperand(i-1));
4897       }
4898       if (ThisIsNonZero) {
4899         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4900         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4901                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4902         if (LastIsNonZero)
4903           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4904       } else
4905         ThisElt = LastElt;
4906
4907       if (ThisElt.getNode())
4908         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4909                         DAG.getIntPtrConstant(i/2, dl));
4910     }
4911   }
4912
4913   return DAG.getBitcast(MVT::v16i8, V);
4914 }
4915
4916 /// Custom lower build_vector of v8i16.
4917 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4918                                      unsigned NumNonZero, unsigned NumZero,
4919                                      SelectionDAG &DAG,
4920                                      const X86Subtarget* Subtarget,
4921                                      const TargetLowering &TLI) {
4922   if (NumNonZero > 4)
4923     return SDValue();
4924
4925   SDLoc dl(Op);
4926   SDValue V;
4927   bool First = true;
4928   for (unsigned i = 0; i < 8; ++i) {
4929     bool isNonZero = (NonZeros & (1 << i)) != 0;
4930     if (isNonZero) {
4931       if (First) {
4932         if (NumZero)
4933           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4934         else
4935           V = DAG.getUNDEF(MVT::v8i16);
4936         First = false;
4937       }
4938       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4939                       MVT::v8i16, V, Op.getOperand(i),
4940                       DAG.getIntPtrConstant(i, dl));
4941     }
4942   }
4943
4944   return V;
4945 }
4946
4947 /// Custom lower build_vector of v4i32 or v4f32.
4948 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4949                                      const X86Subtarget *Subtarget,
4950                                      const TargetLowering &TLI) {
4951   // Find all zeroable elements.
4952   std::bitset<4> Zeroable;
4953   for (int i=0; i < 4; ++i) {
4954     SDValue Elt = Op->getOperand(i);
4955     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4956   }
4957   assert(Zeroable.size() - Zeroable.count() > 1 &&
4958          "We expect at least two non-zero elements!");
4959
4960   // We only know how to deal with build_vector nodes where elements are either
4961   // zeroable or extract_vector_elt with constant index.
4962   SDValue FirstNonZero;
4963   unsigned FirstNonZeroIdx;
4964   for (unsigned i=0; i < 4; ++i) {
4965     if (Zeroable[i])
4966       continue;
4967     SDValue Elt = Op->getOperand(i);
4968     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4969         !isa<ConstantSDNode>(Elt.getOperand(1)))
4970       return SDValue();
4971     // Make sure that this node is extracting from a 128-bit vector.
4972     MVT VT = Elt.getOperand(0).getSimpleValueType();
4973     if (!VT.is128BitVector())
4974       return SDValue();
4975     if (!FirstNonZero.getNode()) {
4976       FirstNonZero = Elt;
4977       FirstNonZeroIdx = i;
4978     }
4979   }
4980
4981   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4982   SDValue V1 = FirstNonZero.getOperand(0);
4983   MVT VT = V1.getSimpleValueType();
4984
4985   // See if this build_vector can be lowered as a blend with zero.
4986   SDValue Elt;
4987   unsigned EltMaskIdx, EltIdx;
4988   int Mask[4];
4989   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4990     if (Zeroable[EltIdx]) {
4991       // The zero vector will be on the right hand side.
4992       Mask[EltIdx] = EltIdx+4;
4993       continue;
4994     }
4995
4996     Elt = Op->getOperand(EltIdx);
4997     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4998     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4999     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5000       break;
5001     Mask[EltIdx] = EltIdx;
5002   }
5003
5004   if (EltIdx == 4) {
5005     // Let the shuffle legalizer deal with blend operations.
5006     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5007     if (V1.getSimpleValueType() != VT)
5008       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5009     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5010   }
5011
5012   // See if we can lower this build_vector to a INSERTPS.
5013   if (!Subtarget->hasSSE41())
5014     return SDValue();
5015
5016   SDValue V2 = Elt.getOperand(0);
5017   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5018     V1 = SDValue();
5019
5020   bool CanFold = true;
5021   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5022     if (Zeroable[i])
5023       continue;
5024
5025     SDValue Current = Op->getOperand(i);
5026     SDValue SrcVector = Current->getOperand(0);
5027     if (!V1.getNode())
5028       V1 = SrcVector;
5029     CanFold = SrcVector == V1 &&
5030       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5031   }
5032
5033   if (!CanFold)
5034     return SDValue();
5035
5036   assert(V1.getNode() && "Expected at least two non-zero elements!");
5037   if (V1.getSimpleValueType() != MVT::v4f32)
5038     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5039   if (V2.getSimpleValueType() != MVT::v4f32)
5040     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5041
5042   // Ok, we can emit an INSERTPS instruction.
5043   unsigned ZMask = Zeroable.to_ulong();
5044
5045   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5046   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5047   SDLoc DL(Op);
5048   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5049                                DAG.getIntPtrConstant(InsertPSMask, DL));
5050   return DAG.getBitcast(VT, Result);
5051 }
5052
5053 /// Return a vector logical shift node.
5054 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5055                          unsigned NumBits, SelectionDAG &DAG,
5056                          const TargetLowering &TLI, SDLoc dl) {
5057   assert(VT.is128BitVector() && "Unknown type for VShift");
5058   MVT ShVT = MVT::v2i64;
5059   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5060   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5061   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5062   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5063   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5064   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5065 }
5066
5067 static SDValue
5068 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5069
5070   // Check if the scalar load can be widened into a vector load. And if
5071   // the address is "base + cst" see if the cst can be "absorbed" into
5072   // the shuffle mask.
5073   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5074     SDValue Ptr = LD->getBasePtr();
5075     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5076       return SDValue();
5077     EVT PVT = LD->getValueType(0);
5078     if (PVT != MVT::i32 && PVT != MVT::f32)
5079       return SDValue();
5080
5081     int FI = -1;
5082     int64_t Offset = 0;
5083     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5084       FI = FINode->getIndex();
5085       Offset = 0;
5086     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5087                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5088       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5089       Offset = Ptr.getConstantOperandVal(1);
5090       Ptr = Ptr.getOperand(0);
5091     } else {
5092       return SDValue();
5093     }
5094
5095     // FIXME: 256-bit vector instructions don't require a strict alignment,
5096     // improve this code to support it better.
5097     unsigned RequiredAlign = VT.getSizeInBits()/8;
5098     SDValue Chain = LD->getChain();
5099     // Make sure the stack object alignment is at least 16 or 32.
5100     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5101     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5102       if (MFI->isFixedObjectIndex(FI)) {
5103         // Can't change the alignment. FIXME: It's possible to compute
5104         // the exact stack offset and reference FI + adjust offset instead.
5105         // If someone *really* cares about this. That's the way to implement it.
5106         return SDValue();
5107       } else {
5108         MFI->setObjectAlignment(FI, RequiredAlign);
5109       }
5110     }
5111
5112     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5113     // Ptr + (Offset & ~15).
5114     if (Offset < 0)
5115       return SDValue();
5116     if ((Offset % RequiredAlign) & 3)
5117       return SDValue();
5118     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5119     if (StartOffset) {
5120       SDLoc DL(Ptr);
5121       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5122                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5123     }
5124
5125     int EltNo = (Offset - StartOffset) >> 2;
5126     unsigned NumElems = VT.getVectorNumElements();
5127
5128     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5129     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5130                              LD->getPointerInfo().getWithOffset(StartOffset),
5131                              false, false, false, 0);
5132
5133     SmallVector<int, 8> Mask(NumElems, EltNo);
5134
5135     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5136   }
5137
5138   return SDValue();
5139 }
5140
5141 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5142 /// elements can be replaced by a single large load which has the same value as
5143 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5144 ///
5145 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5146 ///
5147 /// FIXME: we'd also like to handle the case where the last elements are zero
5148 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5149 /// There's even a handy isZeroNode for that purpose.
5150 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5151                                         SDLoc &DL, SelectionDAG &DAG,
5152                                         bool isAfterLegalize) {
5153   unsigned NumElems = Elts.size();
5154
5155   LoadSDNode *LDBase = nullptr;
5156   unsigned LastLoadedElt = -1U;
5157
5158   // For each element in the initializer, see if we've found a load or an undef.
5159   // If we don't find an initial load element, or later load elements are
5160   // non-consecutive, bail out.
5161   for (unsigned i = 0; i < NumElems; ++i) {
5162     SDValue Elt = Elts[i];
5163     // Look through a bitcast.
5164     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5165       Elt = Elt.getOperand(0);
5166     if (!Elt.getNode() ||
5167         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5168       return SDValue();
5169     if (!LDBase) {
5170       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5171         return SDValue();
5172       LDBase = cast<LoadSDNode>(Elt.getNode());
5173       LastLoadedElt = i;
5174       continue;
5175     }
5176     if (Elt.getOpcode() == ISD::UNDEF)
5177       continue;
5178
5179     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5180     EVT LdVT = Elt.getValueType();
5181     // Each loaded element must be the correct fractional portion of the
5182     // requested vector load.
5183     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5184       return SDValue();
5185     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5186       return SDValue();
5187     LastLoadedElt = i;
5188   }
5189
5190   // If we have found an entire vector of loads and undefs, then return a large
5191   // load of the entire vector width starting at the base pointer.  If we found
5192   // consecutive loads for the low half, generate a vzext_load node.
5193   if (LastLoadedElt == NumElems - 1) {
5194     assert(LDBase && "Did not find base load for merging consecutive loads");
5195     EVT EltVT = LDBase->getValueType(0);
5196     // Ensure that the input vector size for the merged loads matches the
5197     // cumulative size of the input elements.
5198     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5199       return SDValue();
5200
5201     if (isAfterLegalize &&
5202         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5203       return SDValue();
5204
5205     SDValue NewLd = SDValue();
5206
5207     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5208                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5209                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5210                         LDBase->getAlignment());
5211
5212     if (LDBase->hasAnyUseOfValue(1)) {
5213       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5214                                      SDValue(LDBase, 1),
5215                                      SDValue(NewLd.getNode(), 1));
5216       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5217       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5218                              SDValue(NewLd.getNode(), 1));
5219     }
5220
5221     return NewLd;
5222   }
5223
5224   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5225   //of a v4i32 / v4f32. It's probably worth generalizing.
5226   EVT EltVT = VT.getVectorElementType();
5227   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5228       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5229     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5230     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5231     SDValue ResNode =
5232         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5233                                 LDBase->getPointerInfo(),
5234                                 LDBase->getAlignment(),
5235                                 false/*isVolatile*/, true/*ReadMem*/,
5236                                 false/*WriteMem*/);
5237
5238     // Make sure the newly-created LOAD is in the same position as LDBase in
5239     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5240     // update uses of LDBase's output chain to use the TokenFactor.
5241     if (LDBase->hasAnyUseOfValue(1)) {
5242       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5243                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5244       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5245       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5246                              SDValue(ResNode.getNode(), 1));
5247     }
5248
5249     return DAG.getBitcast(VT, ResNode);
5250   }
5251   return SDValue();
5252 }
5253
5254 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5255 /// to generate a splat value for the following cases:
5256 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5257 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5258 /// a scalar load, or a constant.
5259 /// The VBROADCAST node is returned when a pattern is found,
5260 /// or SDValue() otherwise.
5261 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5262                                     SelectionDAG &DAG) {
5263   // VBROADCAST requires AVX.
5264   // TODO: Splats could be generated for non-AVX CPUs using SSE
5265   // instructions, but there's less potential gain for only 128-bit vectors.
5266   if (!Subtarget->hasAVX())
5267     return SDValue();
5268
5269   MVT VT = Op.getSimpleValueType();
5270   SDLoc dl(Op);
5271
5272   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5273          "Unsupported vector type for broadcast.");
5274
5275   SDValue Ld;
5276   bool ConstSplatVal;
5277
5278   switch (Op.getOpcode()) {
5279     default:
5280       // Unknown pattern found.
5281       return SDValue();
5282
5283     case ISD::BUILD_VECTOR: {
5284       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5285       BitVector UndefElements;
5286       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5287
5288       // We need a splat of a single value to use broadcast, and it doesn't
5289       // make any sense if the value is only in one element of the vector.
5290       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5291         return SDValue();
5292
5293       Ld = Splat;
5294       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5295                        Ld.getOpcode() == ISD::ConstantFP);
5296
5297       // Make sure that all of the users of a non-constant load are from the
5298       // BUILD_VECTOR node.
5299       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5300         return SDValue();
5301       break;
5302     }
5303
5304     case ISD::VECTOR_SHUFFLE: {
5305       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5306
5307       // Shuffles must have a splat mask where the first element is
5308       // broadcasted.
5309       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5310         return SDValue();
5311
5312       SDValue Sc = Op.getOperand(0);
5313       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5314           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5315
5316         if (!Subtarget->hasInt256())
5317           return SDValue();
5318
5319         // Use the register form of the broadcast instruction available on AVX2.
5320         if (VT.getSizeInBits() >= 256)
5321           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5322         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5323       }
5324
5325       Ld = Sc.getOperand(0);
5326       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5327                        Ld.getOpcode() == ISD::ConstantFP);
5328
5329       // The scalar_to_vector node and the suspected
5330       // load node must have exactly one user.
5331       // Constants may have multiple users.
5332
5333       // AVX-512 has register version of the broadcast
5334       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5335         Ld.getValueType().getSizeInBits() >= 32;
5336       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5337           !hasRegVer))
5338         return SDValue();
5339       break;
5340     }
5341   }
5342
5343   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5344   bool IsGE256 = (VT.getSizeInBits() >= 256);
5345
5346   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5347   // instruction to save 8 or more bytes of constant pool data.
5348   // TODO: If multiple splats are generated to load the same constant,
5349   // it may be detrimental to overall size. There needs to be a way to detect
5350   // that condition to know if this is truly a size win.
5351   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5352
5353   // Handle broadcasting a single constant scalar from the constant pool
5354   // into a vector.
5355   // On Sandybridge (no AVX2), it is still better to load a constant vector
5356   // from the constant pool and not to broadcast it from a scalar.
5357   // But override that restriction when optimizing for size.
5358   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5359   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5360     EVT CVT = Ld.getValueType();
5361     assert(!CVT.isVector() && "Must not broadcast a vector type");
5362
5363     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5364     // For size optimization, also splat v2f64 and v2i64, and for size opt
5365     // with AVX2, also splat i8 and i16.
5366     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5367     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5368         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5369       const Constant *C = nullptr;
5370       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5371         C = CI->getConstantIntValue();
5372       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5373         C = CF->getConstantFPValue();
5374
5375       assert(C && "Invalid constant type");
5376
5377       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5378       SDValue CP =
5379           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5380       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5381       Ld = DAG.getLoad(
5382           CVT, dl, DAG.getEntryNode(), CP,
5383           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5384           false, false, Alignment);
5385
5386       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5387     }
5388   }
5389
5390   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5391
5392   // Handle AVX2 in-register broadcasts.
5393   if (!IsLoad && Subtarget->hasInt256() &&
5394       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5395     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5396
5397   // The scalar source must be a normal load.
5398   if (!IsLoad)
5399     return SDValue();
5400
5401   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5402       (Subtarget->hasVLX() && ScalarSize == 64))
5403     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5404
5405   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5406   // double since there is no vbroadcastsd xmm
5407   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5408     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5409       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5410   }
5411
5412   // Unsupported broadcast.
5413   return SDValue();
5414 }
5415
5416 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5417 /// underlying vector and index.
5418 ///
5419 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5420 /// index.
5421 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5422                                          SDValue ExtIdx) {
5423   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5424   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5425     return Idx;
5426
5427   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5428   // lowered this:
5429   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5430   // to:
5431   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5432   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5433   //                           undef)
5434   //                       Constant<0>)
5435   // In this case the vector is the extract_subvector expression and the index
5436   // is 2, as specified by the shuffle.
5437   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5438   SDValue ShuffleVec = SVOp->getOperand(0);
5439   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5440   assert(ShuffleVecVT.getVectorElementType() ==
5441          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5442
5443   int ShuffleIdx = SVOp->getMaskElt(Idx);
5444   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5445     ExtractedFromVec = ShuffleVec;
5446     return ShuffleIdx;
5447   }
5448   return Idx;
5449 }
5450
5451 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5452   MVT VT = Op.getSimpleValueType();
5453
5454   // Skip if insert_vec_elt is not supported.
5455   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5456   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5457     return SDValue();
5458
5459   SDLoc DL(Op);
5460   unsigned NumElems = Op.getNumOperands();
5461
5462   SDValue VecIn1;
5463   SDValue VecIn2;
5464   SmallVector<unsigned, 4> InsertIndices;
5465   SmallVector<int, 8> Mask(NumElems, -1);
5466
5467   for (unsigned i = 0; i != NumElems; ++i) {
5468     unsigned Opc = Op.getOperand(i).getOpcode();
5469
5470     if (Opc == ISD::UNDEF)
5471       continue;
5472
5473     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5474       // Quit if more than 1 elements need inserting.
5475       if (InsertIndices.size() > 1)
5476         return SDValue();
5477
5478       InsertIndices.push_back(i);
5479       continue;
5480     }
5481
5482     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5483     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5484     // Quit if non-constant index.
5485     if (!isa<ConstantSDNode>(ExtIdx))
5486       return SDValue();
5487     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5488
5489     // Quit if extracted from vector of different type.
5490     if (ExtractedFromVec.getValueType() != VT)
5491       return SDValue();
5492
5493     if (!VecIn1.getNode())
5494       VecIn1 = ExtractedFromVec;
5495     else if (VecIn1 != ExtractedFromVec) {
5496       if (!VecIn2.getNode())
5497         VecIn2 = ExtractedFromVec;
5498       else if (VecIn2 != ExtractedFromVec)
5499         // Quit if more than 2 vectors to shuffle
5500         return SDValue();
5501     }
5502
5503     if (ExtractedFromVec == VecIn1)
5504       Mask[i] = Idx;
5505     else if (ExtractedFromVec == VecIn2)
5506       Mask[i] = Idx + NumElems;
5507   }
5508
5509   if (!VecIn1.getNode())
5510     return SDValue();
5511
5512   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5513   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5514   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5515     unsigned Idx = InsertIndices[i];
5516     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5517                      DAG.getIntPtrConstant(Idx, DL));
5518   }
5519
5520   return NV;
5521 }
5522
5523 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5524   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5525          Op.getScalarValueSizeInBits() == 1 &&
5526          "Can not convert non-constant vector");
5527   uint64_t Immediate = 0;
5528   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5529     SDValue In = Op.getOperand(idx);
5530     if (In.getOpcode() != ISD::UNDEF)
5531       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5532   }
5533   SDLoc dl(Op);
5534   MVT VT =
5535    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5536   return DAG.getConstant(Immediate, dl, VT);
5537 }
5538 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5539 SDValue
5540 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5541
5542   MVT VT = Op.getSimpleValueType();
5543   assert((VT.getVectorElementType() == MVT::i1) &&
5544          "Unexpected type in LowerBUILD_VECTORvXi1!");
5545
5546   SDLoc dl(Op);
5547   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5548     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5549     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5550     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5551   }
5552
5553   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5554     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5555     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5556     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5557   }
5558
5559   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5560     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5561     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5562       return DAG.getBitcast(VT, Imm);
5563     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5564     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5565                         DAG.getIntPtrConstant(0, dl));
5566   }
5567
5568   // Vector has one or more non-const elements
5569   uint64_t Immediate = 0;
5570   SmallVector<unsigned, 16> NonConstIdx;
5571   bool IsSplat = true;
5572   bool HasConstElts = false;
5573   int SplatIdx = -1;
5574   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5575     SDValue In = Op.getOperand(idx);
5576     if (In.getOpcode() == ISD::UNDEF)
5577       continue;
5578     if (!isa<ConstantSDNode>(In))
5579       NonConstIdx.push_back(idx);
5580     else {
5581       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5582       HasConstElts = true;
5583     }
5584     if (SplatIdx == -1)
5585       SplatIdx = idx;
5586     else if (In != Op.getOperand(SplatIdx))
5587       IsSplat = false;
5588   }
5589
5590   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5591   if (IsSplat)
5592     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5593                        DAG.getConstant(1, dl, VT),
5594                        DAG.getConstant(0, dl, VT));
5595
5596   // insert elements one by one
5597   SDValue DstVec;
5598   SDValue Imm;
5599   if (Immediate) {
5600     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5601     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5602   }
5603   else if (HasConstElts)
5604     Imm = DAG.getConstant(0, dl, VT);
5605   else
5606     Imm = DAG.getUNDEF(VT);
5607   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5608     DstVec = DAG.getBitcast(VT, Imm);
5609   else {
5610     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5611     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5612                          DAG.getIntPtrConstant(0, dl));
5613   }
5614
5615   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5616     unsigned InsertIdx = NonConstIdx[i];
5617     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5618                          Op.getOperand(InsertIdx),
5619                          DAG.getIntPtrConstant(InsertIdx, dl));
5620   }
5621   return DstVec;
5622 }
5623
5624 /// \brief Return true if \p N implements a horizontal binop and return the
5625 /// operands for the horizontal binop into V0 and V1.
5626 ///
5627 /// This is a helper function of LowerToHorizontalOp().
5628 /// This function checks that the build_vector \p N in input implements a
5629 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5630 /// operation to match.
5631 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5632 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5633 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5634 /// arithmetic sub.
5635 ///
5636 /// This function only analyzes elements of \p N whose indices are
5637 /// in range [BaseIdx, LastIdx).
5638 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5639                               SelectionDAG &DAG,
5640                               unsigned BaseIdx, unsigned LastIdx,
5641                               SDValue &V0, SDValue &V1) {
5642   EVT VT = N->getValueType(0);
5643
5644   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5645   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5646          "Invalid Vector in input!");
5647
5648   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5649   bool CanFold = true;
5650   unsigned ExpectedVExtractIdx = BaseIdx;
5651   unsigned NumElts = LastIdx - BaseIdx;
5652   V0 = DAG.getUNDEF(VT);
5653   V1 = DAG.getUNDEF(VT);
5654
5655   // Check if N implements a horizontal binop.
5656   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5657     SDValue Op = N->getOperand(i + BaseIdx);
5658
5659     // Skip UNDEFs.
5660     if (Op->getOpcode() == ISD::UNDEF) {
5661       // Update the expected vector extract index.
5662       if (i * 2 == NumElts)
5663         ExpectedVExtractIdx = BaseIdx;
5664       ExpectedVExtractIdx += 2;
5665       continue;
5666     }
5667
5668     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5669
5670     if (!CanFold)
5671       break;
5672
5673     SDValue Op0 = Op.getOperand(0);
5674     SDValue Op1 = Op.getOperand(1);
5675
5676     // Try to match the following pattern:
5677     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5678     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5679         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5680         Op0.getOperand(0) == Op1.getOperand(0) &&
5681         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5682         isa<ConstantSDNode>(Op1.getOperand(1)));
5683     if (!CanFold)
5684       break;
5685
5686     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5687     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5688
5689     if (i * 2 < NumElts) {
5690       if (V0.getOpcode() == ISD::UNDEF) {
5691         V0 = Op0.getOperand(0);
5692         if (V0.getValueType() != VT)
5693           return false;
5694       }
5695     } else {
5696       if (V1.getOpcode() == ISD::UNDEF) {
5697         V1 = Op0.getOperand(0);
5698         if (V1.getValueType() != VT)
5699           return false;
5700       }
5701       if (i * 2 == NumElts)
5702         ExpectedVExtractIdx = BaseIdx;
5703     }
5704
5705     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5706     if (I0 == ExpectedVExtractIdx)
5707       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5708     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5709       // Try to match the following dag sequence:
5710       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5711       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5712     } else
5713       CanFold = false;
5714
5715     ExpectedVExtractIdx += 2;
5716   }
5717
5718   return CanFold;
5719 }
5720
5721 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5722 /// a concat_vector.
5723 ///
5724 /// This is a helper function of LowerToHorizontalOp().
5725 /// This function expects two 256-bit vectors called V0 and V1.
5726 /// At first, each vector is split into two separate 128-bit vectors.
5727 /// Then, the resulting 128-bit vectors are used to implement two
5728 /// horizontal binary operations.
5729 ///
5730 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5731 ///
5732 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5733 /// the two new horizontal binop.
5734 /// When Mode is set, the first horizontal binop dag node would take as input
5735 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5736 /// horizontal binop dag node would take as input the lower 128-bit of V1
5737 /// and the upper 128-bit of V1.
5738 ///   Example:
5739 ///     HADD V0_LO, V0_HI
5740 ///     HADD V1_LO, V1_HI
5741 ///
5742 /// Otherwise, the first horizontal binop dag node takes as input the lower
5743 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5744 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5745 ///   Example:
5746 ///     HADD V0_LO, V1_LO
5747 ///     HADD V0_HI, V1_HI
5748 ///
5749 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5750 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5751 /// the upper 128-bits of the result.
5752 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5753                                      SDLoc DL, SelectionDAG &DAG,
5754                                      unsigned X86Opcode, bool Mode,
5755                                      bool isUndefLO, bool isUndefHI) {
5756   EVT VT = V0.getValueType();
5757   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5758          "Invalid nodes in input!");
5759
5760   unsigned NumElts = VT.getVectorNumElements();
5761   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5762   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5763   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5764   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5765   EVT NewVT = V0_LO.getValueType();
5766
5767   SDValue LO = DAG.getUNDEF(NewVT);
5768   SDValue HI = DAG.getUNDEF(NewVT);
5769
5770   if (Mode) {
5771     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5772     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5773       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5774     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5775       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5776   } else {
5777     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5778     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5779                        V1_LO->getOpcode() != ISD::UNDEF))
5780       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5781
5782     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5783                        V1_HI->getOpcode() != ISD::UNDEF))
5784       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5785   }
5786
5787   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5788 }
5789
5790 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5791 /// node.
5792 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5793                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5794   EVT VT = BV->getValueType(0);
5795   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5796       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5797     return SDValue();
5798
5799   SDLoc DL(BV);
5800   unsigned NumElts = VT.getVectorNumElements();
5801   SDValue InVec0 = DAG.getUNDEF(VT);
5802   SDValue InVec1 = DAG.getUNDEF(VT);
5803
5804   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5805           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5806
5807   // Odd-numbered elements in the input build vector are obtained from
5808   // adding two integer/float elements.
5809   // Even-numbered elements in the input build vector are obtained from
5810   // subtracting two integer/float elements.
5811   unsigned ExpectedOpcode = ISD::FSUB;
5812   unsigned NextExpectedOpcode = ISD::FADD;
5813   bool AddFound = false;
5814   bool SubFound = false;
5815
5816   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5817     SDValue Op = BV->getOperand(i);
5818
5819     // Skip 'undef' values.
5820     unsigned Opcode = Op.getOpcode();
5821     if (Opcode == ISD::UNDEF) {
5822       std::swap(ExpectedOpcode, NextExpectedOpcode);
5823       continue;
5824     }
5825
5826     // Early exit if we found an unexpected opcode.
5827     if (Opcode != ExpectedOpcode)
5828       return SDValue();
5829
5830     SDValue Op0 = Op.getOperand(0);
5831     SDValue Op1 = Op.getOperand(1);
5832
5833     // Try to match the following pattern:
5834     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5835     // Early exit if we cannot match that sequence.
5836     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5837         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5838         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5839         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5840         Op0.getOperand(1) != Op1.getOperand(1))
5841       return SDValue();
5842
5843     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5844     if (I0 != i)
5845       return SDValue();
5846
5847     // We found a valid add/sub node. Update the information accordingly.
5848     if (i & 1)
5849       AddFound = true;
5850     else
5851       SubFound = true;
5852
5853     // Update InVec0 and InVec1.
5854     if (InVec0.getOpcode() == ISD::UNDEF) {
5855       InVec0 = Op0.getOperand(0);
5856       if (InVec0.getValueType() != VT)
5857         return SDValue();
5858     }
5859     if (InVec1.getOpcode() == ISD::UNDEF) {
5860       InVec1 = Op1.getOperand(0);
5861       if (InVec1.getValueType() != VT)
5862         return SDValue();
5863     }
5864
5865     // Make sure that operands in input to each add/sub node always
5866     // come from a same pair of vectors.
5867     if (InVec0 != Op0.getOperand(0)) {
5868       if (ExpectedOpcode == ISD::FSUB)
5869         return SDValue();
5870
5871       // FADD is commutable. Try to commute the operands
5872       // and then test again.
5873       std::swap(Op0, Op1);
5874       if (InVec0 != Op0.getOperand(0))
5875         return SDValue();
5876     }
5877
5878     if (InVec1 != Op1.getOperand(0))
5879       return SDValue();
5880
5881     // Update the pair of expected opcodes.
5882     std::swap(ExpectedOpcode, NextExpectedOpcode);
5883   }
5884
5885   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5886   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5887       InVec1.getOpcode() != ISD::UNDEF)
5888     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5889
5890   return SDValue();
5891 }
5892
5893 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5894 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5895                                    const X86Subtarget *Subtarget,
5896                                    SelectionDAG &DAG) {
5897   EVT VT = BV->getValueType(0);
5898   unsigned NumElts = VT.getVectorNumElements();
5899   unsigned NumUndefsLO = 0;
5900   unsigned NumUndefsHI = 0;
5901   unsigned Half = NumElts/2;
5902
5903   // Count the number of UNDEF operands in the build_vector in input.
5904   for (unsigned i = 0, e = Half; i != e; ++i)
5905     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5906       NumUndefsLO++;
5907
5908   for (unsigned i = Half, e = NumElts; i != e; ++i)
5909     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5910       NumUndefsHI++;
5911
5912   // Early exit if this is either a build_vector of all UNDEFs or all the
5913   // operands but one are UNDEF.
5914   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5915     return SDValue();
5916
5917   SDLoc DL(BV);
5918   SDValue InVec0, InVec1;
5919   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5920     // Try to match an SSE3 float HADD/HSUB.
5921     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5922       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5923
5924     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5925       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5926   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5927     // Try to match an SSSE3 integer HADD/HSUB.
5928     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5929       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5930
5931     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5932       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5933   }
5934
5935   if (!Subtarget->hasAVX())
5936     return SDValue();
5937
5938   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5939     // Try to match an AVX horizontal add/sub of packed single/double
5940     // precision floating point values from 256-bit vectors.
5941     SDValue InVec2, InVec3;
5942     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5943         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5944         ((InVec0.getOpcode() == ISD::UNDEF ||
5945           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5946         ((InVec1.getOpcode() == ISD::UNDEF ||
5947           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5948       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5949
5950     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5951         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5952         ((InVec0.getOpcode() == ISD::UNDEF ||
5953           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5954         ((InVec1.getOpcode() == ISD::UNDEF ||
5955           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5956       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5957   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5958     // Try to match an AVX2 horizontal add/sub of signed integers.
5959     SDValue InVec2, InVec3;
5960     unsigned X86Opcode;
5961     bool CanFold = true;
5962
5963     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5964         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5965         ((InVec0.getOpcode() == ISD::UNDEF ||
5966           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5967         ((InVec1.getOpcode() == ISD::UNDEF ||
5968           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5969       X86Opcode = X86ISD::HADD;
5970     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5971         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5972         ((InVec0.getOpcode() == ISD::UNDEF ||
5973           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5974         ((InVec1.getOpcode() == ISD::UNDEF ||
5975           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5976       X86Opcode = X86ISD::HSUB;
5977     else
5978       CanFold = false;
5979
5980     if (CanFold) {
5981       // Fold this build_vector into a single horizontal add/sub.
5982       // Do this only if the target has AVX2.
5983       if (Subtarget->hasAVX2())
5984         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5985
5986       // Do not try to expand this build_vector into a pair of horizontal
5987       // add/sub if we can emit a pair of scalar add/sub.
5988       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5989         return SDValue();
5990
5991       // Convert this build_vector into a pair of horizontal binop followed by
5992       // a concat vector.
5993       bool isUndefLO = NumUndefsLO == Half;
5994       bool isUndefHI = NumUndefsHI == Half;
5995       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5996                                    isUndefLO, isUndefHI);
5997     }
5998   }
5999
6000   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6001        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6002     unsigned X86Opcode;
6003     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6004       X86Opcode = X86ISD::HADD;
6005     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6006       X86Opcode = X86ISD::HSUB;
6007     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6008       X86Opcode = X86ISD::FHADD;
6009     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6010       X86Opcode = X86ISD::FHSUB;
6011     else
6012       return SDValue();
6013
6014     // Don't try to expand this build_vector into a pair of horizontal add/sub
6015     // if we can simply emit a pair of scalar add/sub.
6016     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6017       return SDValue();
6018
6019     // Convert this build_vector into two horizontal add/sub followed by
6020     // a concat vector.
6021     bool isUndefLO = NumUndefsLO == Half;
6022     bool isUndefHI = NumUndefsHI == Half;
6023     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6024                                  isUndefLO, isUndefHI);
6025   }
6026
6027   return SDValue();
6028 }
6029
6030 SDValue
6031 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6032   SDLoc dl(Op);
6033
6034   MVT VT = Op.getSimpleValueType();
6035   MVT ExtVT = VT.getVectorElementType();
6036   unsigned NumElems = Op.getNumOperands();
6037
6038   // Generate vectors for predicate vectors.
6039   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6040     return LowerBUILD_VECTORvXi1(Op, DAG);
6041
6042   // Vectors containing all zeros can be matched by pxor and xorps later
6043   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6044     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6045     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6046     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6047       return Op;
6048
6049     return getZeroVector(VT, Subtarget, DAG, dl);
6050   }
6051
6052   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6053   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6054   // vpcmpeqd on 256-bit vectors.
6055   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6056     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6057       return Op;
6058
6059     if (!VT.is512BitVector())
6060       return getOnesVector(VT, Subtarget, DAG, dl);
6061   }
6062
6063   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6064   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6065     return AddSub;
6066   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6067     return HorizontalOp;
6068   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6069     return Broadcast;
6070
6071   unsigned EVTBits = ExtVT.getSizeInBits();
6072
6073   unsigned NumZero  = 0;
6074   unsigned NumNonZero = 0;
6075   unsigned NonZeros = 0;
6076   bool IsAllConstants = true;
6077   SmallSet<SDValue, 8> Values;
6078   for (unsigned i = 0; i < NumElems; ++i) {
6079     SDValue Elt = Op.getOperand(i);
6080     if (Elt.getOpcode() == ISD::UNDEF)
6081       continue;
6082     Values.insert(Elt);
6083     if (Elt.getOpcode() != ISD::Constant &&
6084         Elt.getOpcode() != ISD::ConstantFP)
6085       IsAllConstants = false;
6086     if (X86::isZeroNode(Elt))
6087       NumZero++;
6088     else {
6089       NonZeros |= (1 << i);
6090       NumNonZero++;
6091     }
6092   }
6093
6094   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6095   if (NumNonZero == 0)
6096     return DAG.getUNDEF(VT);
6097
6098   // Special case for single non-zero, non-undef, element.
6099   if (NumNonZero == 1) {
6100     unsigned Idx = countTrailingZeros(NonZeros);
6101     SDValue Item = Op.getOperand(Idx);
6102
6103     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6104     // the value are obviously zero, truncate the value to i32 and do the
6105     // insertion that way.  Only do this if the value is non-constant or if the
6106     // value is a constant being inserted into element 0.  It is cheaper to do
6107     // a constant pool load than it is to do a movd + shuffle.
6108     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6109         (!IsAllConstants || Idx == 0)) {
6110       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6111         // Handle SSE only.
6112         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6113         EVT VecVT = MVT::v4i32;
6114
6115         // Truncate the value (which may itself be a constant) to i32, and
6116         // convert it to a vector with movd (S2V+shuffle to zero extend).
6117         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6118         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6119         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6120                                       Item, Idx * 2, true, Subtarget, DAG));
6121       }
6122     }
6123
6124     // If we have a constant or non-constant insertion into the low element of
6125     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6126     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6127     // depending on what the source datatype is.
6128     if (Idx == 0) {
6129       if (NumZero == 0)
6130         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6131
6132       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6133           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6134         if (VT.is512BitVector()) {
6135           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6136           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6137                              Item, DAG.getIntPtrConstant(0, dl));
6138         }
6139         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6140                "Expected an SSE value type!");
6141         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6142         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6143         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6144       }
6145
6146       // We can't directly insert an i8 or i16 into a vector, so zero extend
6147       // it to i32 first.
6148       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6149         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6150         if (VT.is256BitVector()) {
6151           if (Subtarget->hasAVX()) {
6152             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6153             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6154           } else {
6155             // Without AVX, we need to extend to a 128-bit vector and then
6156             // insert into the 256-bit vector.
6157             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6158             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6159             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6160           }
6161         } else {
6162           assert(VT.is128BitVector() && "Expected an SSE value type!");
6163           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6164           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6165         }
6166         return DAG.getBitcast(VT, Item);
6167       }
6168     }
6169
6170     // Is it a vector logical left shift?
6171     if (NumElems == 2 && Idx == 1 &&
6172         X86::isZeroNode(Op.getOperand(0)) &&
6173         !X86::isZeroNode(Op.getOperand(1))) {
6174       unsigned NumBits = VT.getSizeInBits();
6175       return getVShift(true, VT,
6176                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6177                                    VT, Op.getOperand(1)),
6178                        NumBits/2, DAG, *this, dl);
6179     }
6180
6181     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6182       return SDValue();
6183
6184     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6185     // is a non-constant being inserted into an element other than the low one,
6186     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6187     // movd/movss) to move this into the low element, then shuffle it into
6188     // place.
6189     if (EVTBits == 32) {
6190       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6191       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6192     }
6193   }
6194
6195   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6196   if (Values.size() == 1) {
6197     if (EVTBits == 32) {
6198       // Instead of a shuffle like this:
6199       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6200       // Check if it's possible to issue this instead.
6201       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6202       unsigned Idx = countTrailingZeros(NonZeros);
6203       SDValue Item = Op.getOperand(Idx);
6204       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6205         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6206     }
6207     return SDValue();
6208   }
6209
6210   // A vector full of immediates; various special cases are already
6211   // handled, so this is best done with a single constant-pool load.
6212   if (IsAllConstants)
6213     return SDValue();
6214
6215   // For AVX-length vectors, see if we can use a vector load to get all of the
6216   // elements, otherwise build the individual 128-bit pieces and use
6217   // shuffles to put them in place.
6218   if (VT.is256BitVector() || VT.is512BitVector()) {
6219     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6220
6221     // Check for a build vector of consecutive loads.
6222     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6223       return LD;
6224
6225     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6226
6227     // Build both the lower and upper subvector.
6228     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6229                                 makeArrayRef(&V[0], NumElems/2));
6230     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6231                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6232
6233     // Recreate the wider vector with the lower and upper part.
6234     if (VT.is256BitVector())
6235       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6236     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6237   }
6238
6239   // Let legalizer expand 2-wide build_vectors.
6240   if (EVTBits == 64) {
6241     if (NumNonZero == 1) {
6242       // One half is zero or undef.
6243       unsigned Idx = countTrailingZeros(NonZeros);
6244       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6245                                  Op.getOperand(Idx));
6246       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6247     }
6248     return SDValue();
6249   }
6250
6251   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6252   if (EVTBits == 8 && NumElems == 16)
6253     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6254                                         Subtarget, *this))
6255       return V;
6256
6257   if (EVTBits == 16 && NumElems == 8)
6258     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6259                                       Subtarget, *this))
6260       return V;
6261
6262   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6263   if (EVTBits == 32 && NumElems == 4)
6264     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6265       return V;
6266
6267   // If element VT is == 32 bits, turn it into a number of shuffles.
6268   SmallVector<SDValue, 8> V(NumElems);
6269   if (NumElems == 4 && NumZero > 0) {
6270     for (unsigned i = 0; i < 4; ++i) {
6271       bool isZero = !(NonZeros & (1 << i));
6272       if (isZero)
6273         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6274       else
6275         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6276     }
6277
6278     for (unsigned i = 0; i < 2; ++i) {
6279       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6280         default: break;
6281         case 0:
6282           V[i] = V[i*2];  // Must be a zero vector.
6283           break;
6284         case 1:
6285           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6286           break;
6287         case 2:
6288           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6289           break;
6290         case 3:
6291           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6292           break;
6293       }
6294     }
6295
6296     bool Reverse1 = (NonZeros & 0x3) == 2;
6297     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6298     int MaskVec[] = {
6299       Reverse1 ? 1 : 0,
6300       Reverse1 ? 0 : 1,
6301       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6302       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6303     };
6304     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6305   }
6306
6307   if (Values.size() > 1 && VT.is128BitVector()) {
6308     // Check for a build vector of consecutive loads.
6309     for (unsigned i = 0; i < NumElems; ++i)
6310       V[i] = Op.getOperand(i);
6311
6312     // Check for elements which are consecutive loads.
6313     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6314       return LD;
6315
6316     // Check for a build vector from mostly shuffle plus few inserting.
6317     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6318       return Sh;
6319
6320     // For SSE 4.1, use insertps to put the high elements into the low element.
6321     if (Subtarget->hasSSE41()) {
6322       SDValue Result;
6323       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6324         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6325       else
6326         Result = DAG.getUNDEF(VT);
6327
6328       for (unsigned i = 1; i < NumElems; ++i) {
6329         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6330         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6331                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6332       }
6333       return Result;
6334     }
6335
6336     // Otherwise, expand into a number of unpckl*, start by extending each of
6337     // our (non-undef) elements to the full vector width with the element in the
6338     // bottom slot of the vector (which generates no code for SSE).
6339     for (unsigned i = 0; i < NumElems; ++i) {
6340       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6341         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6342       else
6343         V[i] = DAG.getUNDEF(VT);
6344     }
6345
6346     // Next, we iteratively mix elements, e.g. for v4f32:
6347     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6348     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6349     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6350     unsigned EltStride = NumElems >> 1;
6351     while (EltStride != 0) {
6352       for (unsigned i = 0; i < EltStride; ++i) {
6353         // If V[i+EltStride] is undef and this is the first round of mixing,
6354         // then it is safe to just drop this shuffle: V[i] is already in the
6355         // right place, the one element (since it's the first round) being
6356         // inserted as undef can be dropped.  This isn't safe for successive
6357         // rounds because they will permute elements within both vectors.
6358         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6359             EltStride == NumElems/2)
6360           continue;
6361
6362         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6363       }
6364       EltStride >>= 1;
6365     }
6366     return V[0];
6367   }
6368   return SDValue();
6369 }
6370
6371 // 256-bit AVX can use the vinsertf128 instruction
6372 // to create 256-bit vectors from two other 128-bit ones.
6373 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6374   SDLoc dl(Op);
6375   MVT ResVT = Op.getSimpleValueType();
6376
6377   assert((ResVT.is256BitVector() ||
6378           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6379
6380   SDValue V1 = Op.getOperand(0);
6381   SDValue V2 = Op.getOperand(1);
6382   unsigned NumElems = ResVT.getVectorNumElements();
6383   if (ResVT.is256BitVector())
6384     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6385
6386   if (Op.getNumOperands() == 4) {
6387     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6388                                 ResVT.getVectorNumElements()/2);
6389     SDValue V3 = Op.getOperand(2);
6390     SDValue V4 = Op.getOperand(3);
6391     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6392       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6393   }
6394   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6395 }
6396
6397 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6398                                        const X86Subtarget *Subtarget,
6399                                        SelectionDAG & DAG) {
6400   SDLoc dl(Op);
6401   MVT ResVT = Op.getSimpleValueType();
6402   unsigned NumOfOperands = Op.getNumOperands();
6403
6404   assert(isPowerOf2_32(NumOfOperands) &&
6405          "Unexpected number of operands in CONCAT_VECTORS");
6406
6407   if (NumOfOperands > 2) {
6408     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6409                                   ResVT.getVectorNumElements()/2);
6410     SmallVector<SDValue, 2> Ops;
6411     for (unsigned i = 0; i < NumOfOperands/2; i++)
6412       Ops.push_back(Op.getOperand(i));
6413     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6414     Ops.clear();
6415     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6416       Ops.push_back(Op.getOperand(i));
6417     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6418     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6419   }
6420
6421   SDValue V1 = Op.getOperand(0);
6422   SDValue V2 = Op.getOperand(1);
6423   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6424   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6425
6426   if (IsZeroV1 && IsZeroV2)
6427     return getZeroVector(ResVT, Subtarget, DAG, dl);
6428
6429   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6430   SDValue Undef = DAG.getUNDEF(ResVT);
6431   unsigned NumElems = ResVT.getVectorNumElements();
6432   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6433
6434   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6435   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6436   if (IsZeroV1)
6437     return V2;
6438
6439   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6440   // Zero the upper bits of V1
6441   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6442   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6443   if (IsZeroV2)
6444     return V1;
6445   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6446 }
6447
6448 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6449                                    const X86Subtarget *Subtarget,
6450                                    SelectionDAG &DAG) {
6451   MVT VT = Op.getSimpleValueType();
6452   if (VT.getVectorElementType() == MVT::i1)
6453     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6454
6455   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6456          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6457           Op.getNumOperands() == 4)));
6458
6459   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6460   // from two other 128-bit ones.
6461
6462   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6463   return LowerAVXCONCAT_VECTORS(Op, DAG);
6464 }
6465
6466
6467 //===----------------------------------------------------------------------===//
6468 // Vector shuffle lowering
6469 //
6470 // This is an experimental code path for lowering vector shuffles on x86. It is
6471 // designed to handle arbitrary vector shuffles and blends, gracefully
6472 // degrading performance as necessary. It works hard to recognize idiomatic
6473 // shuffles and lower them to optimal instruction patterns without leaving
6474 // a framework that allows reasonably efficient handling of all vector shuffle
6475 // patterns.
6476 //===----------------------------------------------------------------------===//
6477
6478 /// \brief Tiny helper function to identify a no-op mask.
6479 ///
6480 /// This is a somewhat boring predicate function. It checks whether the mask
6481 /// array input, which is assumed to be a single-input shuffle mask of the kind
6482 /// used by the X86 shuffle instructions (not a fully general
6483 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6484 /// in-place shuffle are 'no-op's.
6485 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6486   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6487     if (Mask[i] != -1 && Mask[i] != i)
6488       return false;
6489   return true;
6490 }
6491
6492 /// \brief Helper function to classify a mask as a single-input mask.
6493 ///
6494 /// This isn't a generic single-input test because in the vector shuffle
6495 /// lowering we canonicalize single inputs to be the first input operand. This
6496 /// means we can more quickly test for a single input by only checking whether
6497 /// an input from the second operand exists. We also assume that the size of
6498 /// mask corresponds to the size of the input vectors which isn't true in the
6499 /// fully general case.
6500 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6501   for (int M : Mask)
6502     if (M >= (int)Mask.size())
6503       return false;
6504   return true;
6505 }
6506
6507 /// \brief Test whether there are elements crossing 128-bit lanes in this
6508 /// shuffle mask.
6509 ///
6510 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6511 /// and we routinely test for these.
6512 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6513   int LaneSize = 128 / VT.getScalarSizeInBits();
6514   int Size = Mask.size();
6515   for (int i = 0; i < Size; ++i)
6516     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6517       return true;
6518   return false;
6519 }
6520
6521 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6522 ///
6523 /// This checks a shuffle mask to see if it is performing the same
6524 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6525 /// that it is also not lane-crossing. It may however involve a blend from the
6526 /// same lane of a second vector.
6527 ///
6528 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6529 /// non-trivial to compute in the face of undef lanes. The representation is
6530 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6531 /// entries from both V1 and V2 inputs to the wider mask.
6532 static bool
6533 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6534                                 SmallVectorImpl<int> &RepeatedMask) {
6535   int LaneSize = 128 / VT.getScalarSizeInBits();
6536   RepeatedMask.resize(LaneSize, -1);
6537   int Size = Mask.size();
6538   for (int i = 0; i < Size; ++i) {
6539     if (Mask[i] < 0)
6540       continue;
6541     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6542       // This entry crosses lanes, so there is no way to model this shuffle.
6543       return false;
6544
6545     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6546     if (RepeatedMask[i % LaneSize] == -1)
6547       // This is the first non-undef entry in this slot of a 128-bit lane.
6548       RepeatedMask[i % LaneSize] =
6549           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6550     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6551       // Found a mismatch with the repeated mask.
6552       return false;
6553   }
6554   return true;
6555 }
6556
6557 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6558 /// arguments.
6559 ///
6560 /// This is a fast way to test a shuffle mask against a fixed pattern:
6561 ///
6562 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6563 ///
6564 /// It returns true if the mask is exactly as wide as the argument list, and
6565 /// each element of the mask is either -1 (signifying undef) or the value given
6566 /// in the argument.
6567 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6568                                 ArrayRef<int> ExpectedMask) {
6569   if (Mask.size() != ExpectedMask.size())
6570     return false;
6571
6572   int Size = Mask.size();
6573
6574   // If the values are build vectors, we can look through them to find
6575   // equivalent inputs that make the shuffles equivalent.
6576   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6577   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6578
6579   for (int i = 0; i < Size; ++i)
6580     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6581       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6582       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6583       if (!MaskBV || !ExpectedBV ||
6584           MaskBV->getOperand(Mask[i] % Size) !=
6585               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6586         return false;
6587     }
6588
6589   return true;
6590 }
6591
6592 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6593 ///
6594 /// This helper function produces an 8-bit shuffle immediate corresponding to
6595 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6596 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6597 /// example.
6598 ///
6599 /// NB: We rely heavily on "undef" masks preserving the input lane.
6600 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6601                                           SelectionDAG &DAG) {
6602   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6603   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6604   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6605   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6606   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6607
6608   unsigned Imm = 0;
6609   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6610   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6611   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6612   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6613   return DAG.getConstant(Imm, DL, MVT::i8);
6614 }
6615
6616 /// \brief Compute whether each element of a shuffle is zeroable.
6617 ///
6618 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6619 /// Either it is an undef element in the shuffle mask, the element of the input
6620 /// referenced is undef, or the element of the input referenced is known to be
6621 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6622 /// as many lanes with this technique as possible to simplify the remaining
6623 /// shuffle.
6624 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6625                                                      SDValue V1, SDValue V2) {
6626   SmallBitVector Zeroable(Mask.size(), false);
6627
6628   while (V1.getOpcode() == ISD::BITCAST)
6629     V1 = V1->getOperand(0);
6630   while (V2.getOpcode() == ISD::BITCAST)
6631     V2 = V2->getOperand(0);
6632
6633   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6634   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6635
6636   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6637     int M = Mask[i];
6638     // Handle the easy cases.
6639     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6640       Zeroable[i] = true;
6641       continue;
6642     }
6643
6644     // If this is an index into a build_vector node (which has the same number
6645     // of elements), dig out the input value and use it.
6646     SDValue V = M < Size ? V1 : V2;
6647     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6648       continue;
6649
6650     SDValue Input = V.getOperand(M % Size);
6651     // The UNDEF opcode check really should be dead code here, but not quite
6652     // worth asserting on (it isn't invalid, just unexpected).
6653     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6654       Zeroable[i] = true;
6655   }
6656
6657   return Zeroable;
6658 }
6659
6660 // X86 has dedicated unpack instructions that can handle specific blend
6661 // operations: UNPCKH and UNPCKL.
6662 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6663                                            SDValue V1, SDValue V2,
6664                                            SelectionDAG &DAG) {
6665   int NumElts = VT.getVectorNumElements();
6666   bool Unpckl = true;
6667   bool Unpckh = true;
6668   bool UnpcklSwapped = true;
6669   bool UnpckhSwapped = true;
6670   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6671
6672   for (int i = 0; i < NumElts; ++i) {
6673     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6674
6675     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6676     int HiPos = LoPos + NumEltsInLane / 2;
6677     int LoPosSwapped = (LoPos + NumElts) % (NumElts * 2);
6678     int HiPosSwapped = (HiPos + NumElts) % (NumElts * 2);
6679
6680     if (Mask[i] == -1)
6681       continue;
6682     if (Mask[i] != LoPos)
6683       Unpckl = false;
6684     if (Mask[i] != HiPos)
6685       Unpckh = false;
6686     if (Mask[i] != LoPosSwapped)
6687       UnpcklSwapped = false;
6688     if (Mask[i] != HiPosSwapped)
6689       UnpckhSwapped = false;
6690     if (!Unpckl && !Unpckh && !UnpcklSwapped && !UnpckhSwapped)
6691       return SDValue();
6692   }
6693   if (Unpckl)
6694     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6695   if (Unpckh)
6696     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6697   if (UnpcklSwapped)
6698     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6699   if (UnpckhSwapped)
6700     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6701
6702   llvm_unreachable("Unexpected result of UNPCK mask analysis");
6703   return SDValue();
6704 }
6705
6706 /// \brief Try to emit a bitmask instruction for a shuffle.
6707 ///
6708 /// This handles cases where we can model a blend exactly as a bitmask due to
6709 /// one of the inputs being zeroable.
6710 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6711                                            SDValue V2, ArrayRef<int> Mask,
6712                                            SelectionDAG &DAG) {
6713   MVT EltVT = VT.getScalarType();
6714   int NumEltBits = EltVT.getSizeInBits();
6715   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6716   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6717   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6718                                     IntEltVT);
6719   if (EltVT.isFloatingPoint()) {
6720     Zero = DAG.getBitcast(EltVT, Zero);
6721     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6722   }
6723   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6724   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6725   SDValue V;
6726   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6727     if (Zeroable[i])
6728       continue;
6729     if (Mask[i] % Size != i)
6730       return SDValue(); // Not a blend.
6731     if (!V)
6732       V = Mask[i] < Size ? V1 : V2;
6733     else if (V != (Mask[i] < Size ? V1 : V2))
6734       return SDValue(); // Can only let one input through the mask.
6735
6736     VMaskOps[i] = AllOnes;
6737   }
6738   if (!V)
6739     return SDValue(); // No non-zeroable elements!
6740
6741   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6742   V = DAG.getNode(VT.isFloatingPoint()
6743                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6744                   DL, VT, V, VMask);
6745   return V;
6746 }
6747
6748 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6749 ///
6750 /// This is used as a fallback approach when first class blend instructions are
6751 /// unavailable. Currently it is only suitable for integer vectors, but could
6752 /// be generalized for floating point vectors if desirable.
6753 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6754                                             SDValue V2, ArrayRef<int> Mask,
6755                                             SelectionDAG &DAG) {
6756   assert(VT.isInteger() && "Only supports integer vector types!");
6757   MVT EltVT = VT.getScalarType();
6758   int NumEltBits = EltVT.getSizeInBits();
6759   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6760   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6761                                     EltVT);
6762   SmallVector<SDValue, 16> MaskOps;
6763   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6764     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6765       return SDValue(); // Shuffled input!
6766     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6767   }
6768
6769   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6770   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6771   // We have to cast V2 around.
6772   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6773   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6774                                       DAG.getBitcast(MaskVT, V1Mask),
6775                                       DAG.getBitcast(MaskVT, V2)));
6776   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6777 }
6778
6779 /// \brief Try to emit a blend instruction for a shuffle.
6780 ///
6781 /// This doesn't do any checks for the availability of instructions for blending
6782 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6783 /// be matched in the backend with the type given. What it does check for is
6784 /// that the shuffle mask is in fact a blend.
6785 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6786                                          SDValue V2, ArrayRef<int> Mask,
6787                                          const X86Subtarget *Subtarget,
6788                                          SelectionDAG &DAG) {
6789   unsigned BlendMask = 0;
6790   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6791     if (Mask[i] >= Size) {
6792       if (Mask[i] != i + Size)
6793         return SDValue(); // Shuffled V2 input!
6794       BlendMask |= 1u << i;
6795       continue;
6796     }
6797     if (Mask[i] >= 0 && Mask[i] != i)
6798       return SDValue(); // Shuffled V1 input!
6799   }
6800   switch (VT.SimpleTy) {
6801   case MVT::v2f64:
6802   case MVT::v4f32:
6803   case MVT::v4f64:
6804   case MVT::v8f32:
6805     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6806                        DAG.getConstant(BlendMask, DL, MVT::i8));
6807
6808   case MVT::v4i64:
6809   case MVT::v8i32:
6810     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6811     // FALLTHROUGH
6812   case MVT::v2i64:
6813   case MVT::v4i32:
6814     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6815     // that instruction.
6816     if (Subtarget->hasAVX2()) {
6817       // Scale the blend by the number of 32-bit dwords per element.
6818       int Scale =  VT.getScalarSizeInBits() / 32;
6819       BlendMask = 0;
6820       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6821         if (Mask[i] >= Size)
6822           for (int j = 0; j < Scale; ++j)
6823             BlendMask |= 1u << (i * Scale + j);
6824
6825       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6826       V1 = DAG.getBitcast(BlendVT, V1);
6827       V2 = DAG.getBitcast(BlendVT, V2);
6828       return DAG.getBitcast(
6829           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6830                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6831     }
6832     // FALLTHROUGH
6833   case MVT::v8i16: {
6834     // For integer shuffles we need to expand the mask and cast the inputs to
6835     // v8i16s prior to blending.
6836     int Scale = 8 / VT.getVectorNumElements();
6837     BlendMask = 0;
6838     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6839       if (Mask[i] >= Size)
6840         for (int j = 0; j < Scale; ++j)
6841           BlendMask |= 1u << (i * Scale + j);
6842
6843     V1 = DAG.getBitcast(MVT::v8i16, V1);
6844     V2 = DAG.getBitcast(MVT::v8i16, V2);
6845     return DAG.getBitcast(VT,
6846                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6847                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6848   }
6849
6850   case MVT::v16i16: {
6851     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6852     SmallVector<int, 8> RepeatedMask;
6853     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6854       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6855       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6856       BlendMask = 0;
6857       for (int i = 0; i < 8; ++i)
6858         if (RepeatedMask[i] >= 16)
6859           BlendMask |= 1u << i;
6860       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6861                          DAG.getConstant(BlendMask, DL, MVT::i8));
6862     }
6863   }
6864     // FALLTHROUGH
6865   case MVT::v16i8:
6866   case MVT::v32i8: {
6867     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6868            "256-bit byte-blends require AVX2 support!");
6869
6870     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6871     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6872       return Masked;
6873
6874     // Scale the blend by the number of bytes per element.
6875     int Scale = VT.getScalarSizeInBits() / 8;
6876
6877     // This form of blend is always done on bytes. Compute the byte vector
6878     // type.
6879     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6880
6881     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6882     // mix of LLVM's code generator and the x86 backend. We tell the code
6883     // generator that boolean values in the elements of an x86 vector register
6884     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6885     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6886     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6887     // of the element (the remaining are ignored) and 0 in that high bit would
6888     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6889     // the LLVM model for boolean values in vector elements gets the relevant
6890     // bit set, it is set backwards and over constrained relative to x86's
6891     // actual model.
6892     SmallVector<SDValue, 32> VSELECTMask;
6893     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6894       for (int j = 0; j < Scale; ++j)
6895         VSELECTMask.push_back(
6896             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6897                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6898                                           MVT::i8));
6899
6900     V1 = DAG.getBitcast(BlendVT, V1);
6901     V2 = DAG.getBitcast(BlendVT, V2);
6902     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6903                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6904                                                       BlendVT, VSELECTMask),
6905                                           V1, V2));
6906   }
6907
6908   default:
6909     llvm_unreachable("Not a supported integer vector type!");
6910   }
6911 }
6912
6913 /// \brief Try to lower as a blend of elements from two inputs followed by
6914 /// a single-input permutation.
6915 ///
6916 /// This matches the pattern where we can blend elements from two inputs and
6917 /// then reduce the shuffle to a single-input permutation.
6918 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6919                                                    SDValue V2,
6920                                                    ArrayRef<int> Mask,
6921                                                    SelectionDAG &DAG) {
6922   // We build up the blend mask while checking whether a blend is a viable way
6923   // to reduce the shuffle.
6924   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6925   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6926
6927   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6928     if (Mask[i] < 0)
6929       continue;
6930
6931     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6932
6933     if (BlendMask[Mask[i] % Size] == -1)
6934       BlendMask[Mask[i] % Size] = Mask[i];
6935     else if (BlendMask[Mask[i] % Size] != Mask[i])
6936       return SDValue(); // Can't blend in the needed input!
6937
6938     PermuteMask[i] = Mask[i] % Size;
6939   }
6940
6941   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6942   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6943 }
6944
6945 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6946 /// blends and permutes.
6947 ///
6948 /// This matches the extremely common pattern for handling combined
6949 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6950 /// operations. It will try to pick the best arrangement of shuffles and
6951 /// blends.
6952 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6953                                                           SDValue V1,
6954                                                           SDValue V2,
6955                                                           ArrayRef<int> Mask,
6956                                                           SelectionDAG &DAG) {
6957   // Shuffle the input elements into the desired positions in V1 and V2 and
6958   // blend them together.
6959   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6960   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6961   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6962   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6963     if (Mask[i] >= 0 && Mask[i] < Size) {
6964       V1Mask[i] = Mask[i];
6965       BlendMask[i] = i;
6966     } else if (Mask[i] >= Size) {
6967       V2Mask[i] = Mask[i] - Size;
6968       BlendMask[i] = i + Size;
6969     }
6970
6971   // Try to lower with the simpler initial blend strategy unless one of the
6972   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6973   // shuffle may be able to fold with a load or other benefit. However, when
6974   // we'll have to do 2x as many shuffles in order to achieve this, blending
6975   // first is a better strategy.
6976   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6977     if (SDValue BlendPerm =
6978             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6979       return BlendPerm;
6980
6981   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6982   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6983   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6984 }
6985
6986 /// \brief Try to lower a vector shuffle as a byte rotation.
6987 ///
6988 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6989 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6990 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6991 /// try to generically lower a vector shuffle through such an pattern. It
6992 /// does not check for the profitability of lowering either as PALIGNR or
6993 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6994 /// This matches shuffle vectors that look like:
6995 ///
6996 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6997 ///
6998 /// Essentially it concatenates V1 and V2, shifts right by some number of
6999 /// elements, and takes the low elements as the result. Note that while this is
7000 /// specified as a *right shift* because x86 is little-endian, it is a *left
7001 /// rotate* of the vector lanes.
7002 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7003                                               SDValue V2,
7004                                               ArrayRef<int> Mask,
7005                                               const X86Subtarget *Subtarget,
7006                                               SelectionDAG &DAG) {
7007   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7008
7009   int NumElts = Mask.size();
7010   int NumLanes = VT.getSizeInBits() / 128;
7011   int NumLaneElts = NumElts / NumLanes;
7012
7013   // We need to detect various ways of spelling a rotation:
7014   //   [11, 12, 13, 14, 15,  0,  1,  2]
7015   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7016   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7017   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7018   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7019   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7020   int Rotation = 0;
7021   SDValue Lo, Hi;
7022   for (int l = 0; l < NumElts; l += NumLaneElts) {
7023     for (int i = 0; i < NumLaneElts; ++i) {
7024       if (Mask[l + i] == -1)
7025         continue;
7026       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7027
7028       // Get the mod-Size index and lane correct it.
7029       int LaneIdx = (Mask[l + i] % NumElts) - l;
7030       // Make sure it was in this lane.
7031       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7032         return SDValue();
7033
7034       // Determine where a rotated vector would have started.
7035       int StartIdx = i - LaneIdx;
7036       if (StartIdx == 0)
7037         // The identity rotation isn't interesting, stop.
7038         return SDValue();
7039
7040       // If we found the tail of a vector the rotation must be the missing
7041       // front. If we found the head of a vector, it must be how much of the
7042       // head.
7043       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7044
7045       if (Rotation == 0)
7046         Rotation = CandidateRotation;
7047       else if (Rotation != CandidateRotation)
7048         // The rotations don't match, so we can't match this mask.
7049         return SDValue();
7050
7051       // Compute which value this mask is pointing at.
7052       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7053
7054       // Compute which of the two target values this index should be assigned
7055       // to. This reflects whether the high elements are remaining or the low
7056       // elements are remaining.
7057       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7058
7059       // Either set up this value if we've not encountered it before, or check
7060       // that it remains consistent.
7061       if (!TargetV)
7062         TargetV = MaskV;
7063       else if (TargetV != MaskV)
7064         // This may be a rotation, but it pulls from the inputs in some
7065         // unsupported interleaving.
7066         return SDValue();
7067     }
7068   }
7069
7070   // Check that we successfully analyzed the mask, and normalize the results.
7071   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7072   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7073   if (!Lo)
7074     Lo = Hi;
7075   else if (!Hi)
7076     Hi = Lo;
7077
7078   // The actual rotate instruction rotates bytes, so we need to scale the
7079   // rotation based on how many bytes are in the vector lane.
7080   int Scale = 16 / NumLaneElts;
7081
7082   // SSSE3 targets can use the palignr instruction.
7083   if (Subtarget->hasSSSE3()) {
7084     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7085     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7086     Lo = DAG.getBitcast(AlignVT, Lo);
7087     Hi = DAG.getBitcast(AlignVT, Hi);
7088
7089     return DAG.getBitcast(
7090         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7091                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7092   }
7093
7094   assert(VT.getSizeInBits() == 128 &&
7095          "Rotate-based lowering only supports 128-bit lowering!");
7096   assert(Mask.size() <= 16 &&
7097          "Can shuffle at most 16 bytes in a 128-bit vector!");
7098
7099   // Default SSE2 implementation
7100   int LoByteShift = 16 - Rotation * Scale;
7101   int HiByteShift = Rotation * Scale;
7102
7103   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7104   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7105   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7106
7107   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7108                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7109   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7110                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7111   return DAG.getBitcast(VT,
7112                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7113 }
7114
7115 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7116 ///
7117 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7118 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7119 /// matches elements from one of the input vectors shuffled to the left or
7120 /// right with zeroable elements 'shifted in'. It handles both the strictly
7121 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7122 /// quad word lane.
7123 ///
7124 /// PSHL : (little-endian) left bit shift.
7125 /// [ zz, 0, zz,  2 ]
7126 /// [ -1, 4, zz, -1 ]
7127 /// PSRL : (little-endian) right bit shift.
7128 /// [  1, zz,  3, zz]
7129 /// [ -1, -1,  7, zz]
7130 /// PSLLDQ : (little-endian) left byte shift
7131 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7132 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7133 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7134 /// PSRLDQ : (little-endian) right byte shift
7135 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7136 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7137 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7138 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7139                                          SDValue V2, ArrayRef<int> Mask,
7140                                          SelectionDAG &DAG) {
7141   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7142
7143   int Size = Mask.size();
7144   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7145
7146   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7147     for (int i = 0; i < Size; i += Scale)
7148       for (int j = 0; j < Shift; ++j)
7149         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7150           return false;
7151
7152     return true;
7153   };
7154
7155   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7156     for (int i = 0; i != Size; i += Scale) {
7157       unsigned Pos = Left ? i + Shift : i;
7158       unsigned Low = Left ? i : i + Shift;
7159       unsigned Len = Scale - Shift;
7160       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7161                                       Low + (V == V1 ? 0 : Size)))
7162         return SDValue();
7163     }
7164
7165     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7166     bool ByteShift = ShiftEltBits > 64;
7167     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7168                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7169     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7170
7171     // Normalize the scale for byte shifts to still produce an i64 element
7172     // type.
7173     Scale = ByteShift ? Scale / 2 : Scale;
7174
7175     // We need to round trip through the appropriate type for the shift.
7176     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7177     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7178     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7179            "Illegal integer vector type");
7180     V = DAG.getBitcast(ShiftVT, V);
7181
7182     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7183                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7184     return DAG.getBitcast(VT, V);
7185   };
7186
7187   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7188   // keep doubling the size of the integer elements up to that. We can
7189   // then shift the elements of the integer vector by whole multiples of
7190   // their width within the elements of the larger integer vector. Test each
7191   // multiple to see if we can find a match with the moved element indices
7192   // and that the shifted in elements are all zeroable.
7193   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7194     for (int Shift = 1; Shift != Scale; ++Shift)
7195       for (bool Left : {true, false})
7196         if (CheckZeros(Shift, Scale, Left))
7197           for (SDValue V : {V1, V2})
7198             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7199               return Match;
7200
7201   // no match
7202   return SDValue();
7203 }
7204
7205 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7206 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7207                                            SDValue V2, ArrayRef<int> Mask,
7208                                            SelectionDAG &DAG) {
7209   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7210   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7211
7212   int Size = Mask.size();
7213   int HalfSize = Size / 2;
7214   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7215
7216   // Upper half must be undefined.
7217   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7218     return SDValue();
7219
7220   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7221   // Remainder of lower half result is zero and upper half is all undef.
7222   auto LowerAsEXTRQ = [&]() {
7223     // Determine the extraction length from the part of the
7224     // lower half that isn't zeroable.
7225     int Len = HalfSize;
7226     for (; Len >= 0; --Len)
7227       if (!Zeroable[Len - 1])
7228         break;
7229     assert(Len > 0 && "Zeroable shuffle mask");
7230
7231     // Attempt to match first Len sequential elements from the lower half.
7232     SDValue Src;
7233     int Idx = -1;
7234     for (int i = 0; i != Len; ++i) {
7235       int M = Mask[i];
7236       if (M < 0)
7237         continue;
7238       SDValue &V = (M < Size ? V1 : V2);
7239       M = M % Size;
7240
7241       // All mask elements must be in the lower half.
7242       if (M > HalfSize)
7243         return SDValue();
7244
7245       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7246         Src = V;
7247         Idx = M - i;
7248         continue;
7249       }
7250       return SDValue();
7251     }
7252
7253     if (Idx < 0)
7254       return SDValue();
7255
7256     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7257     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7258     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7259     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7260                        DAG.getConstant(BitLen, DL, MVT::i8),
7261                        DAG.getConstant(BitIdx, DL, MVT::i8));
7262   };
7263
7264   if (SDValue ExtrQ = LowerAsEXTRQ())
7265     return ExtrQ;
7266
7267   // INSERTQ: Extract lowest Len elements from lower half of second source and
7268   // insert over first source, starting at Idx.
7269   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7270   auto LowerAsInsertQ = [&]() {
7271     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7272       SDValue Base;
7273
7274       // Attempt to match first source from mask before insertion point.
7275       if (isUndefInRange(Mask, 0, Idx)) {
7276         /* EMPTY */
7277       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7278         Base = V1;
7279       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7280         Base = V2;
7281       } else {
7282         continue;
7283       }
7284
7285       // Extend the extraction length looking to match both the insertion of
7286       // the second source and the remaining elements of the first.
7287       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7288         SDValue Insert;
7289         int Len = Hi - Idx;
7290
7291         // Match insertion.
7292         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7293           Insert = V1;
7294         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7295           Insert = V2;
7296         } else {
7297           continue;
7298         }
7299
7300         // Match the remaining elements of the lower half.
7301         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7302           /* EMPTY */
7303         } else if ((!Base || (Base == V1)) &&
7304                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7305           Base = V1;
7306         } else if ((!Base || (Base == V2)) &&
7307                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7308                                               Size + Hi)) {
7309           Base = V2;
7310         } else {
7311           continue;
7312         }
7313
7314         // We may not have a base (first source) - this can safely be undefined.
7315         if (!Base)
7316           Base = DAG.getUNDEF(VT);
7317
7318         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7319         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7320         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7321                            DAG.getConstant(BitLen, DL, MVT::i8),
7322                            DAG.getConstant(BitIdx, DL, MVT::i8));
7323       }
7324     }
7325
7326     return SDValue();
7327   };
7328
7329   if (SDValue InsertQ = LowerAsInsertQ())
7330     return InsertQ;
7331
7332   return SDValue();
7333 }
7334
7335 /// \brief Lower a vector shuffle as a zero or any extension.
7336 ///
7337 /// Given a specific number of elements, element bit width, and extension
7338 /// stride, produce either a zero or any extension based on the available
7339 /// features of the subtarget.
7340 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7341     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7342     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7343   assert(Scale > 1 && "Need a scale to extend.");
7344   int NumElements = VT.getVectorNumElements();
7345   int EltBits = VT.getScalarSizeInBits();
7346   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7347          "Only 8, 16, and 32 bit elements can be extended.");
7348   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7349
7350   // Found a valid zext mask! Try various lowering strategies based on the
7351   // input type and available ISA extensions.
7352   if (Subtarget->hasSSE41()) {
7353     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7354                                  NumElements / Scale);
7355     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7356   }
7357
7358   // For any extends we can cheat for larger element sizes and use shuffle
7359   // instructions that can fold with a load and/or copy.
7360   if (AnyExt && EltBits == 32) {
7361     int PSHUFDMask[4] = {0, -1, 1, -1};
7362     return DAG.getBitcast(
7363         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7364                         DAG.getBitcast(MVT::v4i32, InputV),
7365                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7366   }
7367   if (AnyExt && EltBits == 16 && Scale > 2) {
7368     int PSHUFDMask[4] = {0, -1, 0, -1};
7369     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7370                          DAG.getBitcast(MVT::v4i32, InputV),
7371                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7372     int PSHUFHWMask[4] = {1, -1, -1, -1};
7373     return DAG.getBitcast(
7374         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7375                         DAG.getBitcast(MVT::v8i16, InputV),
7376                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7377   }
7378
7379   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7380   // to 64-bits.
7381   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7382     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7383     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7384
7385     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7386                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7387                                          DAG.getConstant(EltBits, DL, MVT::i8),
7388                                          DAG.getConstant(0, DL, MVT::i8)));
7389     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7390       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7391
7392     SDValue Hi =
7393         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7394                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7395                                 DAG.getConstant(EltBits, DL, MVT::i8),
7396                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7397     return DAG.getNode(ISD::BITCAST, DL, VT,
7398                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7399   }
7400
7401   // If this would require more than 2 unpack instructions to expand, use
7402   // pshufb when available. We can only use more than 2 unpack instructions
7403   // when zero extending i8 elements which also makes it easier to use pshufb.
7404   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7405     assert(NumElements == 16 && "Unexpected byte vector width!");
7406     SDValue PSHUFBMask[16];
7407     for (int i = 0; i < 16; ++i)
7408       PSHUFBMask[i] =
7409           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7410     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7411     return DAG.getBitcast(VT,
7412                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7413                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7414                                                   MVT::v16i8, PSHUFBMask)));
7415   }
7416
7417   // Otherwise emit a sequence of unpacks.
7418   do {
7419     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7420     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7421                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7422     InputV = DAG.getBitcast(InputVT, InputV);
7423     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7424     Scale /= 2;
7425     EltBits *= 2;
7426     NumElements /= 2;
7427   } while (Scale > 1);
7428   return DAG.getBitcast(VT, InputV);
7429 }
7430
7431 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7432 ///
7433 /// This routine will try to do everything in its power to cleverly lower
7434 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7435 /// check for the profitability of this lowering,  it tries to aggressively
7436 /// match this pattern. It will use all of the micro-architectural details it
7437 /// can to emit an efficient lowering. It handles both blends with all-zero
7438 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7439 /// masking out later).
7440 ///
7441 /// The reason we have dedicated lowering for zext-style shuffles is that they
7442 /// are both incredibly common and often quite performance sensitive.
7443 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7444     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7445     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7446   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7447
7448   int Bits = VT.getSizeInBits();
7449   int NumElements = VT.getVectorNumElements();
7450   assert(VT.getScalarSizeInBits() <= 32 &&
7451          "Exceeds 32-bit integer zero extension limit");
7452   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7453
7454   // Define a helper function to check a particular ext-scale and lower to it if
7455   // valid.
7456   auto Lower = [&](int Scale) -> SDValue {
7457     SDValue InputV;
7458     bool AnyExt = true;
7459     for (int i = 0; i < NumElements; ++i) {
7460       if (Mask[i] == -1)
7461         continue; // Valid anywhere but doesn't tell us anything.
7462       if (i % Scale != 0) {
7463         // Each of the extended elements need to be zeroable.
7464         if (!Zeroable[i])
7465           return SDValue();
7466
7467         // We no longer are in the anyext case.
7468         AnyExt = false;
7469         continue;
7470       }
7471
7472       // Each of the base elements needs to be consecutive indices into the
7473       // same input vector.
7474       SDValue V = Mask[i] < NumElements ? V1 : V2;
7475       if (!InputV)
7476         InputV = V;
7477       else if (InputV != V)
7478         return SDValue(); // Flip-flopping inputs.
7479
7480       if (Mask[i] % NumElements != i / Scale)
7481         return SDValue(); // Non-consecutive strided elements.
7482     }
7483
7484     // If we fail to find an input, we have a zero-shuffle which should always
7485     // have already been handled.
7486     // FIXME: Maybe handle this here in case during blending we end up with one?
7487     if (!InputV)
7488       return SDValue();
7489
7490     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7491         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7492   };
7493
7494   // The widest scale possible for extending is to a 64-bit integer.
7495   assert(Bits % 64 == 0 &&
7496          "The number of bits in a vector must be divisible by 64 on x86!");
7497   int NumExtElements = Bits / 64;
7498
7499   // Each iteration, try extending the elements half as much, but into twice as
7500   // many elements.
7501   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7502     assert(NumElements % NumExtElements == 0 &&
7503            "The input vector size must be divisible by the extended size.");
7504     if (SDValue V = Lower(NumElements / NumExtElements))
7505       return V;
7506   }
7507
7508   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7509   if (Bits != 128)
7510     return SDValue();
7511
7512   // Returns one of the source operands if the shuffle can be reduced to a
7513   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7514   auto CanZExtLowHalf = [&]() {
7515     for (int i = NumElements / 2; i != NumElements; ++i)
7516       if (!Zeroable[i])
7517         return SDValue();
7518     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7519       return V1;
7520     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7521       return V2;
7522     return SDValue();
7523   };
7524
7525   if (SDValue V = CanZExtLowHalf()) {
7526     V = DAG.getBitcast(MVT::v2i64, V);
7527     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7528     return DAG.getBitcast(VT, V);
7529   }
7530
7531   // No viable ext lowering found.
7532   return SDValue();
7533 }
7534
7535 /// \brief Try to get a scalar value for a specific element of a vector.
7536 ///
7537 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7538 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7539                                               SelectionDAG &DAG) {
7540   MVT VT = V.getSimpleValueType();
7541   MVT EltVT = VT.getVectorElementType();
7542   while (V.getOpcode() == ISD::BITCAST)
7543     V = V.getOperand(0);
7544   // If the bitcasts shift the element size, we can't extract an equivalent
7545   // element from it.
7546   MVT NewVT = V.getSimpleValueType();
7547   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7548     return SDValue();
7549
7550   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7551       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7552     // Ensure the scalar operand is the same size as the destination.
7553     // FIXME: Add support for scalar truncation where possible.
7554     SDValue S = V.getOperand(Idx);
7555     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7556       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7557   }
7558
7559   return SDValue();
7560 }
7561
7562 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7563 ///
7564 /// This is particularly important because the set of instructions varies
7565 /// significantly based on whether the operand is a load or not.
7566 static bool isShuffleFoldableLoad(SDValue V) {
7567   while (V.getOpcode() == ISD::BITCAST)
7568     V = V.getOperand(0);
7569
7570   return ISD::isNON_EXTLoad(V.getNode());
7571 }
7572
7573 /// \brief Try to lower insertion of a single element into a zero vector.
7574 ///
7575 /// This is a common pattern that we have especially efficient patterns to lower
7576 /// across all subtarget feature sets.
7577 static SDValue lowerVectorShuffleAsElementInsertion(
7578     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7579     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7580   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7581   MVT ExtVT = VT;
7582   MVT EltVT = VT.getVectorElementType();
7583
7584   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7585                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7586                 Mask.begin();
7587   bool IsV1Zeroable = true;
7588   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7589     if (i != V2Index && !Zeroable[i]) {
7590       IsV1Zeroable = false;
7591       break;
7592     }
7593
7594   // Check for a single input from a SCALAR_TO_VECTOR node.
7595   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7596   // all the smarts here sunk into that routine. However, the current
7597   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7598   // vector shuffle lowering is dead.
7599   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7600                                                DAG);
7601   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7602     // We need to zext the scalar if it is smaller than an i32.
7603     V2S = DAG.getBitcast(EltVT, V2S);
7604     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7605       // Using zext to expand a narrow element won't work for non-zero
7606       // insertions.
7607       if (!IsV1Zeroable)
7608         return SDValue();
7609
7610       // Zero-extend directly to i32.
7611       ExtVT = MVT::v4i32;
7612       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7613     }
7614     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7615   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7616              EltVT == MVT::i16) {
7617     // Either not inserting from the low element of the input or the input
7618     // element size is too small to use VZEXT_MOVL to clear the high bits.
7619     return SDValue();
7620   }
7621
7622   if (!IsV1Zeroable) {
7623     // If V1 can't be treated as a zero vector we have fewer options to lower
7624     // this. We can't support integer vectors or non-zero targets cheaply, and
7625     // the V1 elements can't be permuted in any way.
7626     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7627     if (!VT.isFloatingPoint() || V2Index != 0)
7628       return SDValue();
7629     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7630     V1Mask[V2Index] = -1;
7631     if (!isNoopShuffleMask(V1Mask))
7632       return SDValue();
7633     // This is essentially a special case blend operation, but if we have
7634     // general purpose blend operations, they are always faster. Bail and let
7635     // the rest of the lowering handle these as blends.
7636     if (Subtarget->hasSSE41())
7637       return SDValue();
7638
7639     // Otherwise, use MOVSD or MOVSS.
7640     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7641            "Only two types of floating point element types to handle!");
7642     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7643                        ExtVT, V1, V2);
7644   }
7645
7646   // This lowering only works for the low element with floating point vectors.
7647   if (VT.isFloatingPoint() && V2Index != 0)
7648     return SDValue();
7649
7650   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7651   if (ExtVT != VT)
7652     V2 = DAG.getBitcast(VT, V2);
7653
7654   if (V2Index != 0) {
7655     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7656     // the desired position. Otherwise it is more efficient to do a vector
7657     // shift left. We know that we can do a vector shift left because all
7658     // the inputs are zero.
7659     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7660       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7661       V2Shuffle[V2Index] = 0;
7662       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7663     } else {
7664       V2 = DAG.getBitcast(MVT::v2i64, V2);
7665       V2 = DAG.getNode(
7666           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7667           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7668                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7669                               DAG.getDataLayout(), VT)));
7670       V2 = DAG.getBitcast(VT, V2);
7671     }
7672   }
7673   return V2;
7674 }
7675
7676 /// \brief Try to lower broadcast of a single element.
7677 ///
7678 /// For convenience, this code also bundles all of the subtarget feature set
7679 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7680 /// a convenient way to factor it out.
7681 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7682                                              ArrayRef<int> Mask,
7683                                              const X86Subtarget *Subtarget,
7684                                              SelectionDAG &DAG) {
7685   if (!Subtarget->hasAVX())
7686     return SDValue();
7687   if (VT.isInteger() && !Subtarget->hasAVX2())
7688     return SDValue();
7689
7690   // Check that the mask is a broadcast.
7691   int BroadcastIdx = -1;
7692   for (int M : Mask)
7693     if (M >= 0 && BroadcastIdx == -1)
7694       BroadcastIdx = M;
7695     else if (M >= 0 && M != BroadcastIdx)
7696       return SDValue();
7697
7698   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7699                                             "a sorted mask where the broadcast "
7700                                             "comes from V1.");
7701
7702   // Go up the chain of (vector) values to find a scalar load that we can
7703   // combine with the broadcast.
7704   for (;;) {
7705     switch (V.getOpcode()) {
7706     case ISD::CONCAT_VECTORS: {
7707       int OperandSize = Mask.size() / V.getNumOperands();
7708       V = V.getOperand(BroadcastIdx / OperandSize);
7709       BroadcastIdx %= OperandSize;
7710       continue;
7711     }
7712
7713     case ISD::INSERT_SUBVECTOR: {
7714       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7715       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7716       if (!ConstantIdx)
7717         break;
7718
7719       int BeginIdx = (int)ConstantIdx->getZExtValue();
7720       int EndIdx =
7721           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7722       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7723         BroadcastIdx -= BeginIdx;
7724         V = VInner;
7725       } else {
7726         V = VOuter;
7727       }
7728       continue;
7729     }
7730     }
7731     break;
7732   }
7733
7734   // Check if this is a broadcast of a scalar. We special case lowering
7735   // for scalars so that we can more effectively fold with loads.
7736   // First, look through bitcast: if the original value has a larger element
7737   // type than the shuffle, the broadcast element is in essence truncated.
7738   // Make that explicit to ease folding.
7739   if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7740     EVT EltVT = VT.getVectorElementType();
7741     SDValue V0 = V.getOperand(0);
7742     EVT V0VT = V0.getValueType();
7743
7744     if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7745         ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7746          (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7747       V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7748       BroadcastIdx = 0;
7749     }
7750   }
7751
7752   // Also check the simpler case, where we can directly reuse the scalar.
7753   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7754       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7755     V = V.getOperand(BroadcastIdx);
7756
7757     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7758     // Only AVX2 has register broadcasts.
7759     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7760       return SDValue();
7761   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7762     // We can't broadcast from a vector register without AVX2, and we can only
7763     // broadcast from the zero-element of a vector register.
7764     return SDValue();
7765   }
7766
7767   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7768 }
7769
7770 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7771 // INSERTPS when the V1 elements are already in the correct locations
7772 // because otherwise we can just always use two SHUFPS instructions which
7773 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7774 // perform INSERTPS if a single V1 element is out of place and all V2
7775 // elements are zeroable.
7776 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7777                                             ArrayRef<int> Mask,
7778                                             SelectionDAG &DAG) {
7779   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7780   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7781   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7782   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7783
7784   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7785
7786   unsigned ZMask = 0;
7787   int V1DstIndex = -1;
7788   int V2DstIndex = -1;
7789   bool V1UsedInPlace = false;
7790
7791   for (int i = 0; i < 4; ++i) {
7792     // Synthesize a zero mask from the zeroable elements (includes undefs).
7793     if (Zeroable[i]) {
7794       ZMask |= 1 << i;
7795       continue;
7796     }
7797
7798     // Flag if we use any V1 inputs in place.
7799     if (i == Mask[i]) {
7800       V1UsedInPlace = true;
7801       continue;
7802     }
7803
7804     // We can only insert a single non-zeroable element.
7805     if (V1DstIndex != -1 || V2DstIndex != -1)
7806       return SDValue();
7807
7808     if (Mask[i] < 4) {
7809       // V1 input out of place for insertion.
7810       V1DstIndex = i;
7811     } else {
7812       // V2 input for insertion.
7813       V2DstIndex = i;
7814     }
7815   }
7816
7817   // Don't bother if we have no (non-zeroable) element for insertion.
7818   if (V1DstIndex == -1 && V2DstIndex == -1)
7819     return SDValue();
7820
7821   // Determine element insertion src/dst indices. The src index is from the
7822   // start of the inserted vector, not the start of the concatenated vector.
7823   unsigned V2SrcIndex = 0;
7824   if (V1DstIndex != -1) {
7825     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7826     // and don't use the original V2 at all.
7827     V2SrcIndex = Mask[V1DstIndex];
7828     V2DstIndex = V1DstIndex;
7829     V2 = V1;
7830   } else {
7831     V2SrcIndex = Mask[V2DstIndex] - 4;
7832   }
7833
7834   // If no V1 inputs are used in place, then the result is created only from
7835   // the zero mask and the V2 insertion - so remove V1 dependency.
7836   if (!V1UsedInPlace)
7837     V1 = DAG.getUNDEF(MVT::v4f32);
7838
7839   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7840   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7841
7842   // Insert the V2 element into the desired position.
7843   SDLoc DL(Op);
7844   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7845                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7846 }
7847
7848 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7849 /// UNPCK instruction.
7850 ///
7851 /// This specifically targets cases where we end up with alternating between
7852 /// the two inputs, and so can permute them into something that feeds a single
7853 /// UNPCK instruction. Note that this routine only targets integer vectors
7854 /// because for floating point vectors we have a generalized SHUFPS lowering
7855 /// strategy that handles everything that doesn't *exactly* match an unpack,
7856 /// making this clever lowering unnecessary.
7857 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
7858                                                     SDValue V1, SDValue V2,
7859                                                     ArrayRef<int> Mask,
7860                                                     SelectionDAG &DAG) {
7861   assert(!VT.isFloatingPoint() &&
7862          "This routine only supports integer vectors.");
7863   assert(!isSingleInputShuffleMask(Mask) &&
7864          "This routine should only be used when blending two inputs.");
7865   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7866
7867   int Size = Mask.size();
7868
7869   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7870     return M >= 0 && M % Size < Size / 2;
7871   });
7872   int NumHiInputs = std::count_if(
7873       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7874
7875   bool UnpackLo = NumLoInputs >= NumHiInputs;
7876
7877   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7878     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7879     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7880
7881     for (int i = 0; i < Size; ++i) {
7882       if (Mask[i] < 0)
7883         continue;
7884
7885       // Each element of the unpack contains Scale elements from this mask.
7886       int UnpackIdx = i / Scale;
7887
7888       // We only handle the case where V1 feeds the first slots of the unpack.
7889       // We rely on canonicalization to ensure this is the case.
7890       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7891         return SDValue();
7892
7893       // Setup the mask for this input. The indexing is tricky as we have to
7894       // handle the unpack stride.
7895       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7896       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7897           Mask[i] % Size;
7898     }
7899
7900     // If we will have to shuffle both inputs to use the unpack, check whether
7901     // we can just unpack first and shuffle the result. If so, skip this unpack.
7902     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7903         !isNoopShuffleMask(V2Mask))
7904       return SDValue();
7905
7906     // Shuffle the inputs into place.
7907     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7908     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7909
7910     // Cast the inputs to the type we will use to unpack them.
7911     V1 = DAG.getBitcast(UnpackVT, V1);
7912     V2 = DAG.getBitcast(UnpackVT, V2);
7913
7914     // Unpack the inputs and cast the result back to the desired type.
7915     return DAG.getBitcast(
7916         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7917                         UnpackVT, V1, V2));
7918   };
7919
7920   // We try each unpack from the largest to the smallest to try and find one
7921   // that fits this mask.
7922   int OrigNumElements = VT.getVectorNumElements();
7923   int OrigScalarSize = VT.getScalarSizeInBits();
7924   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7925     int Scale = ScalarSize / OrigScalarSize;
7926     int NumElements = OrigNumElements / Scale;
7927     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7928     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7929       return Unpack;
7930   }
7931
7932   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7933   // initial unpack.
7934   if (NumLoInputs == 0 || NumHiInputs == 0) {
7935     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7936            "We have to have *some* inputs!");
7937     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7938
7939     // FIXME: We could consider the total complexity of the permute of each
7940     // possible unpacking. Or at the least we should consider how many
7941     // half-crossings are created.
7942     // FIXME: We could consider commuting the unpacks.
7943
7944     SmallVector<int, 32> PermMask;
7945     PermMask.assign(Size, -1);
7946     for (int i = 0; i < Size; ++i) {
7947       if (Mask[i] < 0)
7948         continue;
7949
7950       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7951
7952       PermMask[i] =
7953           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7954     }
7955     return DAG.getVectorShuffle(
7956         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7957                             DL, VT, V1, V2),
7958         DAG.getUNDEF(VT), PermMask);
7959   }
7960
7961   return SDValue();
7962 }
7963
7964 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7965 ///
7966 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7967 /// support for floating point shuffles but not integer shuffles. These
7968 /// instructions will incur a domain crossing penalty on some chips though so
7969 /// it is better to avoid lowering through this for integer vectors where
7970 /// possible.
7971 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7972                                        const X86Subtarget *Subtarget,
7973                                        SelectionDAG &DAG) {
7974   SDLoc DL(Op);
7975   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7976   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7977   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7978   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7979   ArrayRef<int> Mask = SVOp->getMask();
7980   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7981
7982   if (isSingleInputShuffleMask(Mask)) {
7983     // Use low duplicate instructions for masks that match their pattern.
7984     if (Subtarget->hasSSE3())
7985       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7986         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7987
7988     // Straight shuffle of a single input vector. Simulate this by using the
7989     // single input as both of the "inputs" to this instruction..
7990     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7991
7992     if (Subtarget->hasAVX()) {
7993       // If we have AVX, we can use VPERMILPS which will allow folding a load
7994       // into the shuffle.
7995       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7996                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7997     }
7998
7999     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8000                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8001   }
8002   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8003   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8004
8005   // If we have a single input, insert that into V1 if we can do so cheaply.
8006   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8007     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8008             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8009       return Insertion;
8010     // Try inverting the insertion since for v2 masks it is easy to do and we
8011     // can't reliably sort the mask one way or the other.
8012     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8013                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8014     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8015             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8016       return Insertion;
8017   }
8018
8019   // Try to use one of the special instruction patterns to handle two common
8020   // blend patterns if a zero-blend above didn't work.
8021   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8022       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8023     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8024       // We can either use a special instruction to load over the low double or
8025       // to move just the low double.
8026       return DAG.getNode(
8027           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8028           DL, MVT::v2f64, V2,
8029           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8030
8031   if (Subtarget->hasSSE41())
8032     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8033                                                   Subtarget, DAG))
8034       return Blend;
8035
8036   // Use dedicated unpack instructions for masks that match their pattern.
8037   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8038     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8039   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8040     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8041
8042   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8043   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8044                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8045 }
8046
8047 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8048 ///
8049 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8050 /// the integer unit to minimize domain crossing penalties. However, for blends
8051 /// it falls back to the floating point shuffle operation with appropriate bit
8052 /// casting.
8053 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8054                                        const X86Subtarget *Subtarget,
8055                                        SelectionDAG &DAG) {
8056   SDLoc DL(Op);
8057   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8058   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8059   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8060   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8061   ArrayRef<int> Mask = SVOp->getMask();
8062   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8063
8064   if (isSingleInputShuffleMask(Mask)) {
8065     // Check for being able to broadcast a single element.
8066     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8067                                                           Mask, Subtarget, DAG))
8068       return Broadcast;
8069
8070     // Straight shuffle of a single input vector. For everything from SSE2
8071     // onward this has a single fast instruction with no scary immediates.
8072     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8073     V1 = DAG.getBitcast(MVT::v4i32, V1);
8074     int WidenedMask[4] = {
8075         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8076         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8077     return DAG.getBitcast(
8078         MVT::v2i64,
8079         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8080                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8081   }
8082   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8083   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8084   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8085   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8086
8087   // If we have a blend of two PACKUS operations an the blend aligns with the
8088   // low and half halves, we can just merge the PACKUS operations. This is
8089   // particularly important as it lets us merge shuffles that this routine itself
8090   // creates.
8091   auto GetPackNode = [](SDValue V) {
8092     while (V.getOpcode() == ISD::BITCAST)
8093       V = V.getOperand(0);
8094
8095     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8096   };
8097   if (SDValue V1Pack = GetPackNode(V1))
8098     if (SDValue V2Pack = GetPackNode(V2))
8099       return DAG.getBitcast(MVT::v2i64,
8100                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8101                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8102                                                      : V1Pack.getOperand(1),
8103                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8104                                                      : V2Pack.getOperand(1)));
8105
8106   // Try to use shift instructions.
8107   if (SDValue Shift =
8108           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8109     return Shift;
8110
8111   // When loading a scalar and then shuffling it into a vector we can often do
8112   // the insertion cheaply.
8113   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8114           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8115     return Insertion;
8116   // Try inverting the insertion since for v2 masks it is easy to do and we
8117   // can't reliably sort the mask one way or the other.
8118   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8119   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8120           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8121     return Insertion;
8122
8123   // We have different paths for blend lowering, but they all must use the
8124   // *exact* same predicate.
8125   bool IsBlendSupported = Subtarget->hasSSE41();
8126   if (IsBlendSupported)
8127     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8128                                                   Subtarget, DAG))
8129       return Blend;
8130
8131   // Use dedicated unpack instructions for masks that match their pattern.
8132   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8133     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8134   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8135     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8136
8137   // Try to use byte rotation instructions.
8138   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8139   if (Subtarget->hasSSSE3())
8140     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8141             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8142       return Rotate;
8143
8144   // If we have direct support for blends, we should lower by decomposing into
8145   // a permute. That will be faster than the domain cross.
8146   if (IsBlendSupported)
8147     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8148                                                       Mask, DAG);
8149
8150   // We implement this with SHUFPD which is pretty lame because it will likely
8151   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8152   // However, all the alternatives are still more cycles and newer chips don't
8153   // have this problem. It would be really nice if x86 had better shuffles here.
8154   V1 = DAG.getBitcast(MVT::v2f64, V1);
8155   V2 = DAG.getBitcast(MVT::v2f64, V2);
8156   return DAG.getBitcast(MVT::v2i64,
8157                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8158 }
8159
8160 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8161 ///
8162 /// This is used to disable more specialized lowerings when the shufps lowering
8163 /// will happen to be efficient.
8164 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8165   // This routine only handles 128-bit shufps.
8166   assert(Mask.size() == 4 && "Unsupported mask size!");
8167
8168   // To lower with a single SHUFPS we need to have the low half and high half
8169   // each requiring a single input.
8170   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8171     return false;
8172   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8173     return false;
8174
8175   return true;
8176 }
8177
8178 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8179 ///
8180 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8181 /// It makes no assumptions about whether this is the *best* lowering, it simply
8182 /// uses it.
8183 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8184                                             ArrayRef<int> Mask, SDValue V1,
8185                                             SDValue V2, SelectionDAG &DAG) {
8186   SDValue LowV = V1, HighV = V2;
8187   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8188
8189   int NumV2Elements =
8190       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8191
8192   if (NumV2Elements == 1) {
8193     int V2Index =
8194         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8195         Mask.begin();
8196
8197     // Compute the index adjacent to V2Index and in the same half by toggling
8198     // the low bit.
8199     int V2AdjIndex = V2Index ^ 1;
8200
8201     if (Mask[V2AdjIndex] == -1) {
8202       // Handles all the cases where we have a single V2 element and an undef.
8203       // This will only ever happen in the high lanes because we commute the
8204       // vector otherwise.
8205       if (V2Index < 2)
8206         std::swap(LowV, HighV);
8207       NewMask[V2Index] -= 4;
8208     } else {
8209       // Handle the case where the V2 element ends up adjacent to a V1 element.
8210       // To make this work, blend them together as the first step.
8211       int V1Index = V2AdjIndex;
8212       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8213       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8214                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8215
8216       // Now proceed to reconstruct the final blend as we have the necessary
8217       // high or low half formed.
8218       if (V2Index < 2) {
8219         LowV = V2;
8220         HighV = V1;
8221       } else {
8222         HighV = V2;
8223       }
8224       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8225       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8226     }
8227   } else if (NumV2Elements == 2) {
8228     if (Mask[0] < 4 && Mask[1] < 4) {
8229       // Handle the easy case where we have V1 in the low lanes and V2 in the
8230       // high lanes.
8231       NewMask[2] -= 4;
8232       NewMask[3] -= 4;
8233     } else if (Mask[2] < 4 && Mask[3] < 4) {
8234       // We also handle the reversed case because this utility may get called
8235       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8236       // arrange things in the right direction.
8237       NewMask[0] -= 4;
8238       NewMask[1] -= 4;
8239       HighV = V1;
8240       LowV = V2;
8241     } else {
8242       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8243       // trying to place elements directly, just blend them and set up the final
8244       // shuffle to place them.
8245
8246       // The first two blend mask elements are for V1, the second two are for
8247       // V2.
8248       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8249                           Mask[2] < 4 ? Mask[2] : Mask[3],
8250                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8251                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8252       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8253                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8254
8255       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8256       // a blend.
8257       LowV = HighV = V1;
8258       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8259       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8260       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8261       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8262     }
8263   }
8264   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8265                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8266 }
8267
8268 /// \brief Lower 4-lane 32-bit floating point shuffles.
8269 ///
8270 /// Uses instructions exclusively from the floating point unit to minimize
8271 /// domain crossing penalties, as these are sufficient to implement all v4f32
8272 /// shuffles.
8273 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8274                                        const X86Subtarget *Subtarget,
8275                                        SelectionDAG &DAG) {
8276   SDLoc DL(Op);
8277   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8278   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8279   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8280   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8281   ArrayRef<int> Mask = SVOp->getMask();
8282   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8283
8284   int NumV2Elements =
8285       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8286
8287   if (NumV2Elements == 0) {
8288     // Check for being able to broadcast a single element.
8289     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8290                                                           Mask, Subtarget, DAG))
8291       return Broadcast;
8292
8293     // Use even/odd duplicate instructions for masks that match their pattern.
8294     if (Subtarget->hasSSE3()) {
8295       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8296         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8297       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8298         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8299     }
8300
8301     if (Subtarget->hasAVX()) {
8302       // If we have AVX, we can use VPERMILPS which will allow folding a load
8303       // into the shuffle.
8304       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8305                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8306     }
8307
8308     // Otherwise, use a straight shuffle of a single input vector. We pass the
8309     // input vector to both operands to simulate this with a SHUFPS.
8310     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8311                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8312   }
8313
8314   // There are special ways we can lower some single-element blends. However, we
8315   // have custom ways we can lower more complex single-element blends below that
8316   // we defer to if both this and BLENDPS fail to match, so restrict this to
8317   // when the V2 input is targeting element 0 of the mask -- that is the fast
8318   // case here.
8319   if (NumV2Elements == 1 && Mask[0] >= 4)
8320     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8321                                                          Mask, Subtarget, DAG))
8322       return V;
8323
8324   if (Subtarget->hasSSE41()) {
8325     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8326                                                   Subtarget, DAG))
8327       return Blend;
8328
8329     // Use INSERTPS if we can complete the shuffle efficiently.
8330     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8331       return V;
8332
8333     if (!isSingleSHUFPSMask(Mask))
8334       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8335               DL, MVT::v4f32, V1, V2, Mask, DAG))
8336         return BlendPerm;
8337   }
8338
8339   // Use dedicated unpack instructions for masks that match their pattern.
8340   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8341     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8342   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8343     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8344   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8345     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8346   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8347     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8348
8349   // Otherwise fall back to a SHUFPS lowering strategy.
8350   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8351 }
8352
8353 /// \brief Lower 4-lane i32 vector shuffles.
8354 ///
8355 /// We try to handle these with integer-domain shuffles where we can, but for
8356 /// blends we use the floating point domain blend instructions.
8357 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8358                                        const X86Subtarget *Subtarget,
8359                                        SelectionDAG &DAG) {
8360   SDLoc DL(Op);
8361   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8362   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8363   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8364   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8365   ArrayRef<int> Mask = SVOp->getMask();
8366   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8367
8368   // Whenever we can lower this as a zext, that instruction is strictly faster
8369   // than any alternative. It also allows us to fold memory operands into the
8370   // shuffle in many cases.
8371   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8372                                                          Mask, Subtarget, DAG))
8373     return ZExt;
8374
8375   int NumV2Elements =
8376       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8377
8378   if (NumV2Elements == 0) {
8379     // Check for being able to broadcast a single element.
8380     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8381                                                           Mask, Subtarget, DAG))
8382       return Broadcast;
8383
8384     // Straight shuffle of a single input vector. For everything from SSE2
8385     // onward this has a single fast instruction with no scary immediates.
8386     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8387     // but we aren't actually going to use the UNPCK instruction because doing
8388     // so prevents folding a load into this instruction or making a copy.
8389     const int UnpackLoMask[] = {0, 0, 1, 1};
8390     const int UnpackHiMask[] = {2, 2, 3, 3};
8391     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8392       Mask = UnpackLoMask;
8393     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8394       Mask = UnpackHiMask;
8395
8396     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8397                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8398   }
8399
8400   // Try to use shift instructions.
8401   if (SDValue Shift =
8402           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8403     return Shift;
8404
8405   // There are special ways we can lower some single-element blends.
8406   if (NumV2Elements == 1)
8407     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8408                                                          Mask, Subtarget, DAG))
8409       return V;
8410
8411   // We have different paths for blend lowering, but they all must use the
8412   // *exact* same predicate.
8413   bool IsBlendSupported = Subtarget->hasSSE41();
8414   if (IsBlendSupported)
8415     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8416                                                   Subtarget, DAG))
8417       return Blend;
8418
8419   if (SDValue Masked =
8420           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8421     return Masked;
8422
8423   // Use dedicated unpack instructions for masks that match their pattern.
8424   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8425     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8426   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8427     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8428   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8429     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8430   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8431     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8432
8433   // Try to use byte rotation instructions.
8434   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8435   if (Subtarget->hasSSSE3())
8436     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8437             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8438       return Rotate;
8439
8440   // If we have direct support for blends, we should lower by decomposing into
8441   // a permute. That will be faster than the domain cross.
8442   if (IsBlendSupported)
8443     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8444                                                       Mask, DAG);
8445
8446   // Try to lower by permuting the inputs into an unpack instruction.
8447   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8448                                                             V2, Mask, DAG))
8449     return Unpack;
8450
8451   // We implement this with SHUFPS because it can blend from two vectors.
8452   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8453   // up the inputs, bypassing domain shift penalties that we would encur if we
8454   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8455   // relevant.
8456   return DAG.getBitcast(
8457       MVT::v4i32,
8458       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8459                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8460 }
8461
8462 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8463 /// shuffle lowering, and the most complex part.
8464 ///
8465 /// The lowering strategy is to try to form pairs of input lanes which are
8466 /// targeted at the same half of the final vector, and then use a dword shuffle
8467 /// to place them onto the right half, and finally unpack the paired lanes into
8468 /// their final position.
8469 ///
8470 /// The exact breakdown of how to form these dword pairs and align them on the
8471 /// correct sides is really tricky. See the comments within the function for
8472 /// more of the details.
8473 ///
8474 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8475 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8476 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8477 /// vector, form the analogous 128-bit 8-element Mask.
8478 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8479     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8480     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8481   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8482   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8483
8484   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8485   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8486   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8487
8488   SmallVector<int, 4> LoInputs;
8489   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8490                [](int M) { return M >= 0; });
8491   std::sort(LoInputs.begin(), LoInputs.end());
8492   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8493   SmallVector<int, 4> HiInputs;
8494   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8495                [](int M) { return M >= 0; });
8496   std::sort(HiInputs.begin(), HiInputs.end());
8497   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8498   int NumLToL =
8499       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8500   int NumHToL = LoInputs.size() - NumLToL;
8501   int NumLToH =
8502       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8503   int NumHToH = HiInputs.size() - NumLToH;
8504   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8505   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8506   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8507   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8508
8509   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8510   // such inputs we can swap two of the dwords across the half mark and end up
8511   // with <=2 inputs to each half in each half. Once there, we can fall through
8512   // to the generic code below. For example:
8513   //
8514   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8515   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8516   //
8517   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8518   // and an existing 2-into-2 on the other half. In this case we may have to
8519   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8520   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8521   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8522   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8523   // half than the one we target for fixing) will be fixed when we re-enter this
8524   // path. We will also combine away any sequence of PSHUFD instructions that
8525   // result into a single instruction. Here is an example of the tricky case:
8526   //
8527   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8528   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8529   //
8530   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8531   //
8532   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8533   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8534   //
8535   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8536   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8537   //
8538   // The result is fine to be handled by the generic logic.
8539   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8540                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8541                           int AOffset, int BOffset) {
8542     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8543            "Must call this with A having 3 or 1 inputs from the A half.");
8544     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8545            "Must call this with B having 1 or 3 inputs from the B half.");
8546     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8547            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8548
8549     bool ThreeAInputs = AToAInputs.size() == 3;
8550
8551     // Compute the index of dword with only one word among the three inputs in
8552     // a half by taking the sum of the half with three inputs and subtracting
8553     // the sum of the actual three inputs. The difference is the remaining
8554     // slot.
8555     int ADWord, BDWord;
8556     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8557     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8558     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8559     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8560     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8561     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8562     int TripleNonInputIdx =
8563         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8564     TripleDWord = TripleNonInputIdx / 2;
8565
8566     // We use xor with one to compute the adjacent DWord to whichever one the
8567     // OneInput is in.
8568     OneInputDWord = (OneInput / 2) ^ 1;
8569
8570     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8571     // and BToA inputs. If there is also such a problem with the BToB and AToB
8572     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8573     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8574     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8575     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8576       // Compute how many inputs will be flipped by swapping these DWords. We
8577       // need
8578       // to balance this to ensure we don't form a 3-1 shuffle in the other
8579       // half.
8580       int NumFlippedAToBInputs =
8581           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8582           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8583       int NumFlippedBToBInputs =
8584           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8585           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8586       if ((NumFlippedAToBInputs == 1 &&
8587            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8588           (NumFlippedBToBInputs == 1 &&
8589            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8590         // We choose whether to fix the A half or B half based on whether that
8591         // half has zero flipped inputs. At zero, we may not be able to fix it
8592         // with that half. We also bias towards fixing the B half because that
8593         // will more commonly be the high half, and we have to bias one way.
8594         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8595                                                        ArrayRef<int> Inputs) {
8596           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8597           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8598                                          PinnedIdx ^ 1) != Inputs.end();
8599           // Determine whether the free index is in the flipped dword or the
8600           // unflipped dword based on where the pinned index is. We use this bit
8601           // in an xor to conditionally select the adjacent dword.
8602           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8603           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8604                                              FixFreeIdx) != Inputs.end();
8605           if (IsFixIdxInput == IsFixFreeIdxInput)
8606             FixFreeIdx += 1;
8607           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8608                                         FixFreeIdx) != Inputs.end();
8609           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8610                  "We need to be changing the number of flipped inputs!");
8611           int PSHUFHalfMask[] = {0, 1, 2, 3};
8612           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8613           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8614                           MVT::v8i16, V,
8615                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8616
8617           for (int &M : Mask)
8618             if (M != -1 && M == FixIdx)
8619               M = FixFreeIdx;
8620             else if (M != -1 && M == FixFreeIdx)
8621               M = FixIdx;
8622         };
8623         if (NumFlippedBToBInputs != 0) {
8624           int BPinnedIdx =
8625               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8626           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8627         } else {
8628           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8629           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8630           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8631         }
8632       }
8633     }
8634
8635     int PSHUFDMask[] = {0, 1, 2, 3};
8636     PSHUFDMask[ADWord] = BDWord;
8637     PSHUFDMask[BDWord] = ADWord;
8638     V = DAG.getBitcast(
8639         VT,
8640         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8641                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8642
8643     // Adjust the mask to match the new locations of A and B.
8644     for (int &M : Mask)
8645       if (M != -1 && M/2 == ADWord)
8646         M = 2 * BDWord + M % 2;
8647       else if (M != -1 && M/2 == BDWord)
8648         M = 2 * ADWord + M % 2;
8649
8650     // Recurse back into this routine to re-compute state now that this isn't
8651     // a 3 and 1 problem.
8652     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8653                                                      DAG);
8654   };
8655   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8656     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8657   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8658     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8659
8660   // At this point there are at most two inputs to the low and high halves from
8661   // each half. That means the inputs can always be grouped into dwords and
8662   // those dwords can then be moved to the correct half with a dword shuffle.
8663   // We use at most one low and one high word shuffle to collect these paired
8664   // inputs into dwords, and finally a dword shuffle to place them.
8665   int PSHUFLMask[4] = {-1, -1, -1, -1};
8666   int PSHUFHMask[4] = {-1, -1, -1, -1};
8667   int PSHUFDMask[4] = {-1, -1, -1, -1};
8668
8669   // First fix the masks for all the inputs that are staying in their
8670   // original halves. This will then dictate the targets of the cross-half
8671   // shuffles.
8672   auto fixInPlaceInputs =
8673       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8674                     MutableArrayRef<int> SourceHalfMask,
8675                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8676     if (InPlaceInputs.empty())
8677       return;
8678     if (InPlaceInputs.size() == 1) {
8679       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8680           InPlaceInputs[0] - HalfOffset;
8681       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8682       return;
8683     }
8684     if (IncomingInputs.empty()) {
8685       // Just fix all of the in place inputs.
8686       for (int Input : InPlaceInputs) {
8687         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8688         PSHUFDMask[Input / 2] = Input / 2;
8689       }
8690       return;
8691     }
8692
8693     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8694     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8695         InPlaceInputs[0] - HalfOffset;
8696     // Put the second input next to the first so that they are packed into
8697     // a dword. We find the adjacent index by toggling the low bit.
8698     int AdjIndex = InPlaceInputs[0] ^ 1;
8699     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8700     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8701     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8702   };
8703   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8704   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8705
8706   // Now gather the cross-half inputs and place them into a free dword of
8707   // their target half.
8708   // FIXME: This operation could almost certainly be simplified dramatically to
8709   // look more like the 3-1 fixing operation.
8710   auto moveInputsToRightHalf = [&PSHUFDMask](
8711       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8712       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8713       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8714       int DestOffset) {
8715     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8716       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8717     };
8718     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8719                                                int Word) {
8720       int LowWord = Word & ~1;
8721       int HighWord = Word | 1;
8722       return isWordClobbered(SourceHalfMask, LowWord) ||
8723              isWordClobbered(SourceHalfMask, HighWord);
8724     };
8725
8726     if (IncomingInputs.empty())
8727       return;
8728
8729     if (ExistingInputs.empty()) {
8730       // Map any dwords with inputs from them into the right half.
8731       for (int Input : IncomingInputs) {
8732         // If the source half mask maps over the inputs, turn those into
8733         // swaps and use the swapped lane.
8734         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8735           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8736             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8737                 Input - SourceOffset;
8738             // We have to swap the uses in our half mask in one sweep.
8739             for (int &M : HalfMask)
8740               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8741                 M = Input;
8742               else if (M == Input)
8743                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8744           } else {
8745             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8746                        Input - SourceOffset &&
8747                    "Previous placement doesn't match!");
8748           }
8749           // Note that this correctly re-maps both when we do a swap and when
8750           // we observe the other side of the swap above. We rely on that to
8751           // avoid swapping the members of the input list directly.
8752           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8753         }
8754
8755         // Map the input's dword into the correct half.
8756         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8757           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8758         else
8759           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8760                      Input / 2 &&
8761                  "Previous placement doesn't match!");
8762       }
8763
8764       // And just directly shift any other-half mask elements to be same-half
8765       // as we will have mirrored the dword containing the element into the
8766       // same position within that half.
8767       for (int &M : HalfMask)
8768         if (M >= SourceOffset && M < SourceOffset + 4) {
8769           M = M - SourceOffset + DestOffset;
8770           assert(M >= 0 && "This should never wrap below zero!");
8771         }
8772       return;
8773     }
8774
8775     // Ensure we have the input in a viable dword of its current half. This
8776     // is particularly tricky because the original position may be clobbered
8777     // by inputs being moved and *staying* in that half.
8778     if (IncomingInputs.size() == 1) {
8779       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8780         int InputFixed = std::find(std::begin(SourceHalfMask),
8781                                    std::end(SourceHalfMask), -1) -
8782                          std::begin(SourceHalfMask) + SourceOffset;
8783         SourceHalfMask[InputFixed - SourceOffset] =
8784             IncomingInputs[0] - SourceOffset;
8785         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8786                      InputFixed);
8787         IncomingInputs[0] = InputFixed;
8788       }
8789     } else if (IncomingInputs.size() == 2) {
8790       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8791           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8792         // We have two non-adjacent or clobbered inputs we need to extract from
8793         // the source half. To do this, we need to map them into some adjacent
8794         // dword slot in the source mask.
8795         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8796                               IncomingInputs[1] - SourceOffset};
8797
8798         // If there is a free slot in the source half mask adjacent to one of
8799         // the inputs, place the other input in it. We use (Index XOR 1) to
8800         // compute an adjacent index.
8801         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8802             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8803           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8804           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8805           InputsFixed[1] = InputsFixed[0] ^ 1;
8806         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8807                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8808           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8809           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8810           InputsFixed[0] = InputsFixed[1] ^ 1;
8811         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8812                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8813           // The two inputs are in the same DWord but it is clobbered and the
8814           // adjacent DWord isn't used at all. Move both inputs to the free
8815           // slot.
8816           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8817           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8818           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8819           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8820         } else {
8821           // The only way we hit this point is if there is no clobbering
8822           // (because there are no off-half inputs to this half) and there is no
8823           // free slot adjacent to one of the inputs. In this case, we have to
8824           // swap an input with a non-input.
8825           for (int i = 0; i < 4; ++i)
8826             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8827                    "We can't handle any clobbers here!");
8828           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8829                  "Cannot have adjacent inputs here!");
8830
8831           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8832           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8833
8834           // We also have to update the final source mask in this case because
8835           // it may need to undo the above swap.
8836           for (int &M : FinalSourceHalfMask)
8837             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8838               M = InputsFixed[1] + SourceOffset;
8839             else if (M == InputsFixed[1] + SourceOffset)
8840               M = (InputsFixed[0] ^ 1) + SourceOffset;
8841
8842           InputsFixed[1] = InputsFixed[0] ^ 1;
8843         }
8844
8845         // Point everything at the fixed inputs.
8846         for (int &M : HalfMask)
8847           if (M == IncomingInputs[0])
8848             M = InputsFixed[0] + SourceOffset;
8849           else if (M == IncomingInputs[1])
8850             M = InputsFixed[1] + SourceOffset;
8851
8852         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8853         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8854       }
8855     } else {
8856       llvm_unreachable("Unhandled input size!");
8857     }
8858
8859     // Now hoist the DWord down to the right half.
8860     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8861     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8862     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8863     for (int &M : HalfMask)
8864       for (int Input : IncomingInputs)
8865         if (M == Input)
8866           M = FreeDWord * 2 + Input % 2;
8867   };
8868   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8869                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8870   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8871                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8872
8873   // Now enact all the shuffles we've computed to move the inputs into their
8874   // target half.
8875   if (!isNoopShuffleMask(PSHUFLMask))
8876     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8877                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8878   if (!isNoopShuffleMask(PSHUFHMask))
8879     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8880                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8881   if (!isNoopShuffleMask(PSHUFDMask))
8882     V = DAG.getBitcast(
8883         VT,
8884         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8885                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8886
8887   // At this point, each half should contain all its inputs, and we can then
8888   // just shuffle them into their final position.
8889   assert(std::count_if(LoMask.begin(), LoMask.end(),
8890                        [](int M) { return M >= 4; }) == 0 &&
8891          "Failed to lift all the high half inputs to the low mask!");
8892   assert(std::count_if(HiMask.begin(), HiMask.end(),
8893                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8894          "Failed to lift all the low half inputs to the high mask!");
8895
8896   // Do a half shuffle for the low mask.
8897   if (!isNoopShuffleMask(LoMask))
8898     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8899                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8900
8901   // Do a half shuffle with the high mask after shifting its values down.
8902   for (int &M : HiMask)
8903     if (M >= 0)
8904       M -= 4;
8905   if (!isNoopShuffleMask(HiMask))
8906     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8907                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8908
8909   return V;
8910 }
8911
8912 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8913 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8914                                           SDValue V2, ArrayRef<int> Mask,
8915                                           SelectionDAG &DAG, bool &V1InUse,
8916                                           bool &V2InUse) {
8917   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8918   SDValue V1Mask[16];
8919   SDValue V2Mask[16];
8920   V1InUse = false;
8921   V2InUse = false;
8922
8923   int Size = Mask.size();
8924   int Scale = 16 / Size;
8925   for (int i = 0; i < 16; ++i) {
8926     if (Mask[i / Scale] == -1) {
8927       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8928     } else {
8929       const int ZeroMask = 0x80;
8930       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8931                                           : ZeroMask;
8932       int V2Idx = Mask[i / Scale] < Size
8933                       ? ZeroMask
8934                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8935       if (Zeroable[i / Scale])
8936         V1Idx = V2Idx = ZeroMask;
8937       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8938       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8939       V1InUse |= (ZeroMask != V1Idx);
8940       V2InUse |= (ZeroMask != V2Idx);
8941     }
8942   }
8943
8944   if (V1InUse)
8945     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8946                      DAG.getBitcast(MVT::v16i8, V1),
8947                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8948   if (V2InUse)
8949     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8950                      DAG.getBitcast(MVT::v16i8, V2),
8951                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8952
8953   // If we need shuffled inputs from both, blend the two.
8954   SDValue V;
8955   if (V1InUse && V2InUse)
8956     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8957   else
8958     V = V1InUse ? V1 : V2;
8959
8960   // Cast the result back to the correct type.
8961   return DAG.getBitcast(VT, V);
8962 }
8963
8964 /// \brief Generic lowering of 8-lane i16 shuffles.
8965 ///
8966 /// This handles both single-input shuffles and combined shuffle/blends with
8967 /// two inputs. The single input shuffles are immediately delegated to
8968 /// a dedicated lowering routine.
8969 ///
8970 /// The blends are lowered in one of three fundamental ways. If there are few
8971 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8972 /// of the input is significantly cheaper when lowered as an interleaving of
8973 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8974 /// halves of the inputs separately (making them have relatively few inputs)
8975 /// and then concatenate them.
8976 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8977                                        const X86Subtarget *Subtarget,
8978                                        SelectionDAG &DAG) {
8979   SDLoc DL(Op);
8980   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8981   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8982   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8983   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8984   ArrayRef<int> OrigMask = SVOp->getMask();
8985   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8986                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8987   MutableArrayRef<int> Mask(MaskStorage);
8988
8989   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8990
8991   // Whenever we can lower this as a zext, that instruction is strictly faster
8992   // than any alternative.
8993   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8994           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8995     return ZExt;
8996
8997   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8998   (void)isV1;
8999   auto isV2 = [](int M) { return M >= 8; };
9000
9001   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9002
9003   if (NumV2Inputs == 0) {
9004     // Check for being able to broadcast a single element.
9005     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9006                                                           Mask, Subtarget, DAG))
9007       return Broadcast;
9008
9009     // Try to use shift instructions.
9010     if (SDValue Shift =
9011             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9012       return Shift;
9013
9014     // Use dedicated unpack instructions for masks that match their pattern.
9015     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
9016       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
9017     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
9018       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
9019
9020     // Try to use byte rotation instructions.
9021     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9022                                                         Mask, Subtarget, DAG))
9023       return Rotate;
9024
9025     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9026                                                      Subtarget, DAG);
9027   }
9028
9029   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9030          "All single-input shuffles should be canonicalized to be V1-input "
9031          "shuffles.");
9032
9033   // Try to use shift instructions.
9034   if (SDValue Shift =
9035           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9036     return Shift;
9037
9038   // See if we can use SSE4A Extraction / Insertion.
9039   if (Subtarget->hasSSE4A())
9040     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9041       return V;
9042
9043   // There are special ways we can lower some single-element blends.
9044   if (NumV2Inputs == 1)
9045     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9046                                                          Mask, Subtarget, DAG))
9047       return V;
9048
9049   // We have different paths for blend lowering, but they all must use the
9050   // *exact* same predicate.
9051   bool IsBlendSupported = Subtarget->hasSSE41();
9052   if (IsBlendSupported)
9053     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9054                                                   Subtarget, DAG))
9055       return Blend;
9056
9057   if (SDValue Masked =
9058           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9059     return Masked;
9060
9061   // Use dedicated unpack instructions for masks that match their pattern.
9062   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
9063     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9064   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
9065     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9066
9067   // Try to use byte rotation instructions.
9068   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9069           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9070     return Rotate;
9071
9072   if (SDValue BitBlend =
9073           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9074     return BitBlend;
9075
9076   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9077                                                             V2, Mask, DAG))
9078     return Unpack;
9079
9080   // If we can't directly blend but can use PSHUFB, that will be better as it
9081   // can both shuffle and set up the inefficient blend.
9082   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9083     bool V1InUse, V2InUse;
9084     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9085                                       V1InUse, V2InUse);
9086   }
9087
9088   // We can always bit-blend if we have to so the fallback strategy is to
9089   // decompose into single-input permutes and blends.
9090   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9091                                                       Mask, DAG);
9092 }
9093
9094 /// \brief Check whether a compaction lowering can be done by dropping even
9095 /// elements and compute how many times even elements must be dropped.
9096 ///
9097 /// This handles shuffles which take every Nth element where N is a power of
9098 /// two. Example shuffle masks:
9099 ///
9100 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9101 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9102 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9103 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9104 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9105 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9106 ///
9107 /// Any of these lanes can of course be undef.
9108 ///
9109 /// This routine only supports N <= 3.
9110 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9111 /// for larger N.
9112 ///
9113 /// \returns N above, or the number of times even elements must be dropped if
9114 /// there is such a number. Otherwise returns zero.
9115 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9116   // Figure out whether we're looping over two inputs or just one.
9117   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9118
9119   // The modulus for the shuffle vector entries is based on whether this is
9120   // a single input or not.
9121   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9122   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9123          "We should only be called with masks with a power-of-2 size!");
9124
9125   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9126
9127   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9128   // and 2^3 simultaneously. This is because we may have ambiguity with
9129   // partially undef inputs.
9130   bool ViableForN[3] = {true, true, true};
9131
9132   for (int i = 0, e = Mask.size(); i < e; ++i) {
9133     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9134     // want.
9135     if (Mask[i] == -1)
9136       continue;
9137
9138     bool IsAnyViable = false;
9139     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9140       if (ViableForN[j]) {
9141         uint64_t N = j + 1;
9142
9143         // The shuffle mask must be equal to (i * 2^N) % M.
9144         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9145           IsAnyViable = true;
9146         else
9147           ViableForN[j] = false;
9148       }
9149     // Early exit if we exhaust the possible powers of two.
9150     if (!IsAnyViable)
9151       break;
9152   }
9153
9154   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9155     if (ViableForN[j])
9156       return j + 1;
9157
9158   // Return 0 as there is no viable power of two.
9159   return 0;
9160 }
9161
9162 /// \brief Generic lowering of v16i8 shuffles.
9163 ///
9164 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9165 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9166 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9167 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9168 /// back together.
9169 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9170                                        const X86Subtarget *Subtarget,
9171                                        SelectionDAG &DAG) {
9172   SDLoc DL(Op);
9173   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9174   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9175   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9176   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9177   ArrayRef<int> Mask = SVOp->getMask();
9178   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9179
9180   // Try to use shift instructions.
9181   if (SDValue Shift =
9182           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9183     return Shift;
9184
9185   // Try to use byte rotation instructions.
9186   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9187           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9188     return Rotate;
9189
9190   // Try to use a zext lowering.
9191   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9192           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9193     return ZExt;
9194
9195   // See if we can use SSE4A Extraction / Insertion.
9196   if (Subtarget->hasSSE4A())
9197     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9198       return V;
9199
9200   int NumV2Elements =
9201       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9202
9203   // For single-input shuffles, there are some nicer lowering tricks we can use.
9204   if (NumV2Elements == 0) {
9205     // Check for being able to broadcast a single element.
9206     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9207                                                           Mask, Subtarget, DAG))
9208       return Broadcast;
9209
9210     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9211     // Notably, this handles splat and partial-splat shuffles more efficiently.
9212     // However, it only makes sense if the pre-duplication shuffle simplifies
9213     // things significantly. Currently, this means we need to be able to
9214     // express the pre-duplication shuffle as an i16 shuffle.
9215     //
9216     // FIXME: We should check for other patterns which can be widened into an
9217     // i16 shuffle as well.
9218     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9219       for (int i = 0; i < 16; i += 2)
9220         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9221           return false;
9222
9223       return true;
9224     };
9225     auto tryToWidenViaDuplication = [&]() -> SDValue {
9226       if (!canWidenViaDuplication(Mask))
9227         return SDValue();
9228       SmallVector<int, 4> LoInputs;
9229       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9230                    [](int M) { return M >= 0 && M < 8; });
9231       std::sort(LoInputs.begin(), LoInputs.end());
9232       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9233                      LoInputs.end());
9234       SmallVector<int, 4> HiInputs;
9235       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9236                    [](int M) { return M >= 8; });
9237       std::sort(HiInputs.begin(), HiInputs.end());
9238       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9239                      HiInputs.end());
9240
9241       bool TargetLo = LoInputs.size() >= HiInputs.size();
9242       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9243       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9244
9245       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9246       SmallDenseMap<int, int, 8> LaneMap;
9247       for (int I : InPlaceInputs) {
9248         PreDupI16Shuffle[I/2] = I/2;
9249         LaneMap[I] = I;
9250       }
9251       int j = TargetLo ? 0 : 4, je = j + 4;
9252       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9253         // Check if j is already a shuffle of this input. This happens when
9254         // there are two adjacent bytes after we move the low one.
9255         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9256           // If we haven't yet mapped the input, search for a slot into which
9257           // we can map it.
9258           while (j < je && PreDupI16Shuffle[j] != -1)
9259             ++j;
9260
9261           if (j == je)
9262             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9263             return SDValue();
9264
9265           // Map this input with the i16 shuffle.
9266           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9267         }
9268
9269         // Update the lane map based on the mapping we ended up with.
9270         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9271       }
9272       V1 = DAG.getBitcast(
9273           MVT::v16i8,
9274           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9275                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9276
9277       // Unpack the bytes to form the i16s that will be shuffled into place.
9278       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9279                        MVT::v16i8, V1, V1);
9280
9281       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9282       for (int i = 0; i < 16; ++i)
9283         if (Mask[i] != -1) {
9284           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9285           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9286           if (PostDupI16Shuffle[i / 2] == -1)
9287             PostDupI16Shuffle[i / 2] = MappedMask;
9288           else
9289             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9290                    "Conflicting entrties in the original shuffle!");
9291         }
9292       return DAG.getBitcast(
9293           MVT::v16i8,
9294           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9295                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9296     };
9297     if (SDValue V = tryToWidenViaDuplication())
9298       return V;
9299   }
9300
9301   if (SDValue Masked =
9302           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9303     return Masked;
9304
9305   // Use dedicated unpack instructions for masks that match their pattern.
9306   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9307                                          0, 16, 1, 17, 2, 18, 3, 19,
9308                                          // High half.
9309                                          4, 20, 5, 21, 6, 22, 7, 23}))
9310     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9311   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9312                                          8, 24, 9, 25, 10, 26, 11, 27,
9313                                          // High half.
9314                                          12, 28, 13, 29, 14, 30, 15, 31}))
9315     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9316
9317   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9318   // with PSHUFB. It is important to do this before we attempt to generate any
9319   // blends but after all of the single-input lowerings. If the single input
9320   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9321   // want to preserve that and we can DAG combine any longer sequences into
9322   // a PSHUFB in the end. But once we start blending from multiple inputs,
9323   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9324   // and there are *very* few patterns that would actually be faster than the
9325   // PSHUFB approach because of its ability to zero lanes.
9326   //
9327   // FIXME: The only exceptions to the above are blends which are exact
9328   // interleavings with direct instructions supporting them. We currently don't
9329   // handle those well here.
9330   if (Subtarget->hasSSSE3()) {
9331     bool V1InUse = false;
9332     bool V2InUse = false;
9333
9334     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9335                                                 DAG, V1InUse, V2InUse);
9336
9337     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9338     // do so. This avoids using them to handle blends-with-zero which is
9339     // important as a single pshufb is significantly faster for that.
9340     if (V1InUse && V2InUse) {
9341       if (Subtarget->hasSSE41())
9342         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9343                                                       Mask, Subtarget, DAG))
9344           return Blend;
9345
9346       // We can use an unpack to do the blending rather than an or in some
9347       // cases. Even though the or may be (very minorly) more efficient, we
9348       // preference this lowering because there are common cases where part of
9349       // the complexity of the shuffles goes away when we do the final blend as
9350       // an unpack.
9351       // FIXME: It might be worth trying to detect if the unpack-feeding
9352       // shuffles will both be pshufb, in which case we shouldn't bother with
9353       // this.
9354       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9355               DL, MVT::v16i8, V1, V2, Mask, DAG))
9356         return Unpack;
9357     }
9358
9359     return PSHUFB;
9360   }
9361
9362   // There are special ways we can lower some single-element blends.
9363   if (NumV2Elements == 1)
9364     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9365                                                          Mask, Subtarget, DAG))
9366       return V;
9367
9368   if (SDValue BitBlend =
9369           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9370     return BitBlend;
9371
9372   // Check whether a compaction lowering can be done. This handles shuffles
9373   // which take every Nth element for some even N. See the helper function for
9374   // details.
9375   //
9376   // We special case these as they can be particularly efficiently handled with
9377   // the PACKUSB instruction on x86 and they show up in common patterns of
9378   // rearranging bytes to truncate wide elements.
9379   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9380     // NumEvenDrops is the power of two stride of the elements. Another way of
9381     // thinking about it is that we need to drop the even elements this many
9382     // times to get the original input.
9383     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9384
9385     // First we need to zero all the dropped bytes.
9386     assert(NumEvenDrops <= 3 &&
9387            "No support for dropping even elements more than 3 times.");
9388     // We use the mask type to pick which bytes are preserved based on how many
9389     // elements are dropped.
9390     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9391     SDValue ByteClearMask = DAG.getBitcast(
9392         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9393     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9394     if (!IsSingleInput)
9395       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9396
9397     // Now pack things back together.
9398     V1 = DAG.getBitcast(MVT::v8i16, V1);
9399     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9400     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9401     for (int i = 1; i < NumEvenDrops; ++i) {
9402       Result = DAG.getBitcast(MVT::v8i16, Result);
9403       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9404     }
9405
9406     return Result;
9407   }
9408
9409   // Handle multi-input cases by blending single-input shuffles.
9410   if (NumV2Elements > 0)
9411     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9412                                                       Mask, DAG);
9413
9414   // The fallback path for single-input shuffles widens this into two v8i16
9415   // vectors with unpacks, shuffles those, and then pulls them back together
9416   // with a pack.
9417   SDValue V = V1;
9418
9419   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9420   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9421   for (int i = 0; i < 16; ++i)
9422     if (Mask[i] >= 0)
9423       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9424
9425   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9426
9427   SDValue VLoHalf, VHiHalf;
9428   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9429   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9430   // i16s.
9431   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9432                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9433       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9434                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9435     // Use a mask to drop the high bytes.
9436     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9437     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9438                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9439
9440     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9441     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9442
9443     // Squash the masks to point directly into VLoHalf.
9444     for (int &M : LoBlendMask)
9445       if (M >= 0)
9446         M /= 2;
9447     for (int &M : HiBlendMask)
9448       if (M >= 0)
9449         M /= 2;
9450   } else {
9451     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9452     // VHiHalf so that we can blend them as i16s.
9453     VLoHalf = DAG.getBitcast(
9454         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9455     VHiHalf = DAG.getBitcast(
9456         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9457   }
9458
9459   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9460   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9461
9462   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9463 }
9464
9465 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9466 ///
9467 /// This routine breaks down the specific type of 128-bit shuffle and
9468 /// dispatches to the lowering routines accordingly.
9469 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9470                                         MVT VT, const X86Subtarget *Subtarget,
9471                                         SelectionDAG &DAG) {
9472   switch (VT.SimpleTy) {
9473   case MVT::v2i64:
9474     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9475   case MVT::v2f64:
9476     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9477   case MVT::v4i32:
9478     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9479   case MVT::v4f32:
9480     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9481   case MVT::v8i16:
9482     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9483   case MVT::v16i8:
9484     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9485
9486   default:
9487     llvm_unreachable("Unimplemented!");
9488   }
9489 }
9490
9491 /// \brief Helper function to test whether a shuffle mask could be
9492 /// simplified by widening the elements being shuffled.
9493 ///
9494 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9495 /// leaves it in an unspecified state.
9496 ///
9497 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9498 /// shuffle masks. The latter have the special property of a '-2' representing
9499 /// a zero-ed lane of a vector.
9500 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9501                                     SmallVectorImpl<int> &WidenedMask) {
9502   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9503     // If both elements are undef, its trivial.
9504     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9505       WidenedMask.push_back(SM_SentinelUndef);
9506       continue;
9507     }
9508
9509     // Check for an undef mask and a mask value properly aligned to fit with
9510     // a pair of values. If we find such a case, use the non-undef mask's value.
9511     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9512       WidenedMask.push_back(Mask[i + 1] / 2);
9513       continue;
9514     }
9515     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9516       WidenedMask.push_back(Mask[i] / 2);
9517       continue;
9518     }
9519
9520     // When zeroing, we need to spread the zeroing across both lanes to widen.
9521     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9522       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9523           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9524         WidenedMask.push_back(SM_SentinelZero);
9525         continue;
9526       }
9527       return false;
9528     }
9529
9530     // Finally check if the two mask values are adjacent and aligned with
9531     // a pair.
9532     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9533       WidenedMask.push_back(Mask[i] / 2);
9534       continue;
9535     }
9536
9537     // Otherwise we can't safely widen the elements used in this shuffle.
9538     return false;
9539   }
9540   assert(WidenedMask.size() == Mask.size() / 2 &&
9541          "Incorrect size of mask after widening the elements!");
9542
9543   return true;
9544 }
9545
9546 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9547 ///
9548 /// This routine just extracts two subvectors, shuffles them independently, and
9549 /// then concatenates them back together. This should work effectively with all
9550 /// AVX vector shuffle types.
9551 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9552                                           SDValue V2, ArrayRef<int> Mask,
9553                                           SelectionDAG &DAG) {
9554   assert(VT.getSizeInBits() >= 256 &&
9555          "Only for 256-bit or wider vector shuffles!");
9556   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9557   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9558
9559   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9560   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9561
9562   int NumElements = VT.getVectorNumElements();
9563   int SplitNumElements = NumElements / 2;
9564   MVT ScalarVT = VT.getScalarType();
9565   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9566
9567   // Rather than splitting build-vectors, just build two narrower build
9568   // vectors. This helps shuffling with splats and zeros.
9569   auto SplitVector = [&](SDValue V) {
9570     while (V.getOpcode() == ISD::BITCAST)
9571       V = V->getOperand(0);
9572
9573     MVT OrigVT = V.getSimpleValueType();
9574     int OrigNumElements = OrigVT.getVectorNumElements();
9575     int OrigSplitNumElements = OrigNumElements / 2;
9576     MVT OrigScalarVT = OrigVT.getScalarType();
9577     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9578
9579     SDValue LoV, HiV;
9580
9581     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9582     if (!BV) {
9583       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9584                         DAG.getIntPtrConstant(0, DL));
9585       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9586                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9587     } else {
9588
9589       SmallVector<SDValue, 16> LoOps, HiOps;
9590       for (int i = 0; i < OrigSplitNumElements; ++i) {
9591         LoOps.push_back(BV->getOperand(i));
9592         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9593       }
9594       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9595       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9596     }
9597     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9598                           DAG.getBitcast(SplitVT, HiV));
9599   };
9600
9601   SDValue LoV1, HiV1, LoV2, HiV2;
9602   std::tie(LoV1, HiV1) = SplitVector(V1);
9603   std::tie(LoV2, HiV2) = SplitVector(V2);
9604
9605   // Now create two 4-way blends of these half-width vectors.
9606   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9607     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9608     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9609     for (int i = 0; i < SplitNumElements; ++i) {
9610       int M = HalfMask[i];
9611       if (M >= NumElements) {
9612         if (M >= NumElements + SplitNumElements)
9613           UseHiV2 = true;
9614         else
9615           UseLoV2 = true;
9616         V2BlendMask.push_back(M - NumElements);
9617         V1BlendMask.push_back(-1);
9618         BlendMask.push_back(SplitNumElements + i);
9619       } else if (M >= 0) {
9620         if (M >= SplitNumElements)
9621           UseHiV1 = true;
9622         else
9623           UseLoV1 = true;
9624         V2BlendMask.push_back(-1);
9625         V1BlendMask.push_back(M);
9626         BlendMask.push_back(i);
9627       } else {
9628         V2BlendMask.push_back(-1);
9629         V1BlendMask.push_back(-1);
9630         BlendMask.push_back(-1);
9631       }
9632     }
9633
9634     // Because the lowering happens after all combining takes place, we need to
9635     // manually combine these blend masks as much as possible so that we create
9636     // a minimal number of high-level vector shuffle nodes.
9637
9638     // First try just blending the halves of V1 or V2.
9639     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9640       return DAG.getUNDEF(SplitVT);
9641     if (!UseLoV2 && !UseHiV2)
9642       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9643     if (!UseLoV1 && !UseHiV1)
9644       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9645
9646     SDValue V1Blend, V2Blend;
9647     if (UseLoV1 && UseHiV1) {
9648       V1Blend =
9649         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9650     } else {
9651       // We only use half of V1 so map the usage down into the final blend mask.
9652       V1Blend = UseLoV1 ? LoV1 : HiV1;
9653       for (int i = 0; i < SplitNumElements; ++i)
9654         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9655           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9656     }
9657     if (UseLoV2 && UseHiV2) {
9658       V2Blend =
9659         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9660     } else {
9661       // We only use half of V2 so map the usage down into the final blend mask.
9662       V2Blend = UseLoV2 ? LoV2 : HiV2;
9663       for (int i = 0; i < SplitNumElements; ++i)
9664         if (BlendMask[i] >= SplitNumElements)
9665           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9666     }
9667     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9668   };
9669   SDValue Lo = HalfBlend(LoMask);
9670   SDValue Hi = HalfBlend(HiMask);
9671   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9672 }
9673
9674 /// \brief Either split a vector in halves or decompose the shuffles and the
9675 /// blend.
9676 ///
9677 /// This is provided as a good fallback for many lowerings of non-single-input
9678 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9679 /// between splitting the shuffle into 128-bit components and stitching those
9680 /// back together vs. extracting the single-input shuffles and blending those
9681 /// results.
9682 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9683                                                 SDValue V2, ArrayRef<int> Mask,
9684                                                 SelectionDAG &DAG) {
9685   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9686                                             "lower single-input shuffles as it "
9687                                             "could then recurse on itself.");
9688   int Size = Mask.size();
9689
9690   // If this can be modeled as a broadcast of two elements followed by a blend,
9691   // prefer that lowering. This is especially important because broadcasts can
9692   // often fold with memory operands.
9693   auto DoBothBroadcast = [&] {
9694     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9695     for (int M : Mask)
9696       if (M >= Size) {
9697         if (V2BroadcastIdx == -1)
9698           V2BroadcastIdx = M - Size;
9699         else if (M - Size != V2BroadcastIdx)
9700           return false;
9701       } else if (M >= 0) {
9702         if (V1BroadcastIdx == -1)
9703           V1BroadcastIdx = M;
9704         else if (M != V1BroadcastIdx)
9705           return false;
9706       }
9707     return true;
9708   };
9709   if (DoBothBroadcast())
9710     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9711                                                       DAG);
9712
9713   // If the inputs all stem from a single 128-bit lane of each input, then we
9714   // split them rather than blending because the split will decompose to
9715   // unusually few instructions.
9716   int LaneCount = VT.getSizeInBits() / 128;
9717   int LaneSize = Size / LaneCount;
9718   SmallBitVector LaneInputs[2];
9719   LaneInputs[0].resize(LaneCount, false);
9720   LaneInputs[1].resize(LaneCount, false);
9721   for (int i = 0; i < Size; ++i)
9722     if (Mask[i] >= 0)
9723       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9724   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9725     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9726
9727   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9728   // that the decomposed single-input shuffles don't end up here.
9729   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9730 }
9731
9732 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9733 /// a permutation and blend of those lanes.
9734 ///
9735 /// This essentially blends the out-of-lane inputs to each lane into the lane
9736 /// from a permuted copy of the vector. This lowering strategy results in four
9737 /// instructions in the worst case for a single-input cross lane shuffle which
9738 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9739 /// of. Special cases for each particular shuffle pattern should be handled
9740 /// prior to trying this lowering.
9741 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9742                                                        SDValue V1, SDValue V2,
9743                                                        ArrayRef<int> Mask,
9744                                                        SelectionDAG &DAG) {
9745   // FIXME: This should probably be generalized for 512-bit vectors as well.
9746   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9747   int LaneSize = Mask.size() / 2;
9748
9749   // If there are only inputs from one 128-bit lane, splitting will in fact be
9750   // less expensive. The flags track whether the given lane contains an element
9751   // that crosses to another lane.
9752   bool LaneCrossing[2] = {false, false};
9753   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9754     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9755       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9756   if (!LaneCrossing[0] || !LaneCrossing[1])
9757     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9758
9759   if (isSingleInputShuffleMask(Mask)) {
9760     SmallVector<int, 32> FlippedBlendMask;
9761     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9762       FlippedBlendMask.push_back(
9763           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9764                                   ? Mask[i]
9765                                   : Mask[i] % LaneSize +
9766                                         (i / LaneSize) * LaneSize + Size));
9767
9768     // Flip the vector, and blend the results which should now be in-lane. The
9769     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9770     // 5 for the high source. The value 3 selects the high half of source 2 and
9771     // the value 2 selects the low half of source 2. We only use source 2 to
9772     // allow folding it into a memory operand.
9773     unsigned PERMMask = 3 | 2 << 4;
9774     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9775                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9776     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9777   }
9778
9779   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9780   // will be handled by the above logic and a blend of the results, much like
9781   // other patterns in AVX.
9782   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9783 }
9784
9785 /// \brief Handle lowering 2-lane 128-bit shuffles.
9786 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9787                                         SDValue V2, ArrayRef<int> Mask,
9788                                         const X86Subtarget *Subtarget,
9789                                         SelectionDAG &DAG) {
9790   // TODO: If minimizing size and one of the inputs is a zero vector and the
9791   // the zero vector has only one use, we could use a VPERM2X128 to save the
9792   // instruction bytes needed to explicitly generate the zero vector.
9793
9794   // Blends are faster and handle all the non-lane-crossing cases.
9795   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9796                                                 Subtarget, DAG))
9797     return Blend;
9798
9799   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9800   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9801
9802   // If either input operand is a zero vector, use VPERM2X128 because its mask
9803   // allows us to replace the zero input with an implicit zero.
9804   if (!IsV1Zero && !IsV2Zero) {
9805     // Check for patterns which can be matched with a single insert of a 128-bit
9806     // subvector.
9807     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9808     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9809       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9810                                    VT.getVectorNumElements() / 2);
9811       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9812                                 DAG.getIntPtrConstant(0, DL));
9813       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9814                                 OnlyUsesV1 ? V1 : V2,
9815                                 DAG.getIntPtrConstant(0, DL));
9816       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9817     }
9818   }
9819
9820   // Otherwise form a 128-bit permutation. After accounting for undefs,
9821   // convert the 64-bit shuffle mask selection values into 128-bit
9822   // selection bits by dividing the indexes by 2 and shifting into positions
9823   // defined by a vperm2*128 instruction's immediate control byte.
9824
9825   // The immediate permute control byte looks like this:
9826   //    [1:0] - select 128 bits from sources for low half of destination
9827   //    [2]   - ignore
9828   //    [3]   - zero low half of destination
9829   //    [5:4] - select 128 bits from sources for high half of destination
9830   //    [6]   - ignore
9831   //    [7]   - zero high half of destination
9832
9833   int MaskLO = Mask[0];
9834   if (MaskLO == SM_SentinelUndef)
9835     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9836
9837   int MaskHI = Mask[2];
9838   if (MaskHI == SM_SentinelUndef)
9839     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9840
9841   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9842
9843   // If either input is a zero vector, replace it with an undef input.
9844   // Shuffle mask values <  4 are selecting elements of V1.
9845   // Shuffle mask values >= 4 are selecting elements of V2.
9846   // Adjust each half of the permute mask by clearing the half that was
9847   // selecting the zero vector and setting the zero mask bit.
9848   if (IsV1Zero) {
9849     V1 = DAG.getUNDEF(VT);
9850     if (MaskLO < 4)
9851       PermMask = (PermMask & 0xf0) | 0x08;
9852     if (MaskHI < 4)
9853       PermMask = (PermMask & 0x0f) | 0x80;
9854   }
9855   if (IsV2Zero) {
9856     V2 = DAG.getUNDEF(VT);
9857     if (MaskLO >= 4)
9858       PermMask = (PermMask & 0xf0) | 0x08;
9859     if (MaskHI >= 4)
9860       PermMask = (PermMask & 0x0f) | 0x80;
9861   }
9862
9863   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9864                      DAG.getConstant(PermMask, DL, MVT::i8));
9865 }
9866
9867 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9868 /// shuffling each lane.
9869 ///
9870 /// This will only succeed when the result of fixing the 128-bit lanes results
9871 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9872 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9873 /// the lane crosses early and then use simpler shuffles within each lane.
9874 ///
9875 /// FIXME: It might be worthwhile at some point to support this without
9876 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9877 /// in x86 only floating point has interesting non-repeating shuffles, and even
9878 /// those are still *marginally* more expensive.
9879 static SDValue lowerVectorShuffleByMerging128BitLanes(
9880     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9881     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9882   assert(!isSingleInputShuffleMask(Mask) &&
9883          "This is only useful with multiple inputs.");
9884
9885   int Size = Mask.size();
9886   int LaneSize = 128 / VT.getScalarSizeInBits();
9887   int NumLanes = Size / LaneSize;
9888   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9889
9890   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9891   // check whether the in-128-bit lane shuffles share a repeating pattern.
9892   SmallVector<int, 4> Lanes;
9893   Lanes.resize(NumLanes, -1);
9894   SmallVector<int, 4> InLaneMask;
9895   InLaneMask.resize(LaneSize, -1);
9896   for (int i = 0; i < Size; ++i) {
9897     if (Mask[i] < 0)
9898       continue;
9899
9900     int j = i / LaneSize;
9901
9902     if (Lanes[j] < 0) {
9903       // First entry we've seen for this lane.
9904       Lanes[j] = Mask[i] / LaneSize;
9905     } else if (Lanes[j] != Mask[i] / LaneSize) {
9906       // This doesn't match the lane selected previously!
9907       return SDValue();
9908     }
9909
9910     // Check that within each lane we have a consistent shuffle mask.
9911     int k = i % LaneSize;
9912     if (InLaneMask[k] < 0) {
9913       InLaneMask[k] = Mask[i] % LaneSize;
9914     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9915       // This doesn't fit a repeating in-lane mask.
9916       return SDValue();
9917     }
9918   }
9919
9920   // First shuffle the lanes into place.
9921   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9922                                 VT.getSizeInBits() / 64);
9923   SmallVector<int, 8> LaneMask;
9924   LaneMask.resize(NumLanes * 2, -1);
9925   for (int i = 0; i < NumLanes; ++i)
9926     if (Lanes[i] >= 0) {
9927       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9928       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9929     }
9930
9931   V1 = DAG.getBitcast(LaneVT, V1);
9932   V2 = DAG.getBitcast(LaneVT, V2);
9933   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9934
9935   // Cast it back to the type we actually want.
9936   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9937
9938   // Now do a simple shuffle that isn't lane crossing.
9939   SmallVector<int, 8> NewMask;
9940   NewMask.resize(Size, -1);
9941   for (int i = 0; i < Size; ++i)
9942     if (Mask[i] >= 0)
9943       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9944   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9945          "Must not introduce lane crosses at this point!");
9946
9947   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9948 }
9949
9950 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9951 /// given mask.
9952 ///
9953 /// This returns true if the elements from a particular input are already in the
9954 /// slot required by the given mask and require no permutation.
9955 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9956   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9957   int Size = Mask.size();
9958   for (int i = 0; i < Size; ++i)
9959     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9960       return false;
9961
9962   return true;
9963 }
9964
9965 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9966                                             ArrayRef<int> Mask, SDValue V1,
9967                                             SDValue V2, SelectionDAG &DAG) {
9968
9969   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9970   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9971   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9972   int NumElts = VT.getVectorNumElements();
9973   bool ShufpdMask = true;
9974   bool CommutableMask = true;
9975   unsigned Immediate = 0;
9976   for (int i = 0; i < NumElts; ++i) {
9977     if (Mask[i] < 0)
9978       continue;
9979     int Val = (i & 6) + NumElts * (i & 1);
9980     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9981     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9982       ShufpdMask = false;
9983     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9984       CommutableMask = false;
9985     Immediate |= (Mask[i] % 2) << i;
9986   }
9987   if (ShufpdMask)
9988     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9989                        DAG.getConstant(Immediate, DL, MVT::i8));
9990   if (CommutableMask)
9991     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9992                        DAG.getConstant(Immediate, DL, MVT::i8));
9993   return SDValue();
9994 }
9995
9996 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9997 ///
9998 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9999 /// isn't available.
10000 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10001                                        const X86Subtarget *Subtarget,
10002                                        SelectionDAG &DAG) {
10003   SDLoc DL(Op);
10004   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10005   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10006   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10007   ArrayRef<int> Mask = SVOp->getMask();
10008   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10009
10010   SmallVector<int, 4> WidenedMask;
10011   if (canWidenShuffleElements(Mask, WidenedMask))
10012     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10013                                     DAG);
10014
10015   if (isSingleInputShuffleMask(Mask)) {
10016     // Check for being able to broadcast a single element.
10017     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10018                                                           Mask, Subtarget, DAG))
10019       return Broadcast;
10020
10021     // Use low duplicate instructions for masks that match their pattern.
10022     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10023       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10024
10025     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10026       // Non-half-crossing single input shuffles can be lowerid with an
10027       // interleaved permutation.
10028       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10029                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10030       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10031                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10032     }
10033
10034     // With AVX2 we have direct support for this permutation.
10035     if (Subtarget->hasAVX2())
10036       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10037                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10038
10039     // Otherwise, fall back.
10040     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10041                                                    DAG);
10042   }
10043
10044   // X86 has dedicated unpack instructions that can handle specific blend
10045   // operations: UNPCKH and UNPCKL.
10046   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10047     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10048   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10049     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10050   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10051     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
10052   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10053     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
10054
10055   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10056                                                 Subtarget, DAG))
10057     return Blend;
10058
10059   // Check if the blend happens to exactly fit that of SHUFPD.
10060   if (SDValue Op =
10061       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10062     return Op;
10063
10064   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10065   // shuffle. However, if we have AVX2 and either inputs are already in place,
10066   // we will be able to shuffle even across lanes the other input in a single
10067   // instruction so skip this pattern.
10068   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10069                                  isShuffleMaskInputInPlace(1, Mask))))
10070     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10071             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10072       return Result;
10073
10074   // If we have AVX2 then we always want to lower with a blend because an v4 we
10075   // can fully permute the elements.
10076   if (Subtarget->hasAVX2())
10077     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10078                                                       Mask, DAG);
10079
10080   // Otherwise fall back on generic lowering.
10081   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10082 }
10083
10084 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10085 ///
10086 /// This routine is only called when we have AVX2 and thus a reasonable
10087 /// instruction set for v4i64 shuffling..
10088 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10089                                        const X86Subtarget *Subtarget,
10090                                        SelectionDAG &DAG) {
10091   SDLoc DL(Op);
10092   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10093   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10094   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10095   ArrayRef<int> Mask = SVOp->getMask();
10096   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10097   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10098
10099   SmallVector<int, 4> WidenedMask;
10100   if (canWidenShuffleElements(Mask, WidenedMask))
10101     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10102                                     DAG);
10103
10104   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10105                                                 Subtarget, DAG))
10106     return Blend;
10107
10108   // Check for being able to broadcast a single element.
10109   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10110                                                         Mask, Subtarget, DAG))
10111     return Broadcast;
10112
10113   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10114   // use lower latency instructions that will operate on both 128-bit lanes.
10115   SmallVector<int, 2> RepeatedMask;
10116   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10117     if (isSingleInputShuffleMask(Mask)) {
10118       int PSHUFDMask[] = {-1, -1, -1, -1};
10119       for (int i = 0; i < 2; ++i)
10120         if (RepeatedMask[i] >= 0) {
10121           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10122           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10123         }
10124       return DAG.getBitcast(
10125           MVT::v4i64,
10126           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10127                       DAG.getBitcast(MVT::v8i32, V1),
10128                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10129     }
10130   }
10131
10132   // AVX2 provides a direct instruction for permuting a single input across
10133   // lanes.
10134   if (isSingleInputShuffleMask(Mask))
10135     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10136                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10137
10138   // Try to use shift instructions.
10139   if (SDValue Shift =
10140           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10141     return Shift;
10142
10143   // Use dedicated unpack instructions for masks that match their pattern.
10144   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10145     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10146   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10147     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10148   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10149     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
10150   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10151     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
10152
10153   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10154   // shuffle. However, if we have AVX2 and either inputs are already in place,
10155   // we will be able to shuffle even across lanes the other input in a single
10156   // instruction so skip this pattern.
10157   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10158                                  isShuffleMaskInputInPlace(1, Mask))))
10159     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10160             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10161       return Result;
10162
10163   // Otherwise fall back on generic blend lowering.
10164   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10165                                                     Mask, DAG);
10166 }
10167
10168 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10169 ///
10170 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10171 /// isn't available.
10172 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10173                                        const X86Subtarget *Subtarget,
10174                                        SelectionDAG &DAG) {
10175   SDLoc DL(Op);
10176   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10177   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10178   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10179   ArrayRef<int> Mask = SVOp->getMask();
10180   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10181
10182   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10183                                                 Subtarget, DAG))
10184     return Blend;
10185
10186   // Check for being able to broadcast a single element.
10187   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10188                                                         Mask, Subtarget, DAG))
10189     return Broadcast;
10190
10191   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10192   // options to efficiently lower the shuffle.
10193   SmallVector<int, 4> RepeatedMask;
10194   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10195     assert(RepeatedMask.size() == 4 &&
10196            "Repeated masks must be half the mask width!");
10197
10198     // Use even/odd duplicate instructions for masks that match their pattern.
10199     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10200       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10201     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10202       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10203
10204     if (isSingleInputShuffleMask(Mask))
10205       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10206                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10207
10208     // Use dedicated unpack instructions for masks that match their pattern.
10209     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10210       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10211     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10212       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10213     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10214       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10215     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10216       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10217
10218     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10219     // have already handled any direct blends. We also need to squash the
10220     // repeated mask into a simulated v4f32 mask.
10221     for (int i = 0; i < 4; ++i)
10222       if (RepeatedMask[i] >= 8)
10223         RepeatedMask[i] -= 4;
10224     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10225   }
10226
10227   // If we have a single input shuffle with different shuffle patterns in the
10228   // two 128-bit lanes use the variable mask to VPERMILPS.
10229   if (isSingleInputShuffleMask(Mask)) {
10230     SDValue VPermMask[8];
10231     for (int i = 0; i < 8; ++i)
10232       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10233                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10234     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10235       return DAG.getNode(
10236           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10237           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10238
10239     if (Subtarget->hasAVX2())
10240       return DAG.getNode(
10241           X86ISD::VPERMV, DL, MVT::v8f32,
10242           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10243                                                  MVT::v8i32, VPermMask)),
10244           V1);
10245
10246     // Otherwise, fall back.
10247     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10248                                                    DAG);
10249   }
10250
10251   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10252   // shuffle.
10253   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10254           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10255     return Result;
10256
10257   // If we have AVX2 then we always want to lower with a blend because at v8 we
10258   // can fully permute the elements.
10259   if (Subtarget->hasAVX2())
10260     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10261                                                       Mask, DAG);
10262
10263   // Otherwise fall back on generic lowering.
10264   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10265 }
10266
10267 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10268 ///
10269 /// This routine is only called when we have AVX2 and thus a reasonable
10270 /// instruction set for v8i32 shuffling..
10271 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10272                                        const X86Subtarget *Subtarget,
10273                                        SelectionDAG &DAG) {
10274   SDLoc DL(Op);
10275   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10276   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10277   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10278   ArrayRef<int> Mask = SVOp->getMask();
10279   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10280   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10281
10282   // Whenever we can lower this as a zext, that instruction is strictly faster
10283   // than any alternative. It also allows us to fold memory operands into the
10284   // shuffle in many cases.
10285   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10286                                                          Mask, Subtarget, DAG))
10287     return ZExt;
10288
10289   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10290                                                 Subtarget, DAG))
10291     return Blend;
10292
10293   // Check for being able to broadcast a single element.
10294   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10295                                                         Mask, Subtarget, DAG))
10296     return Broadcast;
10297
10298   // If the shuffle mask is repeated in each 128-bit lane we can use more
10299   // efficient instructions that mirror the shuffles across the two 128-bit
10300   // lanes.
10301   SmallVector<int, 4> RepeatedMask;
10302   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10303     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10304     if (isSingleInputShuffleMask(Mask))
10305       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10306                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10307
10308     // Use dedicated unpack instructions for masks that match their pattern.
10309     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10310       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10311     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10312       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10313     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10314       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10315     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10316       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10317   }
10318
10319   // Try to use shift instructions.
10320   if (SDValue Shift =
10321           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10322     return Shift;
10323
10324   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10325           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10326     return Rotate;
10327
10328   // If the shuffle patterns aren't repeated but it is a single input, directly
10329   // generate a cross-lane VPERMD instruction.
10330   if (isSingleInputShuffleMask(Mask)) {
10331     SDValue VPermMask[8];
10332     for (int i = 0; i < 8; ++i)
10333       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10334                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10335     return DAG.getNode(
10336         X86ISD::VPERMV, DL, MVT::v8i32,
10337         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10338   }
10339
10340   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10341   // shuffle.
10342   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10343           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10344     return Result;
10345
10346   // Otherwise fall back on generic blend lowering.
10347   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10348                                                     Mask, DAG);
10349 }
10350
10351 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10352 ///
10353 /// This routine is only called when we have AVX2 and thus a reasonable
10354 /// instruction set for v16i16 shuffling..
10355 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10356                                         const X86Subtarget *Subtarget,
10357                                         SelectionDAG &DAG) {
10358   SDLoc DL(Op);
10359   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10360   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10361   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10362   ArrayRef<int> Mask = SVOp->getMask();
10363   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10364   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10365
10366   // Whenever we can lower this as a zext, that instruction is strictly faster
10367   // than any alternative. It also allows us to fold memory operands into the
10368   // shuffle in many cases.
10369   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10370                                                          Mask, Subtarget, DAG))
10371     return ZExt;
10372
10373   // Check for being able to broadcast a single element.
10374   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10375                                                         Mask, Subtarget, DAG))
10376     return Broadcast;
10377
10378   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10379                                                 Subtarget, DAG))
10380     return Blend;
10381
10382   // Use dedicated unpack instructions for masks that match their pattern.
10383   if (isShuffleEquivalent(V1, V2, Mask,
10384                           {// First 128-bit lane:
10385                            0, 16, 1, 17, 2, 18, 3, 19,
10386                            // Second 128-bit lane:
10387                            8, 24, 9, 25, 10, 26, 11, 27}))
10388     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10389   if (isShuffleEquivalent(V1, V2, Mask,
10390                           {// First 128-bit lane:
10391                            4, 20, 5, 21, 6, 22, 7, 23,
10392                            // Second 128-bit lane:
10393                            12, 28, 13, 29, 14, 30, 15, 31}))
10394     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10395
10396   // Try to use shift instructions.
10397   if (SDValue Shift =
10398           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10399     return Shift;
10400
10401   // Try to use byte rotation instructions.
10402   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10403           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10404     return Rotate;
10405
10406   if (isSingleInputShuffleMask(Mask)) {
10407     // There are no generalized cross-lane shuffle operations available on i16
10408     // element types.
10409     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10410       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10411                                                      Mask, DAG);
10412
10413     SmallVector<int, 8> RepeatedMask;
10414     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10415       // As this is a single-input shuffle, the repeated mask should be
10416       // a strictly valid v8i16 mask that we can pass through to the v8i16
10417       // lowering to handle even the v16 case.
10418       return lowerV8I16GeneralSingleInputVectorShuffle(
10419           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10420     }
10421
10422     SDValue PSHUFBMask[32];
10423     for (int i = 0; i < 16; ++i) {
10424       if (Mask[i] == -1) {
10425         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10426         continue;
10427       }
10428
10429       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10430       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10431       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10432       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10433     }
10434     return DAG.getBitcast(MVT::v16i16,
10435                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10436                                       DAG.getBitcast(MVT::v32i8, V1),
10437                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10438                                                   MVT::v32i8, PSHUFBMask)));
10439   }
10440
10441   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10442   // shuffle.
10443   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10444           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10445     return Result;
10446
10447   // Otherwise fall back on generic lowering.
10448   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10449 }
10450
10451 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10452 ///
10453 /// This routine is only called when we have AVX2 and thus a reasonable
10454 /// instruction set for v32i8 shuffling..
10455 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10456                                        const X86Subtarget *Subtarget,
10457                                        SelectionDAG &DAG) {
10458   SDLoc DL(Op);
10459   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10460   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10461   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10462   ArrayRef<int> Mask = SVOp->getMask();
10463   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10464   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10465
10466   // Whenever we can lower this as a zext, that instruction is strictly faster
10467   // than any alternative. It also allows us to fold memory operands into the
10468   // shuffle in many cases.
10469   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10470                                                          Mask, Subtarget, DAG))
10471     return ZExt;
10472
10473   // Check for being able to broadcast a single element.
10474   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10475                                                         Mask, Subtarget, DAG))
10476     return Broadcast;
10477
10478   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10479                                                 Subtarget, DAG))
10480     return Blend;
10481
10482   // Use dedicated unpack instructions for masks that match their pattern.
10483   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10484   // 256-bit lanes.
10485   if (isShuffleEquivalent(
10486           V1, V2, Mask,
10487           {// First 128-bit lane:
10488            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10489            // Second 128-bit lane:
10490            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10491     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10492   if (isShuffleEquivalent(
10493           V1, V2, Mask,
10494           {// First 128-bit lane:
10495            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10496            // Second 128-bit lane:
10497            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10498     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10499
10500   // Try to use shift instructions.
10501   if (SDValue Shift =
10502           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10503     return Shift;
10504
10505   // Try to use byte rotation instructions.
10506   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10507           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10508     return Rotate;
10509
10510   if (isSingleInputShuffleMask(Mask)) {
10511     // There are no generalized cross-lane shuffle operations available on i8
10512     // element types.
10513     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10514       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10515                                                      Mask, DAG);
10516
10517     SDValue PSHUFBMask[32];
10518     for (int i = 0; i < 32; ++i)
10519       PSHUFBMask[i] =
10520           Mask[i] < 0
10521               ? DAG.getUNDEF(MVT::i8)
10522               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10523                                 MVT::i8);
10524
10525     return DAG.getNode(
10526         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10527         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10528   }
10529
10530   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10531   // shuffle.
10532   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10533           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10534     return Result;
10535
10536   // Otherwise fall back on generic lowering.
10537   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10538 }
10539
10540 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10541 ///
10542 /// This routine either breaks down the specific type of a 256-bit x86 vector
10543 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10544 /// together based on the available instructions.
10545 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10546                                         MVT VT, const X86Subtarget *Subtarget,
10547                                         SelectionDAG &DAG) {
10548   SDLoc DL(Op);
10549   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10550   ArrayRef<int> Mask = SVOp->getMask();
10551
10552   // If we have a single input to the zero element, insert that into V1 if we
10553   // can do so cheaply.
10554   int NumElts = VT.getVectorNumElements();
10555   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10556     return M >= NumElts;
10557   });
10558
10559   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10560     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10561                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10562       return Insertion;
10563
10564   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10565   // check for those subtargets here and avoid much of the subtarget querying in
10566   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10567   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10568   // floating point types there eventually, just immediately cast everything to
10569   // a float and operate entirely in that domain.
10570   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10571     int ElementBits = VT.getScalarSizeInBits();
10572     if (ElementBits < 32)
10573       // No floating point type available, decompose into 128-bit vectors.
10574       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10575
10576     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10577                                 VT.getVectorNumElements());
10578     V1 = DAG.getBitcast(FpVT, V1);
10579     V2 = DAG.getBitcast(FpVT, V2);
10580     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10581   }
10582
10583   switch (VT.SimpleTy) {
10584   case MVT::v4f64:
10585     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10586   case MVT::v4i64:
10587     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10588   case MVT::v8f32:
10589     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10590   case MVT::v8i32:
10591     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10592   case MVT::v16i16:
10593     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10594   case MVT::v32i8:
10595     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10596
10597   default:
10598     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10599   }
10600 }
10601
10602 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10603                                            ArrayRef<int> Mask, SDValue V1,
10604                                            SDValue V2, SelectionDAG &DAG) {
10605
10606   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10607
10608   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10609   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10610
10611   SmallVector<SDValue, 32>  VPermMask;
10612   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i)
10613     VPermMask.push_back(Mask[i] < 0 ? DAG.getUNDEF(MaskEltVT) :
10614                         DAG.getConstant(Mask[i], DL, MaskEltVT));
10615   SDValue MaskNode = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVecVT,
10616                                  VPermMask);
10617   if (isSingleInputShuffleMask(Mask))
10618     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10619
10620   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10621 }
10622
10623 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10624 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10625                                        const X86Subtarget *Subtarget,
10626                                        SelectionDAG &DAG) {
10627   SDLoc DL(Op);
10628   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10629   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10630   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10631   ArrayRef<int> Mask = SVOp->getMask();
10632   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10633
10634   if (SDValue Unpck =
10635           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10636     return Unpck;
10637
10638   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10639 }
10640
10641 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10642 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10643                                        const X86Subtarget *Subtarget,
10644                                        SelectionDAG &DAG) {
10645   SDLoc DL(Op);
10646   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10647   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10648   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10649   ArrayRef<int> Mask = SVOp->getMask();
10650   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10651
10652   if (SDValue Unpck =
10653           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
10654     return Unpck;
10655
10656   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10657 }
10658
10659 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10660 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10661                                        const X86Subtarget *Subtarget,
10662                                        SelectionDAG &DAG) {
10663   SDLoc DL(Op);
10664   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10665   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10666   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10667   ArrayRef<int> Mask = SVOp->getMask();
10668   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10669
10670   if (SDValue Unpck =
10671           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
10672     return Unpck;
10673
10674   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10675 }
10676
10677 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10678 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10679                                        const X86Subtarget *Subtarget,
10680                                        SelectionDAG &DAG) {
10681   SDLoc DL(Op);
10682   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10683   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10684   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10685   ArrayRef<int> Mask = SVOp->getMask();
10686   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10687
10688   if (SDValue Unpck =
10689           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
10690     return Unpck;
10691
10692   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10693 }
10694
10695 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10696 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10697                                         const X86Subtarget *Subtarget,
10698                                         SelectionDAG &DAG) {
10699   SDLoc DL(Op);
10700   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10701   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10702   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10703   ArrayRef<int> Mask = SVOp->getMask();
10704   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10705   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10706
10707   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10708 }
10709
10710 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10711 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10712                                        const X86Subtarget *Subtarget,
10713                                        SelectionDAG &DAG) {
10714   SDLoc DL(Op);
10715   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10716   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10717   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10718   ArrayRef<int> Mask = SVOp->getMask();
10719   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10720   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10721
10722   // FIXME: Implement direct support for this type!
10723   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10724 }
10725
10726 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10727 ///
10728 /// This routine either breaks down the specific type of a 512-bit x86 vector
10729 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10730 /// together based on the available instructions.
10731 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10732                                         MVT VT, const X86Subtarget *Subtarget,
10733                                         SelectionDAG &DAG) {
10734   SDLoc DL(Op);
10735   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10736   ArrayRef<int> Mask = SVOp->getMask();
10737   assert(Subtarget->hasAVX512() &&
10738          "Cannot lower 512-bit vectors w/ basic ISA!");
10739
10740   // Check for being able to broadcast a single element.
10741   if (SDValue Broadcast =
10742           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10743     return Broadcast;
10744
10745   // Dispatch to each element type for lowering. If we don't have supprot for
10746   // specific element type shuffles at 512 bits, immediately split them and
10747   // lower them. Each lowering routine of a given type is allowed to assume that
10748   // the requisite ISA extensions for that element type are available.
10749   switch (VT.SimpleTy) {
10750   case MVT::v8f64:
10751     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10752   case MVT::v16f32:
10753     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10754   case MVT::v8i64:
10755     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10756   case MVT::v16i32:
10757     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10758   case MVT::v32i16:
10759     if (Subtarget->hasBWI())
10760       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10761     break;
10762   case MVT::v64i8:
10763     if (Subtarget->hasBWI())
10764       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10765     break;
10766
10767   default:
10768     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10769   }
10770
10771   // Otherwise fall back on splitting.
10772   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10773 }
10774
10775 // Lower vXi1 vector shuffles.
10776 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
10777 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
10778 // vector, shuffle and then truncate it back.
10779 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10780                                       MVT VT, const X86Subtarget *Subtarget,
10781                                       SelectionDAG &DAG) {
10782   SDLoc DL(Op);
10783   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10784   ArrayRef<int> Mask = SVOp->getMask();
10785   assert(Subtarget->hasAVX512() &&
10786          "Cannot lower 512-bit vectors w/o basic ISA!");
10787   EVT ExtVT;
10788   switch (VT.SimpleTy) {
10789   default:
10790     assert(false && "Expected a vector of i1 elements");
10791     break;
10792   case MVT::v2i1:
10793     ExtVT = MVT::v2i64;
10794     break;
10795   case MVT::v4i1:
10796     ExtVT = MVT::v4i32;
10797     break;
10798   case MVT::v8i1:
10799     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
10800     break;
10801   case MVT::v16i1:
10802     ExtVT = MVT::v16i32;
10803     break;
10804   case MVT::v32i1:
10805     ExtVT = MVT::v32i16;
10806     break;
10807   case MVT::v64i1:
10808     ExtVT = MVT::v64i8;
10809     break;
10810   }
10811
10812   if (ISD::isBuildVectorAllZeros(V1.getNode()))
10813     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10814   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
10815     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10816   else
10817     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
10818
10819   if (V2.isUndef())
10820     V2 = DAG.getUNDEF(ExtVT);
10821   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
10822     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10823   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
10824     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10825   else
10826     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
10827   return DAG.getNode(ISD::TRUNCATE, DL, VT,
10828                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
10829 }
10830 /// \brief Top-level lowering for x86 vector shuffles.
10831 ///
10832 /// This handles decomposition, canonicalization, and lowering of all x86
10833 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10834 /// above in helper routines. The canonicalization attempts to widen shuffles
10835 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10836 /// s.t. only one of the two inputs needs to be tested, etc.
10837 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10838                                   SelectionDAG &DAG) {
10839   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10840   ArrayRef<int> Mask = SVOp->getMask();
10841   SDValue V1 = Op.getOperand(0);
10842   SDValue V2 = Op.getOperand(1);
10843   MVT VT = Op.getSimpleValueType();
10844   int NumElements = VT.getVectorNumElements();
10845   SDLoc dl(Op);
10846   bool Is1BitVector = (VT.getScalarType() == MVT::i1);
10847
10848   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
10849          "Can't lower MMX shuffles");
10850
10851   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10852   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10853   if (V1IsUndef && V2IsUndef)
10854     return DAG.getUNDEF(VT);
10855
10856   // When we create a shuffle node we put the UNDEF node to second operand,
10857   // but in some cases the first operand may be transformed to UNDEF.
10858   // In this case we should just commute the node.
10859   if (V1IsUndef)
10860     return DAG.getCommutedVectorShuffle(*SVOp);
10861
10862   // Check for non-undef masks pointing at an undef vector and make the masks
10863   // undef as well. This makes it easier to match the shuffle based solely on
10864   // the mask.
10865   if (V2IsUndef)
10866     for (int M : Mask)
10867       if (M >= NumElements) {
10868         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10869         for (int &M : NewMask)
10870           if (M >= NumElements)
10871             M = -1;
10872         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10873       }
10874
10875   // We actually see shuffles that are entirely re-arrangements of a set of
10876   // zero inputs. This mostly happens while decomposing complex shuffles into
10877   // simple ones. Directly lower these as a buildvector of zeros.
10878   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10879   if (Zeroable.all())
10880     return getZeroVector(VT, Subtarget, DAG, dl);
10881
10882   // Try to collapse shuffles into using a vector type with fewer elements but
10883   // wider element types. We cap this to not form integers or floating point
10884   // elements wider than 64 bits, but it might be interesting to form i128
10885   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10886   SmallVector<int, 16> WidenedMask;
10887   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
10888       canWidenShuffleElements(Mask, WidenedMask)) {
10889     MVT NewEltVT = VT.isFloatingPoint()
10890                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10891                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10892     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10893     // Make sure that the new vector type is legal. For example, v2f64 isn't
10894     // legal on SSE1.
10895     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10896       V1 = DAG.getBitcast(NewVT, V1);
10897       V2 = DAG.getBitcast(NewVT, V2);
10898       return DAG.getBitcast(
10899           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10900     }
10901   }
10902
10903   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10904   for (int M : SVOp->getMask())
10905     if (M < 0)
10906       ++NumUndefElements;
10907     else if (M < NumElements)
10908       ++NumV1Elements;
10909     else
10910       ++NumV2Elements;
10911
10912   // Commute the shuffle as needed such that more elements come from V1 than
10913   // V2. This allows us to match the shuffle pattern strictly on how many
10914   // elements come from V1 without handling the symmetric cases.
10915   if (NumV2Elements > NumV1Elements)
10916     return DAG.getCommutedVectorShuffle(*SVOp);
10917
10918   // When the number of V1 and V2 elements are the same, try to minimize the
10919   // number of uses of V2 in the low half of the vector. When that is tied,
10920   // ensure that the sum of indices for V1 is equal to or lower than the sum
10921   // indices for V2. When those are equal, try to ensure that the number of odd
10922   // indices for V1 is lower than the number of odd indices for V2.
10923   if (NumV1Elements == NumV2Elements) {
10924     int LowV1Elements = 0, LowV2Elements = 0;
10925     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10926       if (M >= NumElements)
10927         ++LowV2Elements;
10928       else if (M >= 0)
10929         ++LowV1Elements;
10930     if (LowV2Elements > LowV1Elements) {
10931       return DAG.getCommutedVectorShuffle(*SVOp);
10932     } else if (LowV2Elements == LowV1Elements) {
10933       int SumV1Indices = 0, SumV2Indices = 0;
10934       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10935         if (SVOp->getMask()[i] >= NumElements)
10936           SumV2Indices += i;
10937         else if (SVOp->getMask()[i] >= 0)
10938           SumV1Indices += i;
10939       if (SumV2Indices < SumV1Indices) {
10940         return DAG.getCommutedVectorShuffle(*SVOp);
10941       } else if (SumV2Indices == SumV1Indices) {
10942         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10943         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10944           if (SVOp->getMask()[i] >= NumElements)
10945             NumV2OddIndices += i % 2;
10946           else if (SVOp->getMask()[i] >= 0)
10947             NumV1OddIndices += i % 2;
10948         if (NumV2OddIndices < NumV1OddIndices)
10949           return DAG.getCommutedVectorShuffle(*SVOp);
10950       }
10951     }
10952   }
10953
10954   // For each vector width, delegate to a specialized lowering routine.
10955   if (VT.getSizeInBits() == 128)
10956     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10957
10958   if (VT.getSizeInBits() == 256)
10959     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10960
10961   if (VT.getSizeInBits() == 512)
10962     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10963
10964   if (Is1BitVector)
10965     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10966   llvm_unreachable("Unimplemented!");
10967 }
10968
10969 // This function assumes its argument is a BUILD_VECTOR of constants or
10970 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10971 // true.
10972 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10973                                     unsigned &MaskValue) {
10974   MaskValue = 0;
10975   unsigned NumElems = BuildVector->getNumOperands();
10976   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10977   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10978   unsigned NumElemsInLane = NumElems / NumLanes;
10979
10980   // Blend for v16i16 should be symmetric for the both lanes.
10981   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10982     SDValue EltCond = BuildVector->getOperand(i);
10983     SDValue SndLaneEltCond =
10984         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10985
10986     int Lane1Cond = -1, Lane2Cond = -1;
10987     if (isa<ConstantSDNode>(EltCond))
10988       Lane1Cond = !isZero(EltCond);
10989     if (isa<ConstantSDNode>(SndLaneEltCond))
10990       Lane2Cond = !isZero(SndLaneEltCond);
10991
10992     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10993       // Lane1Cond != 0, means we want the first argument.
10994       // Lane1Cond == 0, means we want the second argument.
10995       // The encoding of this argument is 0 for the first argument, 1
10996       // for the second. Therefore, invert the condition.
10997       MaskValue |= !Lane1Cond << i;
10998     else if (Lane1Cond < 0)
10999       MaskValue |= !Lane2Cond << i;
11000     else
11001       return false;
11002   }
11003   return true;
11004 }
11005
11006 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11007 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11008                                            const X86Subtarget *Subtarget,
11009                                            SelectionDAG &DAG) {
11010   SDValue Cond = Op.getOperand(0);
11011   SDValue LHS = Op.getOperand(1);
11012   SDValue RHS = Op.getOperand(2);
11013   SDLoc dl(Op);
11014   MVT VT = Op.getSimpleValueType();
11015
11016   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11017     return SDValue();
11018   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11019
11020   // Only non-legal VSELECTs reach this lowering, convert those into generic
11021   // shuffles and re-use the shuffle lowering path for blends.
11022   SmallVector<int, 32> Mask;
11023   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11024     SDValue CondElt = CondBV->getOperand(i);
11025     Mask.push_back(
11026         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
11027   }
11028   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11029 }
11030
11031 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11032   // A vselect where all conditions and data are constants can be optimized into
11033   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11034   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11035       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11036       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11037     return SDValue();
11038
11039   // Try to lower this to a blend-style vector shuffle. This can handle all
11040   // constant condition cases.
11041   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11042     return BlendOp;
11043
11044   // Variable blends are only legal from SSE4.1 onward.
11045   if (!Subtarget->hasSSE41())
11046     return SDValue();
11047
11048   // Only some types will be legal on some subtargets. If we can emit a legal
11049   // VSELECT-matching blend, return Op, and but if we need to expand, return
11050   // a null value.
11051   switch (Op.getSimpleValueType().SimpleTy) {
11052   default:
11053     // Most of the vector types have blends past SSE4.1.
11054     return Op;
11055
11056   case MVT::v32i8:
11057     // The byte blends for AVX vectors were introduced only in AVX2.
11058     if (Subtarget->hasAVX2())
11059       return Op;
11060
11061     return SDValue();
11062
11063   case MVT::v8i16:
11064   case MVT::v16i16:
11065     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11066     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11067       return Op;
11068
11069     // FIXME: We should custom lower this by fixing the condition and using i8
11070     // blends.
11071     return SDValue();
11072   }
11073 }
11074
11075 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11076   MVT VT = Op.getSimpleValueType();
11077   SDLoc dl(Op);
11078
11079   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11080     return SDValue();
11081
11082   if (VT.getSizeInBits() == 8) {
11083     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11084                                   Op.getOperand(0), Op.getOperand(1));
11085     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11086                                   DAG.getValueType(VT));
11087     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11088   }
11089
11090   if (VT.getSizeInBits() == 16) {
11091     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11092     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11093     if (Idx == 0)
11094       return DAG.getNode(
11095           ISD::TRUNCATE, dl, MVT::i16,
11096           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11097                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11098                       Op.getOperand(1)));
11099     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11100                                   Op.getOperand(0), Op.getOperand(1));
11101     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11102                                   DAG.getValueType(VT));
11103     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11104   }
11105
11106   if (VT == MVT::f32) {
11107     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11108     // the result back to FR32 register. It's only worth matching if the
11109     // result has a single use which is a store or a bitcast to i32.  And in
11110     // the case of a store, it's not worth it if the index is a constant 0,
11111     // because a MOVSSmr can be used instead, which is smaller and faster.
11112     if (!Op.hasOneUse())
11113       return SDValue();
11114     SDNode *User = *Op.getNode()->use_begin();
11115     if ((User->getOpcode() != ISD::STORE ||
11116          (isa<ConstantSDNode>(Op.getOperand(1)) &&
11117           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11118         (User->getOpcode() != ISD::BITCAST ||
11119          User->getValueType(0) != MVT::i32))
11120       return SDValue();
11121     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11122                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11123                                   Op.getOperand(1));
11124     return DAG.getBitcast(MVT::f32, Extract);
11125   }
11126
11127   if (VT == MVT::i32 || VT == MVT::i64) {
11128     // ExtractPS/pextrq works with constant index.
11129     if (isa<ConstantSDNode>(Op.getOperand(1)))
11130       return Op;
11131   }
11132   return SDValue();
11133 }
11134
11135 /// Extract one bit from mask vector, like v16i1 or v8i1.
11136 /// AVX-512 feature.
11137 SDValue
11138 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11139   SDValue Vec = Op.getOperand(0);
11140   SDLoc dl(Vec);
11141   MVT VecVT = Vec.getSimpleValueType();
11142   SDValue Idx = Op.getOperand(1);
11143   MVT EltVT = Op.getSimpleValueType();
11144
11145   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11146   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11147          "Unexpected vector type in ExtractBitFromMaskVector");
11148
11149   // variable index can't be handled in mask registers,
11150   // extend vector to VR512
11151   if (!isa<ConstantSDNode>(Idx)) {
11152     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11153     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11154     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11155                               ExtVT.getVectorElementType(), Ext, Idx);
11156     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11157   }
11158
11159   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11160   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11161   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11162     rc = getRegClassFor(MVT::v16i1);
11163   unsigned MaxSift = rc->getSize()*8 - 1;
11164   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11165                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11166   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11167                     DAG.getConstant(MaxSift, dl, MVT::i8));
11168   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11169                        DAG.getIntPtrConstant(0, dl));
11170 }
11171
11172 SDValue
11173 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11174                                            SelectionDAG &DAG) const {
11175   SDLoc dl(Op);
11176   SDValue Vec = Op.getOperand(0);
11177   MVT VecVT = Vec.getSimpleValueType();
11178   SDValue Idx = Op.getOperand(1);
11179
11180   if (Op.getSimpleValueType() == MVT::i1)
11181     return ExtractBitFromMaskVector(Op, DAG);
11182
11183   if (!isa<ConstantSDNode>(Idx)) {
11184     if (VecVT.is512BitVector() ||
11185         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11186          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11187
11188       MVT MaskEltVT =
11189         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11190       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11191                                     MaskEltVT.getSizeInBits());
11192
11193       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11194       auto PtrVT = getPointerTy(DAG.getDataLayout());
11195       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11196                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11197                                  DAG.getConstant(0, dl, PtrVT));
11198       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11199       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11200                          DAG.getConstant(0, dl, PtrVT));
11201     }
11202     return SDValue();
11203   }
11204
11205   // If this is a 256-bit vector result, first extract the 128-bit vector and
11206   // then extract the element from the 128-bit vector.
11207   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11208
11209     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11210     // Get the 128-bit vector.
11211     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11212     MVT EltVT = VecVT.getVectorElementType();
11213
11214     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11215
11216     //if (IdxVal >= NumElems/2)
11217     //  IdxVal -= NumElems/2;
11218     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
11219     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11220                        DAG.getConstant(IdxVal, dl, MVT::i32));
11221   }
11222
11223   assert(VecVT.is128BitVector() && "Unexpected vector length");
11224
11225   if (Subtarget->hasSSE41())
11226     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11227       return Res;
11228
11229   MVT VT = Op.getSimpleValueType();
11230   // TODO: handle v16i8.
11231   if (VT.getSizeInBits() == 16) {
11232     SDValue Vec = Op.getOperand(0);
11233     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11234     if (Idx == 0)
11235       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11236                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11237                                      DAG.getBitcast(MVT::v4i32, Vec),
11238                                      Op.getOperand(1)));
11239     // Transform it so it match pextrw which produces a 32-bit result.
11240     MVT EltVT = MVT::i32;
11241     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11242                                   Op.getOperand(0), Op.getOperand(1));
11243     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11244                                   DAG.getValueType(VT));
11245     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11246   }
11247
11248   if (VT.getSizeInBits() == 32) {
11249     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11250     if (Idx == 0)
11251       return Op;
11252
11253     // SHUFPS the element to the lowest double word, then movss.
11254     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11255     MVT VVT = Op.getOperand(0).getSimpleValueType();
11256     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11257                                        DAG.getUNDEF(VVT), Mask);
11258     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11259                        DAG.getIntPtrConstant(0, dl));
11260   }
11261
11262   if (VT.getSizeInBits() == 64) {
11263     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11264     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11265     //        to match extract_elt for f64.
11266     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11267     if (Idx == 0)
11268       return Op;
11269
11270     // UNPCKHPD the element to the lowest double word, then movsd.
11271     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11272     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11273     int Mask[2] = { 1, -1 };
11274     MVT VVT = Op.getOperand(0).getSimpleValueType();
11275     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11276                                        DAG.getUNDEF(VVT), Mask);
11277     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11278                        DAG.getIntPtrConstant(0, dl));
11279   }
11280
11281   return SDValue();
11282 }
11283
11284 /// Insert one bit to mask vector, like v16i1 or v8i1.
11285 /// AVX-512 feature.
11286 SDValue
11287 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11288   SDLoc dl(Op);
11289   SDValue Vec = Op.getOperand(0);
11290   SDValue Elt = Op.getOperand(1);
11291   SDValue Idx = Op.getOperand(2);
11292   MVT VecVT = Vec.getSimpleValueType();
11293
11294   if (!isa<ConstantSDNode>(Idx)) {
11295     // Non constant index. Extend source and destination,
11296     // insert element and then truncate the result.
11297     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11298     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11299     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11300       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11301       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11302     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11303   }
11304
11305   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11306   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11307   if (IdxVal)
11308     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11309                            DAG.getConstant(IdxVal, dl, MVT::i8));
11310   if (Vec.getOpcode() == ISD::UNDEF)
11311     return EltInVec;
11312   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11313 }
11314
11315 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11316                                                   SelectionDAG &DAG) const {
11317   MVT VT = Op.getSimpleValueType();
11318   MVT EltVT = VT.getVectorElementType();
11319
11320   if (EltVT == MVT::i1)
11321     return InsertBitToMaskVector(Op, DAG);
11322
11323   SDLoc dl(Op);
11324   SDValue N0 = Op.getOperand(0);
11325   SDValue N1 = Op.getOperand(1);
11326   SDValue N2 = Op.getOperand(2);
11327   if (!isa<ConstantSDNode>(N2))
11328     return SDValue();
11329   auto *N2C = cast<ConstantSDNode>(N2);
11330   unsigned IdxVal = N2C->getZExtValue();
11331
11332   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11333   // into that, and then insert the subvector back into the result.
11334   if (VT.is256BitVector() || VT.is512BitVector()) {
11335     // With a 256-bit vector, we can insert into the zero element efficiently
11336     // using a blend if we have AVX or AVX2 and the right data type.
11337     if (VT.is256BitVector() && IdxVal == 0) {
11338       // TODO: It is worthwhile to cast integer to floating point and back
11339       // and incur a domain crossing penalty if that's what we'll end up
11340       // doing anyway after extracting to a 128-bit vector.
11341       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11342           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11343         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11344         N2 = DAG.getIntPtrConstant(1, dl);
11345         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11346       }
11347     }
11348
11349     // Get the desired 128-bit vector chunk.
11350     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11351
11352     // Insert the element into the desired chunk.
11353     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11354     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11355
11356     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11357                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11358
11359     // Insert the changed part back into the bigger vector
11360     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11361   }
11362   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11363
11364   if (Subtarget->hasSSE41()) {
11365     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11366       unsigned Opc;
11367       if (VT == MVT::v8i16) {
11368         Opc = X86ISD::PINSRW;
11369       } else {
11370         assert(VT == MVT::v16i8);
11371         Opc = X86ISD::PINSRB;
11372       }
11373
11374       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11375       // argument.
11376       if (N1.getValueType() != MVT::i32)
11377         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11378       if (N2.getValueType() != MVT::i32)
11379         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11380       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11381     }
11382
11383     if (EltVT == MVT::f32) {
11384       // Bits [7:6] of the constant are the source select. This will always be
11385       //   zero here. The DAG Combiner may combine an extract_elt index into
11386       //   these bits. For example (insert (extract, 3), 2) could be matched by
11387       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11388       // Bits [5:4] of the constant are the destination select. This is the
11389       //   value of the incoming immediate.
11390       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11391       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11392
11393       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11394       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11395         // If this is an insertion of 32-bits into the low 32-bits of
11396         // a vector, we prefer to generate a blend with immediate rather
11397         // than an insertps. Blends are simpler operations in hardware and so
11398         // will always have equal or better performance than insertps.
11399         // But if optimizing for size and there's a load folding opportunity,
11400         // generate insertps because blendps does not have a 32-bit memory
11401         // operand form.
11402         N2 = DAG.getIntPtrConstant(1, dl);
11403         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11404         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11405       }
11406       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11407       // Create this as a scalar to vector..
11408       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11409       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11410     }
11411
11412     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11413       // PINSR* works with constant index.
11414       return Op;
11415     }
11416   }
11417
11418   if (EltVT == MVT::i8)
11419     return SDValue();
11420
11421   if (EltVT.getSizeInBits() == 16) {
11422     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11423     // as its second argument.
11424     if (N1.getValueType() != MVT::i32)
11425       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11426     if (N2.getValueType() != MVT::i32)
11427       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11428     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11429   }
11430   return SDValue();
11431 }
11432
11433 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11434   SDLoc dl(Op);
11435   MVT OpVT = Op.getSimpleValueType();
11436
11437   // If this is a 256-bit vector result, first insert into a 128-bit
11438   // vector and then insert into the 256-bit vector.
11439   if (!OpVT.is128BitVector()) {
11440     // Insert into a 128-bit vector.
11441     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11442     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11443                                  OpVT.getVectorNumElements() / SizeFactor);
11444
11445     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11446
11447     // Insert the 128-bit vector.
11448     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11449   }
11450
11451   if (OpVT == MVT::v1i64 &&
11452       Op.getOperand(0).getValueType() == MVT::i64)
11453     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11454
11455   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11456   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11457   return DAG.getBitcast(
11458       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11459 }
11460
11461 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11462 // a simple subregister reference or explicit instructions to grab
11463 // upper bits of a vector.
11464 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11465                                       SelectionDAG &DAG) {
11466   SDLoc dl(Op);
11467   SDValue In =  Op.getOperand(0);
11468   SDValue Idx = Op.getOperand(1);
11469   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11470   MVT ResVT   = Op.getSimpleValueType();
11471   MVT InVT    = In.getSimpleValueType();
11472
11473   if (Subtarget->hasFp256()) {
11474     if (ResVT.is128BitVector() &&
11475         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11476         isa<ConstantSDNode>(Idx)) {
11477       return Extract128BitVector(In, IdxVal, DAG, dl);
11478     }
11479     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11480         isa<ConstantSDNode>(Idx)) {
11481       return Extract256BitVector(In, IdxVal, DAG, dl);
11482     }
11483   }
11484   return SDValue();
11485 }
11486
11487 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11488 // simple superregister reference or explicit instructions to insert
11489 // the upper bits of a vector.
11490 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11491                                      SelectionDAG &DAG) {
11492   if (!Subtarget->hasAVX())
11493     return SDValue();
11494
11495   SDLoc dl(Op);
11496   SDValue Vec = Op.getOperand(0);
11497   SDValue SubVec = Op.getOperand(1);
11498   SDValue Idx = Op.getOperand(2);
11499
11500   if (!isa<ConstantSDNode>(Idx))
11501     return SDValue();
11502
11503   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11504   MVT OpVT = Op.getSimpleValueType();
11505   MVT SubVecVT = SubVec.getSimpleValueType();
11506
11507   // Fold two 16-byte subvector loads into one 32-byte load:
11508   // (insert_subvector (insert_subvector undef, (load addr), 0),
11509   //                   (load addr + 16), Elts/2)
11510   // --> load32 addr
11511   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11512       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11513       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11514     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11515     if (Idx2 && Idx2->getZExtValue() == 0) {
11516       SDValue SubVec2 = Vec.getOperand(1);
11517       // If needed, look through a bitcast to get to the load.
11518       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11519         SubVec2 = SubVec2.getOperand(0);
11520
11521       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11522         bool Fast;
11523         unsigned Alignment = FirstLd->getAlignment();
11524         unsigned AS = FirstLd->getAddressSpace();
11525         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11526         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11527                                     OpVT, AS, Alignment, &Fast) && Fast) {
11528           SDValue Ops[] = { SubVec2, SubVec };
11529           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11530             return Ld;
11531         }
11532       }
11533     }
11534   }
11535
11536   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11537       SubVecVT.is128BitVector())
11538     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11539
11540   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11541     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11542
11543   if (OpVT.getVectorElementType() == MVT::i1) {
11544     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11545       return Op;
11546     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11547     SDValue Undef = DAG.getUNDEF(OpVT);
11548     unsigned NumElems = OpVT.getVectorNumElements();
11549     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11550
11551     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11552       // Zero upper bits of the Vec
11553       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11554       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11555
11556       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11557                                  SubVec, ZeroIdx);
11558       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11559       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11560     }
11561     if (IdxVal == 0) {
11562       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11563                                  SubVec, ZeroIdx);
11564       // Zero upper bits of the Vec2
11565       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11566       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11567       // Zero lower bits of the Vec
11568       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11569       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11570       // Merge them together
11571       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11572     }
11573   }
11574   return SDValue();
11575 }
11576
11577 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11578 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11579 // one of the above mentioned nodes. It has to be wrapped because otherwise
11580 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11581 // be used to form addressing mode. These wrapped nodes will be selected
11582 // into MOV32ri.
11583 SDValue
11584 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11585   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11586
11587   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11588   // global base reg.
11589   unsigned char OpFlag = 0;
11590   unsigned WrapperKind = X86ISD::Wrapper;
11591   CodeModel::Model M = DAG.getTarget().getCodeModel();
11592
11593   if (Subtarget->isPICStyleRIPRel() &&
11594       (M == CodeModel::Small || M == CodeModel::Kernel))
11595     WrapperKind = X86ISD::WrapperRIP;
11596   else if (Subtarget->isPICStyleGOT())
11597     OpFlag = X86II::MO_GOTOFF;
11598   else if (Subtarget->isPICStyleStubPIC())
11599     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11600
11601   auto PtrVT = getPointerTy(DAG.getDataLayout());
11602   SDValue Result = DAG.getTargetConstantPool(
11603       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11604   SDLoc DL(CP);
11605   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11606   // With PIC, the address is actually $g + Offset.
11607   if (OpFlag) {
11608     Result =
11609         DAG.getNode(ISD::ADD, DL, PtrVT,
11610                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11611   }
11612
11613   return Result;
11614 }
11615
11616 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11617   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11618
11619   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11620   // global base reg.
11621   unsigned char OpFlag = 0;
11622   unsigned WrapperKind = X86ISD::Wrapper;
11623   CodeModel::Model M = DAG.getTarget().getCodeModel();
11624
11625   if (Subtarget->isPICStyleRIPRel() &&
11626       (M == CodeModel::Small || M == CodeModel::Kernel))
11627     WrapperKind = X86ISD::WrapperRIP;
11628   else if (Subtarget->isPICStyleGOT())
11629     OpFlag = X86II::MO_GOTOFF;
11630   else if (Subtarget->isPICStyleStubPIC())
11631     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11632
11633   auto PtrVT = getPointerTy(DAG.getDataLayout());
11634   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11635   SDLoc DL(JT);
11636   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11637
11638   // With PIC, the address is actually $g + Offset.
11639   if (OpFlag)
11640     Result =
11641         DAG.getNode(ISD::ADD, DL, PtrVT,
11642                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11643
11644   return Result;
11645 }
11646
11647 SDValue
11648 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11649   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11650
11651   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11652   // global base reg.
11653   unsigned char OpFlag = 0;
11654   unsigned WrapperKind = X86ISD::Wrapper;
11655   CodeModel::Model M = DAG.getTarget().getCodeModel();
11656
11657   if (Subtarget->isPICStyleRIPRel() &&
11658       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11659     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11660       OpFlag = X86II::MO_GOTPCREL;
11661     WrapperKind = X86ISD::WrapperRIP;
11662   } else if (Subtarget->isPICStyleGOT()) {
11663     OpFlag = X86II::MO_GOT;
11664   } else if (Subtarget->isPICStyleStubPIC()) {
11665     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11666   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11667     OpFlag = X86II::MO_DARWIN_NONLAZY;
11668   }
11669
11670   auto PtrVT = getPointerTy(DAG.getDataLayout());
11671   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11672
11673   SDLoc DL(Op);
11674   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11675
11676   // With PIC, the address is actually $g + Offset.
11677   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11678       !Subtarget->is64Bit()) {
11679     Result =
11680         DAG.getNode(ISD::ADD, DL, PtrVT,
11681                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11682   }
11683
11684   // For symbols that require a load from a stub to get the address, emit the
11685   // load.
11686   if (isGlobalStubReference(OpFlag))
11687     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11688                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11689                          false, false, false, 0);
11690
11691   return Result;
11692 }
11693
11694 SDValue
11695 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11696   // Create the TargetBlockAddressAddress node.
11697   unsigned char OpFlags =
11698     Subtarget->ClassifyBlockAddressReference();
11699   CodeModel::Model M = DAG.getTarget().getCodeModel();
11700   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11701   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11702   SDLoc dl(Op);
11703   auto PtrVT = getPointerTy(DAG.getDataLayout());
11704   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11705
11706   if (Subtarget->isPICStyleRIPRel() &&
11707       (M == CodeModel::Small || M == CodeModel::Kernel))
11708     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11709   else
11710     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11711
11712   // With PIC, the address is actually $g + Offset.
11713   if (isGlobalRelativeToPICBase(OpFlags)) {
11714     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11715                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11716   }
11717
11718   return Result;
11719 }
11720
11721 SDValue
11722 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11723                                       int64_t Offset, SelectionDAG &DAG) const {
11724   // Create the TargetGlobalAddress node, folding in the constant
11725   // offset if it is legal.
11726   unsigned char OpFlags =
11727       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11728   CodeModel::Model M = DAG.getTarget().getCodeModel();
11729   auto PtrVT = getPointerTy(DAG.getDataLayout());
11730   SDValue Result;
11731   if (OpFlags == X86II::MO_NO_FLAG &&
11732       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11733     // A direct static reference to a global.
11734     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11735     Offset = 0;
11736   } else {
11737     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11738   }
11739
11740   if (Subtarget->isPICStyleRIPRel() &&
11741       (M == CodeModel::Small || M == CodeModel::Kernel))
11742     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11743   else
11744     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11745
11746   // With PIC, the address is actually $g + Offset.
11747   if (isGlobalRelativeToPICBase(OpFlags)) {
11748     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11749                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11750   }
11751
11752   // For globals that require a load from a stub to get the address, emit the
11753   // load.
11754   if (isGlobalStubReference(OpFlags))
11755     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11756                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11757                          false, false, false, 0);
11758
11759   // If there was a non-zero offset that we didn't fold, create an explicit
11760   // addition for it.
11761   if (Offset != 0)
11762     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11763                          DAG.getConstant(Offset, dl, PtrVT));
11764
11765   return Result;
11766 }
11767
11768 SDValue
11769 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11770   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11771   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11772   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11773 }
11774
11775 static SDValue
11776 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11777            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11778            unsigned char OperandFlags, bool LocalDynamic = false) {
11779   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11780   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11781   SDLoc dl(GA);
11782   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11783                                            GA->getValueType(0),
11784                                            GA->getOffset(),
11785                                            OperandFlags);
11786
11787   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11788                                            : X86ISD::TLSADDR;
11789
11790   if (InFlag) {
11791     SDValue Ops[] = { Chain,  TGA, *InFlag };
11792     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11793   } else {
11794     SDValue Ops[]  = { Chain, TGA };
11795     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11796   }
11797
11798   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11799   MFI->setAdjustsStack(true);
11800   MFI->setHasCalls(true);
11801
11802   SDValue Flag = Chain.getValue(1);
11803   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11804 }
11805
11806 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11807 static SDValue
11808 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11809                                 const EVT PtrVT) {
11810   SDValue InFlag;
11811   SDLoc dl(GA);  // ? function entry point might be better
11812   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11813                                    DAG.getNode(X86ISD::GlobalBaseReg,
11814                                                SDLoc(), PtrVT), InFlag);
11815   InFlag = Chain.getValue(1);
11816
11817   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11818 }
11819
11820 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11821 static SDValue
11822 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11823                                 const EVT PtrVT) {
11824   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11825                     X86::RAX, X86II::MO_TLSGD);
11826 }
11827
11828 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11829                                            SelectionDAG &DAG,
11830                                            const EVT PtrVT,
11831                                            bool is64Bit) {
11832   SDLoc dl(GA);
11833
11834   // Get the start address of the TLS block for this module.
11835   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11836       .getInfo<X86MachineFunctionInfo>();
11837   MFI->incNumLocalDynamicTLSAccesses();
11838
11839   SDValue Base;
11840   if (is64Bit) {
11841     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11842                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11843   } else {
11844     SDValue InFlag;
11845     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11846         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11847     InFlag = Chain.getValue(1);
11848     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11849                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11850   }
11851
11852   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11853   // of Base.
11854
11855   // Build x@dtpoff.
11856   unsigned char OperandFlags = X86II::MO_DTPOFF;
11857   unsigned WrapperKind = X86ISD::Wrapper;
11858   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11859                                            GA->getValueType(0),
11860                                            GA->getOffset(), OperandFlags);
11861   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11862
11863   // Add x@dtpoff with the base.
11864   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11865 }
11866
11867 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11868 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11869                                    const EVT PtrVT, TLSModel::Model model,
11870                                    bool is64Bit, bool isPIC) {
11871   SDLoc dl(GA);
11872
11873   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11874   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11875                                                          is64Bit ? 257 : 256));
11876
11877   SDValue ThreadPointer =
11878       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11879                   MachinePointerInfo(Ptr), false, false, false, 0);
11880
11881   unsigned char OperandFlags = 0;
11882   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11883   // initialexec.
11884   unsigned WrapperKind = X86ISD::Wrapper;
11885   if (model == TLSModel::LocalExec) {
11886     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11887   } else if (model == TLSModel::InitialExec) {
11888     if (is64Bit) {
11889       OperandFlags = X86II::MO_GOTTPOFF;
11890       WrapperKind = X86ISD::WrapperRIP;
11891     } else {
11892       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11893     }
11894   } else {
11895     llvm_unreachable("Unexpected model");
11896   }
11897
11898   // emit "addl x@ntpoff,%eax" (local exec)
11899   // or "addl x@indntpoff,%eax" (initial exec)
11900   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11901   SDValue TGA =
11902       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11903                                  GA->getOffset(), OperandFlags);
11904   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11905
11906   if (model == TLSModel::InitialExec) {
11907     if (isPIC && !is64Bit) {
11908       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11909                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11910                            Offset);
11911     }
11912
11913     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11914                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11915                          false, false, false, 0);
11916   }
11917
11918   // The address of the thread local variable is the add of the thread
11919   // pointer with the offset of the variable.
11920   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11921 }
11922
11923 SDValue
11924 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11925
11926   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11927   const GlobalValue *GV = GA->getGlobal();
11928   auto PtrVT = getPointerTy(DAG.getDataLayout());
11929
11930   if (Subtarget->isTargetELF()) {
11931     if (DAG.getTarget().Options.EmulatedTLS)
11932       return LowerToTLSEmulatedModel(GA, DAG);
11933     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11934     switch (model) {
11935       case TLSModel::GeneralDynamic:
11936         if (Subtarget->is64Bit())
11937           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11938         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11939       case TLSModel::LocalDynamic:
11940         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11941                                            Subtarget->is64Bit());
11942       case TLSModel::InitialExec:
11943       case TLSModel::LocalExec:
11944         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11945                                    DAG.getTarget().getRelocationModel() ==
11946                                        Reloc::PIC_);
11947     }
11948     llvm_unreachable("Unknown TLS model.");
11949   }
11950
11951   if (Subtarget->isTargetDarwin()) {
11952     // Darwin only has one model of TLS.  Lower to that.
11953     unsigned char OpFlag = 0;
11954     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11955                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11956
11957     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11958     // global base reg.
11959     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11960                  !Subtarget->is64Bit();
11961     if (PIC32)
11962       OpFlag = X86II::MO_TLVP_PIC_BASE;
11963     else
11964       OpFlag = X86II::MO_TLVP;
11965     SDLoc DL(Op);
11966     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11967                                                 GA->getValueType(0),
11968                                                 GA->getOffset(), OpFlag);
11969     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11970
11971     // With PIC32, the address is actually $g + Offset.
11972     if (PIC32)
11973       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11974                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11975                            Offset);
11976
11977     // Lowering the machine isd will make sure everything is in the right
11978     // location.
11979     SDValue Chain = DAG.getEntryNode();
11980     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11981     SDValue Args[] = { Chain, Offset };
11982     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11983
11984     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11985     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11986     MFI->setAdjustsStack(true);
11987
11988     // And our return value (tls address) is in the standard call return value
11989     // location.
11990     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11991     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11992   }
11993
11994   if (Subtarget->isTargetKnownWindowsMSVC() ||
11995       Subtarget->isTargetWindowsGNU()) {
11996     // Just use the implicit TLS architecture
11997     // Need to generate someting similar to:
11998     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11999     //                                  ; from TEB
12000     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12001     //   mov     rcx, qword [rdx+rcx*8]
12002     //   mov     eax, .tls$:tlsvar
12003     //   [rax+rcx] contains the address
12004     // Windows 64bit: gs:0x58
12005     // Windows 32bit: fs:__tls_array
12006
12007     SDLoc dl(GA);
12008     SDValue Chain = DAG.getEntryNode();
12009
12010     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12011     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12012     // use its literal value of 0x2C.
12013     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12014                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12015                                                              256)
12016                                         : Type::getInt32PtrTy(*DAG.getContext(),
12017                                                               257));
12018
12019     SDValue TlsArray = Subtarget->is64Bit()
12020                            ? DAG.getIntPtrConstant(0x58, dl)
12021                            : (Subtarget->isTargetWindowsGNU()
12022                                   ? DAG.getIntPtrConstant(0x2C, dl)
12023                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12024
12025     SDValue ThreadPointer =
12026         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12027                     false, false, 0);
12028
12029     SDValue res;
12030     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12031       res = ThreadPointer;
12032     } else {
12033       // Load the _tls_index variable
12034       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12035       if (Subtarget->is64Bit())
12036         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12037                              MachinePointerInfo(), MVT::i32, false, false,
12038                              false, 0);
12039       else
12040         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12041                           false, false, 0);
12042
12043       auto &DL = DAG.getDataLayout();
12044       SDValue Scale =
12045           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12046       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12047
12048       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12049     }
12050
12051     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12052                       false, 0);
12053
12054     // Get the offset of start of .tls section
12055     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12056                                              GA->getValueType(0),
12057                                              GA->getOffset(), X86II::MO_SECREL);
12058     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12059
12060     // The address of the thread local variable is the add of the thread
12061     // pointer with the offset of the variable.
12062     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12063   }
12064
12065   llvm_unreachable("TLS not implemented for this target.");
12066 }
12067
12068 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12069 /// and take a 2 x i32 value to shift plus a shift amount.
12070 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12071   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12072   MVT VT = Op.getSimpleValueType();
12073   unsigned VTBits = VT.getSizeInBits();
12074   SDLoc dl(Op);
12075   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12076   SDValue ShOpLo = Op.getOperand(0);
12077   SDValue ShOpHi = Op.getOperand(1);
12078   SDValue ShAmt  = Op.getOperand(2);
12079   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12080   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12081   // during isel.
12082   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12083                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12084   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12085                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12086                        : DAG.getConstant(0, dl, VT);
12087
12088   SDValue Tmp2, Tmp3;
12089   if (Op.getOpcode() == ISD::SHL_PARTS) {
12090     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12091     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12092   } else {
12093     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12094     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12095   }
12096
12097   // If the shift amount is larger or equal than the width of a part we can't
12098   // rely on the results of shld/shrd. Insert a test and select the appropriate
12099   // values for large shift amounts.
12100   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12101                                 DAG.getConstant(VTBits, dl, MVT::i8));
12102   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12103                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12104
12105   SDValue Hi, Lo;
12106   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12107   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12108   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12109
12110   if (Op.getOpcode() == ISD::SHL_PARTS) {
12111     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12112     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12113   } else {
12114     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12115     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12116   }
12117
12118   SDValue Ops[2] = { Lo, Hi };
12119   return DAG.getMergeValues(Ops, dl);
12120 }
12121
12122 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12123                                            SelectionDAG &DAG) const {
12124   SDValue Src = Op.getOperand(0);
12125   MVT SrcVT = Src.getSimpleValueType();
12126   MVT VT = Op.getSimpleValueType();
12127   SDLoc dl(Op);
12128
12129   if (SrcVT.isVector()) {
12130     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12131       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12132                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12133                          DAG.getUNDEF(SrcVT)));
12134     }
12135     if (SrcVT.getVectorElementType() == MVT::i1) {
12136       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12137       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12138                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12139     }
12140     return SDValue();
12141   }
12142
12143   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12144          "Unknown SINT_TO_FP to lower!");
12145
12146   // These are really Legal; return the operand so the caller accepts it as
12147   // Legal.
12148   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12149     return Op;
12150   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12151       Subtarget->is64Bit()) {
12152     return Op;
12153   }
12154
12155   unsigned Size = SrcVT.getSizeInBits()/8;
12156   MachineFunction &MF = DAG.getMachineFunction();
12157   auto PtrVT = getPointerTy(MF.getDataLayout());
12158   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12159   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12160   SDValue Chain = DAG.getStore(
12161       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12162       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12163       false, 0);
12164   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12165 }
12166
12167 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12168                                      SDValue StackSlot,
12169                                      SelectionDAG &DAG) const {
12170   // Build the FILD
12171   SDLoc DL(Op);
12172   SDVTList Tys;
12173   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12174   if (useSSE)
12175     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12176   else
12177     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12178
12179   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12180
12181   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12182   MachineMemOperand *MMO;
12183   if (FI) {
12184     int SSFI = FI->getIndex();
12185     MMO = DAG.getMachineFunction().getMachineMemOperand(
12186         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12187         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12188   } else {
12189     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12190     StackSlot = StackSlot.getOperand(1);
12191   }
12192   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12193   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12194                                            X86ISD::FILD, DL,
12195                                            Tys, Ops, SrcVT, MMO);
12196
12197   if (useSSE) {
12198     Chain = Result.getValue(1);
12199     SDValue InFlag = Result.getValue(2);
12200
12201     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12202     // shouldn't be necessary except that RFP cannot be live across
12203     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12204     MachineFunction &MF = DAG.getMachineFunction();
12205     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12206     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12207     auto PtrVT = getPointerTy(MF.getDataLayout());
12208     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12209     Tys = DAG.getVTList(MVT::Other);
12210     SDValue Ops[] = {
12211       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12212     };
12213     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12214         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12215         MachineMemOperand::MOStore, SSFISize, SSFISize);
12216
12217     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12218                                     Ops, Op.getValueType(), MMO);
12219     Result = DAG.getLoad(
12220         Op.getValueType(), DL, Chain, StackSlot,
12221         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12222         false, false, false, 0);
12223   }
12224
12225   return Result;
12226 }
12227
12228 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12229 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12230                                                SelectionDAG &DAG) const {
12231   // This algorithm is not obvious. Here it is what we're trying to output:
12232   /*
12233      movq       %rax,  %xmm0
12234      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12235      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12236      #ifdef __SSE3__
12237        haddpd   %xmm0, %xmm0
12238      #else
12239        pshufd   $0x4e, %xmm0, %xmm1
12240        addpd    %xmm1, %xmm0
12241      #endif
12242   */
12243
12244   SDLoc dl(Op);
12245   LLVMContext *Context = DAG.getContext();
12246
12247   // Build some magic constants.
12248   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12249   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12250   auto PtrVT = getPointerTy(DAG.getDataLayout());
12251   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12252
12253   SmallVector<Constant*,2> CV1;
12254   CV1.push_back(
12255     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12256                                       APInt(64, 0x4330000000000000ULL))));
12257   CV1.push_back(
12258     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12259                                       APInt(64, 0x4530000000000000ULL))));
12260   Constant *C1 = ConstantVector::get(CV1);
12261   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12262
12263   // Load the 64-bit value into an XMM register.
12264   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12265                             Op.getOperand(0));
12266   SDValue CLod0 =
12267       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12268                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12269                   false, false, false, 16);
12270   SDValue Unpck1 =
12271       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12272
12273   SDValue CLod1 =
12274       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12275                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12276                   false, false, false, 16);
12277   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12278   // TODO: Are there any fast-math-flags to propagate here?
12279   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12280   SDValue Result;
12281
12282   if (Subtarget->hasSSE3()) {
12283     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12284     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12285   } else {
12286     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12287     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12288                                            S2F, 0x4E, DAG);
12289     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12290                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12291   }
12292
12293   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12294                      DAG.getIntPtrConstant(0, dl));
12295 }
12296
12297 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12298 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12299                                                SelectionDAG &DAG) const {
12300   SDLoc dl(Op);
12301   // FP constant to bias correct the final result.
12302   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12303                                    MVT::f64);
12304
12305   // Load the 32-bit value into an XMM register.
12306   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12307                              Op.getOperand(0));
12308
12309   // Zero out the upper parts of the register.
12310   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12311
12312   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12313                      DAG.getBitcast(MVT::v2f64, Load),
12314                      DAG.getIntPtrConstant(0, dl));
12315
12316   // Or the load with the bias.
12317   SDValue Or = DAG.getNode(
12318       ISD::OR, dl, MVT::v2i64,
12319       DAG.getBitcast(MVT::v2i64,
12320                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12321       DAG.getBitcast(MVT::v2i64,
12322                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12323   Or =
12324       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12325                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12326
12327   // Subtract the bias.
12328   // TODO: Are there any fast-math-flags to propagate here?
12329   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12330
12331   // Handle final rounding.
12332   EVT DestVT = Op.getValueType();
12333
12334   if (DestVT.bitsLT(MVT::f64))
12335     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12336                        DAG.getIntPtrConstant(0, dl));
12337   if (DestVT.bitsGT(MVT::f64))
12338     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12339
12340   // Handle final rounding.
12341   return Sub;
12342 }
12343
12344 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12345                                      const X86Subtarget &Subtarget) {
12346   // The algorithm is the following:
12347   // #ifdef __SSE4_1__
12348   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12349   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12350   //                                 (uint4) 0x53000000, 0xaa);
12351   // #else
12352   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12353   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12354   // #endif
12355   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12356   //     return (float4) lo + fhi;
12357
12358   SDLoc DL(Op);
12359   SDValue V = Op->getOperand(0);
12360   EVT VecIntVT = V.getValueType();
12361   bool Is128 = VecIntVT == MVT::v4i32;
12362   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12363   // If we convert to something else than the supported type, e.g., to v4f64,
12364   // abort early.
12365   if (VecFloatVT != Op->getValueType(0))
12366     return SDValue();
12367
12368   unsigned NumElts = VecIntVT.getVectorNumElements();
12369   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12370          "Unsupported custom type");
12371   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12372
12373   // In the #idef/#else code, we have in common:
12374   // - The vector of constants:
12375   // -- 0x4b000000
12376   // -- 0x53000000
12377   // - A shift:
12378   // -- v >> 16
12379
12380   // Create the splat vector for 0x4b000000.
12381   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12382   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12383                            CstLow, CstLow, CstLow, CstLow};
12384   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12385                                   makeArrayRef(&CstLowArray[0], NumElts));
12386   // Create the splat vector for 0x53000000.
12387   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12388   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12389                             CstHigh, CstHigh, CstHigh, CstHigh};
12390   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12391                                    makeArrayRef(&CstHighArray[0], NumElts));
12392
12393   // Create the right shift.
12394   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12395   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12396                              CstShift, CstShift, CstShift, CstShift};
12397   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12398                                     makeArrayRef(&CstShiftArray[0], NumElts));
12399   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12400
12401   SDValue Low, High;
12402   if (Subtarget.hasSSE41()) {
12403     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12404     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12405     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12406     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12407     // Low will be bitcasted right away, so do not bother bitcasting back to its
12408     // original type.
12409     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12410                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12411     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12412     //                                 (uint4) 0x53000000, 0xaa);
12413     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12414     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12415     // High will be bitcasted right away, so do not bother bitcasting back to
12416     // its original type.
12417     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12418                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12419   } else {
12420     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12421     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12422                                      CstMask, CstMask, CstMask);
12423     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12424     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12425     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12426
12427     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12428     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12429   }
12430
12431   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12432   SDValue CstFAdd = DAG.getConstantFP(
12433       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12434   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12435                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12436   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12437                                    makeArrayRef(&CstFAddArray[0], NumElts));
12438
12439   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12440   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12441   // TODO: Are there any fast-math-flags to propagate here?
12442   SDValue FHigh =
12443       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12444   //     return (float4) lo + fhi;
12445   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12446   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12447 }
12448
12449 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12450                                                SelectionDAG &DAG) const {
12451   SDValue N0 = Op.getOperand(0);
12452   MVT SVT = N0.getSimpleValueType();
12453   SDLoc dl(Op);
12454
12455   switch (SVT.SimpleTy) {
12456   default:
12457     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12458   case MVT::v4i8:
12459   case MVT::v4i16:
12460   case MVT::v8i8:
12461   case MVT::v8i16: {
12462     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12463     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12464                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12465   }
12466   case MVT::v4i32:
12467   case MVT::v8i32:
12468     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12469   case MVT::v16i8:
12470   case MVT::v16i16:
12471     if (Subtarget->hasAVX512())
12472       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12473                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12474   }
12475   llvm_unreachable(nullptr);
12476 }
12477
12478 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12479                                            SelectionDAG &DAG) const {
12480   SDValue N0 = Op.getOperand(0);
12481   SDLoc dl(Op);
12482   auto PtrVT = getPointerTy(DAG.getDataLayout());
12483
12484   if (Op.getValueType().isVector())
12485     return lowerUINT_TO_FP_vec(Op, DAG);
12486
12487   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12488   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12489   // the optimization here.
12490   if (DAG.SignBitIsZero(N0))
12491     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12492
12493   MVT SrcVT = N0.getSimpleValueType();
12494   MVT DstVT = Op.getSimpleValueType();
12495   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12496     return LowerUINT_TO_FP_i64(Op, DAG);
12497   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12498     return LowerUINT_TO_FP_i32(Op, DAG);
12499   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12500     return SDValue();
12501
12502   // Make a 64-bit buffer, and use it to build an FILD.
12503   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12504   if (SrcVT == MVT::i32) {
12505     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12506     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12507     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12508                                   StackSlot, MachinePointerInfo(),
12509                                   false, false, 0);
12510     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12511                                   OffsetSlot, MachinePointerInfo(),
12512                                   false, false, 0);
12513     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12514     return Fild;
12515   }
12516
12517   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12518   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12519                                StackSlot, MachinePointerInfo(),
12520                                false, false, 0);
12521   // For i64 source, we need to add the appropriate power of 2 if the input
12522   // was negative.  This is the same as the optimization in
12523   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12524   // we must be careful to do the computation in x87 extended precision, not
12525   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12526   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12527   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12528       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12529       MachineMemOperand::MOLoad, 8, 8);
12530
12531   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12532   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12533   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12534                                          MVT::i64, MMO);
12535
12536   APInt FF(32, 0x5F800000ULL);
12537
12538   // Check whether the sign bit is set.
12539   SDValue SignSet = DAG.getSetCC(
12540       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12541       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12542
12543   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12544   SDValue FudgePtr = DAG.getConstantPool(
12545       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12546
12547   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12548   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12549   SDValue Four = DAG.getIntPtrConstant(4, dl);
12550   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12551                                Zero, Four);
12552   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12553
12554   // Load the value out, extending it from f32 to f80.
12555   // FIXME: Avoid the extend by constructing the right constant pool?
12556   SDValue Fudge = DAG.getExtLoad(
12557       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12558       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12559       false, false, false, 4);
12560   // Extend everything to 80 bits to force it to be done on x87.
12561   // TODO: Are there any fast-math-flags to propagate here?
12562   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12563   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12564                      DAG.getIntPtrConstant(0, dl));
12565 }
12566
12567 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12568 // is legal, or has an f16 source (which needs to be promoted to f32),
12569 // just return an <SDValue(), SDValue()> pair.
12570 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12571 // to i16, i32 or i64, and we lower it to a legal sequence.
12572 // If lowered to the final integer result we return a <result, SDValue()> pair.
12573 // Otherwise we lower it to a sequence ending with a FIST, return a
12574 // <FIST, StackSlot> pair, and the caller is responsible for loading
12575 // the final integer result from StackSlot.
12576 std::pair<SDValue,SDValue>
12577 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12578                                    bool IsSigned, bool IsReplace) const {
12579   SDLoc DL(Op);
12580
12581   EVT DstTy = Op.getValueType();
12582   EVT TheVT = Op.getOperand(0).getValueType();
12583   auto PtrVT = getPointerTy(DAG.getDataLayout());
12584
12585   if (TheVT == MVT::f16)
12586     // We need to promote the f16 to f32 before using the lowering
12587     // in this routine.
12588     return std::make_pair(SDValue(), SDValue());
12589
12590   assert((TheVT == MVT::f32 ||
12591           TheVT == MVT::f64 ||
12592           TheVT == MVT::f80) &&
12593          "Unexpected FP operand type in FP_TO_INTHelper");
12594
12595   // If using FIST to compute an unsigned i64, we'll need some fixup
12596   // to handle values above the maximum signed i64.  A FIST is always
12597   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12598   bool UnsignedFixup = !IsSigned &&
12599                        DstTy == MVT::i64 &&
12600                        (!Subtarget->is64Bit() ||
12601                         !isScalarFPTypeInSSEReg(TheVT));
12602
12603   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12604     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12605     // The low 32 bits of the fist result will have the correct uint32 result.
12606     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12607     DstTy = MVT::i64;
12608   }
12609
12610   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12611          DstTy.getSimpleVT() >= MVT::i16 &&
12612          "Unknown FP_TO_INT to lower!");
12613
12614   // These are really Legal.
12615   if (DstTy == MVT::i32 &&
12616       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12617     return std::make_pair(SDValue(), SDValue());
12618   if (Subtarget->is64Bit() &&
12619       DstTy == MVT::i64 &&
12620       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12621     return std::make_pair(SDValue(), SDValue());
12622
12623   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12624   // stack slot.
12625   MachineFunction &MF = DAG.getMachineFunction();
12626   unsigned MemSize = DstTy.getSizeInBits()/8;
12627   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12628   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12629
12630   unsigned Opc;
12631   switch (DstTy.getSimpleVT().SimpleTy) {
12632   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12633   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12634   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12635   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12636   }
12637
12638   SDValue Chain = DAG.getEntryNode();
12639   SDValue Value = Op.getOperand(0);
12640   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12641
12642   if (UnsignedFixup) {
12643     //
12644     // Conversion to unsigned i64 is implemented with a select,
12645     // depending on whether the source value fits in the range
12646     // of a signed i64.  Let Thresh be the FP equivalent of
12647     // 0x8000000000000000ULL.
12648     //
12649     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12650     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12651     //  Fist-to-mem64 FistSrc
12652     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12653     //  to XOR'ing the high 32 bits with Adjust.
12654     //
12655     // Being a power of 2, Thresh is exactly representable in all FP formats.
12656     // For X87 we'd like to use the smallest FP type for this constant, but
12657     // for DAG type consistency we have to match the FP operand type.
12658
12659     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12660     APFloat::opStatus Status = APFloat::opOK;
12661     bool LosesInfo = false;
12662     if (TheVT == MVT::f64)
12663       // The rounding mode is irrelevant as the conversion should be exact.
12664       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12665                               &LosesInfo);
12666     else if (TheVT == MVT::f80)
12667       Status = Thresh.convert(APFloat::x87DoubleExtended,
12668                               APFloat::rmNearestTiesToEven, &LosesInfo);
12669
12670     assert(Status == APFloat::opOK && !LosesInfo &&
12671            "FP conversion should have been exact");
12672
12673     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12674
12675     SDValue Cmp = DAG.getSetCC(DL,
12676                                getSetCCResultType(DAG.getDataLayout(),
12677                                                   *DAG.getContext(), TheVT),
12678                                Value, ThreshVal, ISD::SETLT);
12679     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12680                            DAG.getConstant(0, DL, MVT::i32),
12681                            DAG.getConstant(0x80000000, DL, MVT::i32));
12682     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12683     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12684                                               *DAG.getContext(), TheVT),
12685                        Value, ThreshVal, ISD::SETLT);
12686     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12687   }
12688
12689   // FIXME This causes a redundant load/store if the SSE-class value is already
12690   // in memory, such as if it is on the callstack.
12691   if (isScalarFPTypeInSSEReg(TheVT)) {
12692     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12693     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12694                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12695                          false, 0);
12696     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12697     SDValue Ops[] = {
12698       Chain, StackSlot, DAG.getValueType(TheVT)
12699     };
12700
12701     MachineMemOperand *MMO =
12702         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12703                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12704     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12705     Chain = Value.getValue(1);
12706     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12707     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12708   }
12709
12710   MachineMemOperand *MMO =
12711       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12712                               MachineMemOperand::MOStore, MemSize, MemSize);
12713
12714   if (UnsignedFixup) {
12715
12716     // Insert the FIST, load its result as two i32's,
12717     // and XOR the high i32 with Adjust.
12718
12719     SDValue FistOps[] = { Chain, Value, StackSlot };
12720     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12721                                            FistOps, DstTy, MMO);
12722
12723     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12724                                 MachinePointerInfo(),
12725                                 false, false, false, 0);
12726     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12727                                    DAG.getConstant(4, DL, PtrVT));
12728
12729     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12730                                  MachinePointerInfo(),
12731                                  false, false, false, 0);
12732     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12733
12734     if (Subtarget->is64Bit()) {
12735       // Join High32 and Low32 into a 64-bit result.
12736       // (High32 << 32) | Low32
12737       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12738       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12739       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12740                            DAG.getConstant(32, DL, MVT::i8));
12741       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12742       return std::make_pair(Result, SDValue());
12743     }
12744
12745     SDValue ResultOps[] = { Low32, High32 };
12746
12747     SDValue pair = IsReplace
12748       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12749       : DAG.getMergeValues(ResultOps, DL);
12750     return std::make_pair(pair, SDValue());
12751   } else {
12752     // Build the FP_TO_INT*_IN_MEM
12753     SDValue Ops[] = { Chain, Value, StackSlot };
12754     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12755                                            Ops, DstTy, MMO);
12756     return std::make_pair(FIST, StackSlot);
12757   }
12758 }
12759
12760 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12761                               const X86Subtarget *Subtarget) {
12762   MVT VT = Op->getSimpleValueType(0);
12763   SDValue In = Op->getOperand(0);
12764   MVT InVT = In.getSimpleValueType();
12765   SDLoc dl(Op);
12766
12767   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12768     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12769
12770   // Optimize vectors in AVX mode:
12771   //
12772   //   v8i16 -> v8i32
12773   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12774   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12775   //   Concat upper and lower parts.
12776   //
12777   //   v4i32 -> v4i64
12778   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12779   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12780   //   Concat upper and lower parts.
12781   //
12782
12783   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12784       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12785       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12786     return SDValue();
12787
12788   if (Subtarget->hasInt256())
12789     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12790
12791   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12792   SDValue Undef = DAG.getUNDEF(InVT);
12793   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12794   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12795   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12796
12797   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12798                              VT.getVectorNumElements()/2);
12799
12800   OpLo = DAG.getBitcast(HVT, OpLo);
12801   OpHi = DAG.getBitcast(HVT, OpHi);
12802
12803   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12804 }
12805
12806 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12807                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12808   MVT VT = Op->getSimpleValueType(0);
12809   SDValue In = Op->getOperand(0);
12810   MVT InVT = In.getSimpleValueType();
12811   SDLoc DL(Op);
12812   unsigned int NumElts = VT.getVectorNumElements();
12813   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12814     return SDValue();
12815
12816   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12817     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12818
12819   assert(InVT.getVectorElementType() == MVT::i1);
12820   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12821   SDValue One =
12822    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12823   SDValue Zero =
12824    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12825
12826   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12827   if (VT.is512BitVector())
12828     return V;
12829   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12830 }
12831
12832 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12833                                SelectionDAG &DAG) {
12834   if (Subtarget->hasFp256())
12835     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12836       return Res;
12837
12838   return SDValue();
12839 }
12840
12841 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12842                                 SelectionDAG &DAG) {
12843   SDLoc DL(Op);
12844   MVT VT = Op.getSimpleValueType();
12845   SDValue In = Op.getOperand(0);
12846   MVT SVT = In.getSimpleValueType();
12847
12848   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12849     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12850
12851   if (Subtarget->hasFp256())
12852     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12853       return Res;
12854
12855   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12856          VT.getVectorNumElements() != SVT.getVectorNumElements());
12857   return SDValue();
12858 }
12859
12860 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12861   SDLoc DL(Op);
12862   MVT VT = Op.getSimpleValueType();
12863   SDValue In = Op.getOperand(0);
12864   MVT InVT = In.getSimpleValueType();
12865
12866   if (VT == MVT::i1) {
12867     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12868            "Invalid scalar TRUNCATE operation");
12869     if (InVT.getSizeInBits() >= 32)
12870       return SDValue();
12871     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12872     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12873   }
12874   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12875          "Invalid TRUNCATE operation");
12876
12877   // move vector to mask - truncate solution for SKX
12878   if (VT.getVectorElementType() == MVT::i1) {
12879     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12880         Subtarget->hasBWI())
12881       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12882     if ((InVT.is256BitVector() || InVT.is128BitVector())
12883         && InVT.getScalarSizeInBits() <= 16 &&
12884         Subtarget->hasBWI() && Subtarget->hasVLX())
12885       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12886     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12887         Subtarget->hasDQI())
12888       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12889     if ((InVT.is256BitVector() || InVT.is128BitVector())
12890         && InVT.getScalarSizeInBits() >= 32 &&
12891         Subtarget->hasDQI() && Subtarget->hasVLX())
12892       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12893   }
12894
12895   if (VT.getVectorElementType() == MVT::i1) {
12896     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12897     unsigned NumElts = InVT.getVectorNumElements();
12898     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12899     if (InVT.getSizeInBits() < 512) {
12900       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12901       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12902       InVT = ExtVT;
12903     }
12904
12905     SDValue OneV =
12906      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12907     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12908     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12909   }
12910
12911   // vpmovqb/w/d, vpmovdb/w, vpmovwb
12912   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12913       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12914     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12915
12916   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12917     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12918     if (Subtarget->hasInt256()) {
12919       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12920       In = DAG.getBitcast(MVT::v8i32, In);
12921       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12922                                 ShufMask);
12923       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12924                          DAG.getIntPtrConstant(0, DL));
12925     }
12926
12927     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12928                                DAG.getIntPtrConstant(0, DL));
12929     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12930                                DAG.getIntPtrConstant(2, DL));
12931     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12932     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12933     static const int ShufMask[] = {0, 2, 4, 6};
12934     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12935   }
12936
12937   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12938     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12939     if (Subtarget->hasInt256()) {
12940       In = DAG.getBitcast(MVT::v32i8, In);
12941
12942       SmallVector<SDValue,32> pshufbMask;
12943       for (unsigned i = 0; i < 2; ++i) {
12944         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12945         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12946         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12947         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12948         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12949         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12950         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12951         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12952         for (unsigned j = 0; j < 8; ++j)
12953           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12954       }
12955       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12956       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12957       In = DAG.getBitcast(MVT::v4i64, In);
12958
12959       static const int ShufMask[] = {0,  2,  -1,  -1};
12960       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12961                                 &ShufMask[0]);
12962       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12963                        DAG.getIntPtrConstant(0, DL));
12964       return DAG.getBitcast(VT, In);
12965     }
12966
12967     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12968                                DAG.getIntPtrConstant(0, DL));
12969
12970     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12971                                DAG.getIntPtrConstant(4, DL));
12972
12973     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12974     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12975
12976     // The PSHUFB mask:
12977     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12978                                    -1, -1, -1, -1, -1, -1, -1, -1};
12979
12980     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12981     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12982     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12983
12984     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12985     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12986
12987     // The MOVLHPS Mask:
12988     static const int ShufMask2[] = {0, 1, 4, 5};
12989     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12990     return DAG.getBitcast(MVT::v8i16, res);
12991   }
12992
12993   // Handle truncation of V256 to V128 using shuffles.
12994   if (!VT.is128BitVector() || !InVT.is256BitVector())
12995     return SDValue();
12996
12997   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12998
12999   unsigned NumElems = VT.getVectorNumElements();
13000   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13001
13002   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13003   // Prepare truncation shuffle mask
13004   for (unsigned i = 0; i != NumElems; ++i)
13005     MaskVec[i] = i * 2;
13006   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13007                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13008   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13009                      DAG.getIntPtrConstant(0, DL));
13010 }
13011
13012 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13013                                            SelectionDAG &DAG) const {
13014   assert(!Op.getSimpleValueType().isVector());
13015
13016   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13017     /*IsSigned=*/ true, /*IsReplace=*/ false);
13018   SDValue FIST = Vals.first, StackSlot = Vals.second;
13019   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13020   if (!FIST.getNode())
13021     return Op;
13022
13023   if (StackSlot.getNode())
13024     // Load the result.
13025     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13026                        FIST, StackSlot, MachinePointerInfo(),
13027                        false, false, false, 0);
13028
13029   // The node is the result.
13030   return FIST;
13031 }
13032
13033 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13034                                            SelectionDAG &DAG) const {
13035   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13036     /*IsSigned=*/ false, /*IsReplace=*/ false);
13037   SDValue FIST = Vals.first, StackSlot = Vals.second;
13038   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13039   if (!FIST.getNode())
13040     return Op;
13041
13042   if (StackSlot.getNode())
13043     // Load the result.
13044     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13045                        FIST, StackSlot, MachinePointerInfo(),
13046                        false, false, false, 0);
13047
13048   // The node is the result.
13049   return FIST;
13050 }
13051
13052 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13053   SDLoc DL(Op);
13054   MVT VT = Op.getSimpleValueType();
13055   SDValue In = Op.getOperand(0);
13056   MVT SVT = In.getSimpleValueType();
13057
13058   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13059
13060   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13061                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13062                                  In, DAG.getUNDEF(SVT)));
13063 }
13064
13065 /// The only differences between FABS and FNEG are the mask and the logic op.
13066 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13067 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13068   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13069          "Wrong opcode for lowering FABS or FNEG.");
13070
13071   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13072
13073   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13074   // into an FNABS. We'll lower the FABS after that if it is still in use.
13075   if (IsFABS)
13076     for (SDNode *User : Op->uses())
13077       if (User->getOpcode() == ISD::FNEG)
13078         return Op;
13079
13080   SDLoc dl(Op);
13081   MVT VT = Op.getSimpleValueType();
13082
13083   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13084   // decide if we should generate a 16-byte constant mask when we only need 4 or
13085   // 8 bytes for the scalar case.
13086
13087   MVT LogicVT;
13088   MVT EltVT;
13089   unsigned NumElts;
13090
13091   if (VT.isVector()) {
13092     LogicVT = VT;
13093     EltVT = VT.getVectorElementType();
13094     NumElts = VT.getVectorNumElements();
13095   } else {
13096     // There are no scalar bitwise logical SSE/AVX instructions, so we
13097     // generate a 16-byte vector constant and logic op even for the scalar case.
13098     // Using a 16-byte mask allows folding the load of the mask with
13099     // the logic op, so it can save (~4 bytes) on code size.
13100     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13101     EltVT = VT;
13102     NumElts = (VT == MVT::f64) ? 2 : 4;
13103   }
13104
13105   unsigned EltBits = EltVT.getSizeInBits();
13106   LLVMContext *Context = DAG.getContext();
13107   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13108   APInt MaskElt =
13109     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13110   Constant *C = ConstantInt::get(*Context, MaskElt);
13111   C = ConstantVector::getSplat(NumElts, C);
13112   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13113   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13114   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13115   SDValue Mask =
13116       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13117                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13118                   false, false, false, Alignment);
13119
13120   SDValue Op0 = Op.getOperand(0);
13121   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13122   unsigned LogicOp =
13123     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13124   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13125
13126   if (VT.isVector())
13127     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13128
13129   // For the scalar case extend to a 128-bit vector, perform the logic op,
13130   // and extract the scalar result back out.
13131   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13132   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13133   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13134                      DAG.getIntPtrConstant(0, dl));
13135 }
13136
13137 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13138   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13139   LLVMContext *Context = DAG.getContext();
13140   SDValue Op0 = Op.getOperand(0);
13141   SDValue Op1 = Op.getOperand(1);
13142   SDLoc dl(Op);
13143   MVT VT = Op.getSimpleValueType();
13144   MVT SrcVT = Op1.getSimpleValueType();
13145
13146   // If second operand is smaller, extend it first.
13147   if (SrcVT.bitsLT(VT)) {
13148     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13149     SrcVT = VT;
13150   }
13151   // And if it is bigger, shrink it first.
13152   if (SrcVT.bitsGT(VT)) {
13153     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13154     SrcVT = VT;
13155   }
13156
13157   // At this point the operands and the result should have the same
13158   // type, and that won't be f80 since that is not custom lowered.
13159
13160   const fltSemantics &Sem =
13161       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13162   const unsigned SizeInBits = VT.getSizeInBits();
13163
13164   SmallVector<Constant *, 4> CV(
13165       VT == MVT::f64 ? 2 : 4,
13166       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13167
13168   // First, clear all bits but the sign bit from the second operand (sign).
13169   CV[0] = ConstantFP::get(*Context,
13170                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13171   Constant *C = ConstantVector::get(CV);
13172   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13173   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13174
13175   // Perform all logic operations as 16-byte vectors because there are no
13176   // scalar FP logic instructions in SSE. This allows load folding of the
13177   // constants into the logic instructions.
13178   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13179   SDValue Mask1 =
13180       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13181                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13182                   false, false, false, 16);
13183   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13184   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13185
13186   // Next, clear the sign bit from the first operand (magnitude).
13187   // If it's a constant, we can clear it here.
13188   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13189     APFloat APF = Op0CN->getValueAPF();
13190     // If the magnitude is a positive zero, the sign bit alone is enough.
13191     if (APF.isPosZero())
13192       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13193                          DAG.getIntPtrConstant(0, dl));
13194     APF.clearSign();
13195     CV[0] = ConstantFP::get(*Context, APF);
13196   } else {
13197     CV[0] = ConstantFP::get(
13198         *Context,
13199         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13200   }
13201   C = ConstantVector::get(CV);
13202   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13203   SDValue Val =
13204       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13205                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13206                   false, false, false, 16);
13207   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13208   if (!isa<ConstantFPSDNode>(Op0)) {
13209     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13210     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13211   }
13212   // OR the magnitude value with the sign bit.
13213   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13214   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13215                      DAG.getIntPtrConstant(0, dl));
13216 }
13217
13218 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13219   SDValue N0 = Op.getOperand(0);
13220   SDLoc dl(Op);
13221   MVT VT = Op.getSimpleValueType();
13222
13223   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13224   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13225                                   DAG.getConstant(1, dl, VT));
13226   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13227 }
13228
13229 // Check whether an OR'd tree is PTEST-able.
13230 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13231                                       SelectionDAG &DAG) {
13232   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13233
13234   if (!Subtarget->hasSSE41())
13235     return SDValue();
13236
13237   if (!Op->hasOneUse())
13238     return SDValue();
13239
13240   SDNode *N = Op.getNode();
13241   SDLoc DL(N);
13242
13243   SmallVector<SDValue, 8> Opnds;
13244   DenseMap<SDValue, unsigned> VecInMap;
13245   SmallVector<SDValue, 8> VecIns;
13246   EVT VT = MVT::Other;
13247
13248   // Recognize a special case where a vector is casted into wide integer to
13249   // test all 0s.
13250   Opnds.push_back(N->getOperand(0));
13251   Opnds.push_back(N->getOperand(1));
13252
13253   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13254     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13255     // BFS traverse all OR'd operands.
13256     if (I->getOpcode() == ISD::OR) {
13257       Opnds.push_back(I->getOperand(0));
13258       Opnds.push_back(I->getOperand(1));
13259       // Re-evaluate the number of nodes to be traversed.
13260       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13261       continue;
13262     }
13263
13264     // Quit if a non-EXTRACT_VECTOR_ELT
13265     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13266       return SDValue();
13267
13268     // Quit if without a constant index.
13269     SDValue Idx = I->getOperand(1);
13270     if (!isa<ConstantSDNode>(Idx))
13271       return SDValue();
13272
13273     SDValue ExtractedFromVec = I->getOperand(0);
13274     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13275     if (M == VecInMap.end()) {
13276       VT = ExtractedFromVec.getValueType();
13277       // Quit if not 128/256-bit vector.
13278       if (!VT.is128BitVector() && !VT.is256BitVector())
13279         return SDValue();
13280       // Quit if not the same type.
13281       if (VecInMap.begin() != VecInMap.end() &&
13282           VT != VecInMap.begin()->first.getValueType())
13283         return SDValue();
13284       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13285       VecIns.push_back(ExtractedFromVec);
13286     }
13287     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13288   }
13289
13290   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13291          "Not extracted from 128-/256-bit vector.");
13292
13293   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13294
13295   for (DenseMap<SDValue, unsigned>::const_iterator
13296         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13297     // Quit if not all elements are used.
13298     if (I->second != FullMask)
13299       return SDValue();
13300   }
13301
13302   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13303
13304   // Cast all vectors into TestVT for PTEST.
13305   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13306     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13307
13308   // If more than one full vectors are evaluated, OR them first before PTEST.
13309   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13310     // Each iteration will OR 2 nodes and append the result until there is only
13311     // 1 node left, i.e. the final OR'd value of all vectors.
13312     SDValue LHS = VecIns[Slot];
13313     SDValue RHS = VecIns[Slot + 1];
13314     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13315   }
13316
13317   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13318                      VecIns.back(), VecIns.back());
13319 }
13320
13321 /// \brief return true if \c Op has a use that doesn't just read flags.
13322 static bool hasNonFlagsUse(SDValue Op) {
13323   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13324        ++UI) {
13325     SDNode *User = *UI;
13326     unsigned UOpNo = UI.getOperandNo();
13327     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13328       // Look pass truncate.
13329       UOpNo = User->use_begin().getOperandNo();
13330       User = *User->use_begin();
13331     }
13332
13333     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13334         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13335       return true;
13336   }
13337   return false;
13338 }
13339
13340 /// Emit nodes that will be selected as "test Op0,Op0", or something
13341 /// equivalent.
13342 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13343                                     SelectionDAG &DAG) const {
13344   if (Op.getValueType() == MVT::i1) {
13345     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13346     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13347                        DAG.getConstant(0, dl, MVT::i8));
13348   }
13349   // CF and OF aren't always set the way we want. Determine which
13350   // of these we need.
13351   bool NeedCF = false;
13352   bool NeedOF = false;
13353   switch (X86CC) {
13354   default: break;
13355   case X86::COND_A: case X86::COND_AE:
13356   case X86::COND_B: case X86::COND_BE:
13357     NeedCF = true;
13358     break;
13359   case X86::COND_G: case X86::COND_GE:
13360   case X86::COND_L: case X86::COND_LE:
13361   case X86::COND_O: case X86::COND_NO: {
13362     // Check if we really need to set the
13363     // Overflow flag. If NoSignedWrap is present
13364     // that is not actually needed.
13365     switch (Op->getOpcode()) {
13366     case ISD::ADD:
13367     case ISD::SUB:
13368     case ISD::MUL:
13369     case ISD::SHL: {
13370       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13371       if (BinNode->Flags.hasNoSignedWrap())
13372         break;
13373     }
13374     default:
13375       NeedOF = true;
13376       break;
13377     }
13378     break;
13379   }
13380   }
13381   // See if we can use the EFLAGS value from the operand instead of
13382   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13383   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13384   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13385     // Emit a CMP with 0, which is the TEST pattern.
13386     //if (Op.getValueType() == MVT::i1)
13387     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13388     //                     DAG.getConstant(0, MVT::i1));
13389     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13390                        DAG.getConstant(0, dl, Op.getValueType()));
13391   }
13392   unsigned Opcode = 0;
13393   unsigned NumOperands = 0;
13394
13395   // Truncate operations may prevent the merge of the SETCC instruction
13396   // and the arithmetic instruction before it. Attempt to truncate the operands
13397   // of the arithmetic instruction and use a reduced bit-width instruction.
13398   bool NeedTruncation = false;
13399   SDValue ArithOp = Op;
13400   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13401     SDValue Arith = Op->getOperand(0);
13402     // Both the trunc and the arithmetic op need to have one user each.
13403     if (Arith->hasOneUse())
13404       switch (Arith.getOpcode()) {
13405         default: break;
13406         case ISD::ADD:
13407         case ISD::SUB:
13408         case ISD::AND:
13409         case ISD::OR:
13410         case ISD::XOR: {
13411           NeedTruncation = true;
13412           ArithOp = Arith;
13413         }
13414       }
13415   }
13416
13417   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13418   // which may be the result of a CAST.  We use the variable 'Op', which is the
13419   // non-casted variable when we check for possible users.
13420   switch (ArithOp.getOpcode()) {
13421   case ISD::ADD:
13422     // Due to an isel shortcoming, be conservative if this add is likely to be
13423     // selected as part of a load-modify-store instruction. When the root node
13424     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13425     // uses of other nodes in the match, such as the ADD in this case. This
13426     // leads to the ADD being left around and reselected, with the result being
13427     // two adds in the output.  Alas, even if none our users are stores, that
13428     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13429     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13430     // climbing the DAG back to the root, and it doesn't seem to be worth the
13431     // effort.
13432     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13433          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13434       if (UI->getOpcode() != ISD::CopyToReg &&
13435           UI->getOpcode() != ISD::SETCC &&
13436           UI->getOpcode() != ISD::STORE)
13437         goto default_case;
13438
13439     if (ConstantSDNode *C =
13440         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13441       // An add of one will be selected as an INC.
13442       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13443         Opcode = X86ISD::INC;
13444         NumOperands = 1;
13445         break;
13446       }
13447
13448       // An add of negative one (subtract of one) will be selected as a DEC.
13449       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13450         Opcode = X86ISD::DEC;
13451         NumOperands = 1;
13452         break;
13453       }
13454     }
13455
13456     // Otherwise use a regular EFLAGS-setting add.
13457     Opcode = X86ISD::ADD;
13458     NumOperands = 2;
13459     break;
13460   case ISD::SHL:
13461   case ISD::SRL:
13462     // If we have a constant logical shift that's only used in a comparison
13463     // against zero turn it into an equivalent AND. This allows turning it into
13464     // a TEST instruction later.
13465     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13466         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13467       EVT VT = Op.getValueType();
13468       unsigned BitWidth = VT.getSizeInBits();
13469       unsigned ShAmt = Op->getConstantOperandVal(1);
13470       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13471         break;
13472       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13473                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13474                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13475       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13476         break;
13477       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13478                                 DAG.getConstant(Mask, dl, VT));
13479       DAG.ReplaceAllUsesWith(Op, New);
13480       Op = New;
13481     }
13482     break;
13483
13484   case ISD::AND:
13485     // If the primary and result isn't used, don't bother using X86ISD::AND,
13486     // because a TEST instruction will be better.
13487     if (!hasNonFlagsUse(Op))
13488       break;
13489     // FALL THROUGH
13490   case ISD::SUB:
13491   case ISD::OR:
13492   case ISD::XOR:
13493     // Due to the ISEL shortcoming noted above, be conservative if this op is
13494     // likely to be selected as part of a load-modify-store instruction.
13495     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13496            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13497       if (UI->getOpcode() == ISD::STORE)
13498         goto default_case;
13499
13500     // Otherwise use a regular EFLAGS-setting instruction.
13501     switch (ArithOp.getOpcode()) {
13502     default: llvm_unreachable("unexpected operator!");
13503     case ISD::SUB: Opcode = X86ISD::SUB; break;
13504     case ISD::XOR: Opcode = X86ISD::XOR; break;
13505     case ISD::AND: Opcode = X86ISD::AND; break;
13506     case ISD::OR: {
13507       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13508         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13509         if (EFLAGS.getNode())
13510           return EFLAGS;
13511       }
13512       Opcode = X86ISD::OR;
13513       break;
13514     }
13515     }
13516
13517     NumOperands = 2;
13518     break;
13519   case X86ISD::ADD:
13520   case X86ISD::SUB:
13521   case X86ISD::INC:
13522   case X86ISD::DEC:
13523   case X86ISD::OR:
13524   case X86ISD::XOR:
13525   case X86ISD::AND:
13526     return SDValue(Op.getNode(), 1);
13527   default:
13528   default_case:
13529     break;
13530   }
13531
13532   // If we found that truncation is beneficial, perform the truncation and
13533   // update 'Op'.
13534   if (NeedTruncation) {
13535     EVT VT = Op.getValueType();
13536     SDValue WideVal = Op->getOperand(0);
13537     EVT WideVT = WideVal.getValueType();
13538     unsigned ConvertedOp = 0;
13539     // Use a target machine opcode to prevent further DAGCombine
13540     // optimizations that may separate the arithmetic operations
13541     // from the setcc node.
13542     switch (WideVal.getOpcode()) {
13543       default: break;
13544       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13545       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13546       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13547       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13548       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13549     }
13550
13551     if (ConvertedOp) {
13552       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13553       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13554         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13555         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13556         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13557       }
13558     }
13559   }
13560
13561   if (Opcode == 0)
13562     // Emit a CMP with 0, which is the TEST pattern.
13563     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13564                        DAG.getConstant(0, dl, Op.getValueType()));
13565
13566   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13567   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13568
13569   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13570   DAG.ReplaceAllUsesWith(Op, New);
13571   return SDValue(New.getNode(), 1);
13572 }
13573
13574 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13575 /// equivalent.
13576 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13577                                    SDLoc dl, SelectionDAG &DAG) const {
13578   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13579     if (C->getAPIntValue() == 0)
13580       return EmitTest(Op0, X86CC, dl, DAG);
13581
13582      if (Op0.getValueType() == MVT::i1)
13583        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13584   }
13585
13586   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13587        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13588     // Do the comparison at i32 if it's smaller, besides the Atom case.
13589     // This avoids subregister aliasing issues. Keep the smaller reference
13590     // if we're optimizing for size, however, as that'll allow better folding
13591     // of memory operations.
13592     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13593         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13594         !Subtarget->isAtom()) {
13595       unsigned ExtendOp =
13596           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13597       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13598       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13599     }
13600     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13601     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13602     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13603                               Op0, Op1);
13604     return SDValue(Sub.getNode(), 1);
13605   }
13606   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13607 }
13608
13609 /// Convert a comparison if required by the subtarget.
13610 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13611                                                  SelectionDAG &DAG) const {
13612   // If the subtarget does not support the FUCOMI instruction, floating-point
13613   // comparisons have to be converted.
13614   if (Subtarget->hasCMov() ||
13615       Cmp.getOpcode() != X86ISD::CMP ||
13616       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13617       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13618     return Cmp;
13619
13620   // The instruction selector will select an FUCOM instruction instead of
13621   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13622   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13623   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13624   SDLoc dl(Cmp);
13625   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13626   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13627   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13628                             DAG.getConstant(8, dl, MVT::i8));
13629   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13630   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13631 }
13632
13633 /// The minimum architected relative accuracy is 2^-12. We need one
13634 /// Newton-Raphson step to have a good float result (24 bits of precision).
13635 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13636                                             DAGCombinerInfo &DCI,
13637                                             unsigned &RefinementSteps,
13638                                             bool &UseOneConstNR) const {
13639   EVT VT = Op.getValueType();
13640   const char *RecipOp;
13641
13642   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13643   // TODO: Add support for AVX512 (v16f32).
13644   // It is likely not profitable to do this for f64 because a double-precision
13645   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13646   // instructions: convert to single, rsqrtss, convert back to double, refine
13647   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13648   // along with FMA, this could be a throughput win.
13649   if (VT == MVT::f32 && Subtarget->hasSSE1())
13650     RecipOp = "sqrtf";
13651   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13652            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13653     RecipOp = "vec-sqrtf";
13654   else
13655     return SDValue();
13656
13657   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13658   if (!Recips.isEnabled(RecipOp))
13659     return SDValue();
13660
13661   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13662   UseOneConstNR = false;
13663   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13664 }
13665
13666 /// The minimum architected relative accuracy is 2^-12. We need one
13667 /// Newton-Raphson step to have a good float result (24 bits of precision).
13668 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13669                                             DAGCombinerInfo &DCI,
13670                                             unsigned &RefinementSteps) const {
13671   EVT VT = Op.getValueType();
13672   const char *RecipOp;
13673
13674   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13675   // TODO: Add support for AVX512 (v16f32).
13676   // It is likely not profitable to do this for f64 because a double-precision
13677   // reciprocal estimate with refinement on x86 prior to FMA requires
13678   // 15 instructions: convert to single, rcpss, convert back to double, refine
13679   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13680   // along with FMA, this could be a throughput win.
13681   if (VT == MVT::f32 && Subtarget->hasSSE1())
13682     RecipOp = "divf";
13683   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13684            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13685     RecipOp = "vec-divf";
13686   else
13687     return SDValue();
13688
13689   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13690   if (!Recips.isEnabled(RecipOp))
13691     return SDValue();
13692
13693   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13694   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13695 }
13696
13697 /// If we have at least two divisions that use the same divisor, convert to
13698 /// multplication by a reciprocal. This may need to be adjusted for a given
13699 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13700 /// This is because we still need one division to calculate the reciprocal and
13701 /// then we need two multiplies by that reciprocal as replacements for the
13702 /// original divisions.
13703 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13704   return 2;
13705 }
13706
13707 static bool isAllOnes(SDValue V) {
13708   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13709   return C && C->isAllOnesValue();
13710 }
13711
13712 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13713 /// if it's possible.
13714 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13715                                      SDLoc dl, SelectionDAG &DAG) const {
13716   SDValue Op0 = And.getOperand(0);
13717   SDValue Op1 = And.getOperand(1);
13718   if (Op0.getOpcode() == ISD::TRUNCATE)
13719     Op0 = Op0.getOperand(0);
13720   if (Op1.getOpcode() == ISD::TRUNCATE)
13721     Op1 = Op1.getOperand(0);
13722
13723   SDValue LHS, RHS;
13724   if (Op1.getOpcode() == ISD::SHL)
13725     std::swap(Op0, Op1);
13726   if (Op0.getOpcode() == ISD::SHL) {
13727     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13728       if (And00C->getZExtValue() == 1) {
13729         // If we looked past a truncate, check that it's only truncating away
13730         // known zeros.
13731         unsigned BitWidth = Op0.getValueSizeInBits();
13732         unsigned AndBitWidth = And.getValueSizeInBits();
13733         if (BitWidth > AndBitWidth) {
13734           APInt Zeros, Ones;
13735           DAG.computeKnownBits(Op0, Zeros, Ones);
13736           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13737             return SDValue();
13738         }
13739         LHS = Op1;
13740         RHS = Op0.getOperand(1);
13741       }
13742   } else if (Op1.getOpcode() == ISD::Constant) {
13743     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13744     uint64_t AndRHSVal = AndRHS->getZExtValue();
13745     SDValue AndLHS = Op0;
13746
13747     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13748       LHS = AndLHS.getOperand(0);
13749       RHS = AndLHS.getOperand(1);
13750     }
13751
13752     // Use BT if the immediate can't be encoded in a TEST instruction.
13753     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13754       LHS = AndLHS;
13755       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13756     }
13757   }
13758
13759   if (LHS.getNode()) {
13760     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13761     // instruction.  Since the shift amount is in-range-or-undefined, we know
13762     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13763     // the encoding for the i16 version is larger than the i32 version.
13764     // Also promote i16 to i32 for performance / code size reason.
13765     if (LHS.getValueType() == MVT::i8 ||
13766         LHS.getValueType() == MVT::i16)
13767       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13768
13769     // If the operand types disagree, extend the shift amount to match.  Since
13770     // BT ignores high bits (like shifts) we can use anyextend.
13771     if (LHS.getValueType() != RHS.getValueType())
13772       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13773
13774     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13775     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13776     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13777                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13778   }
13779
13780   return SDValue();
13781 }
13782
13783 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13784 /// mask CMPs.
13785 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13786                               SDValue &Op1) {
13787   unsigned SSECC;
13788   bool Swap = false;
13789
13790   // SSE Condition code mapping:
13791   //  0 - EQ
13792   //  1 - LT
13793   //  2 - LE
13794   //  3 - UNORD
13795   //  4 - NEQ
13796   //  5 - NLT
13797   //  6 - NLE
13798   //  7 - ORD
13799   switch (SetCCOpcode) {
13800   default: llvm_unreachable("Unexpected SETCC condition");
13801   case ISD::SETOEQ:
13802   case ISD::SETEQ:  SSECC = 0; break;
13803   case ISD::SETOGT:
13804   case ISD::SETGT:  Swap = true; // Fallthrough
13805   case ISD::SETLT:
13806   case ISD::SETOLT: SSECC = 1; break;
13807   case ISD::SETOGE:
13808   case ISD::SETGE:  Swap = true; // Fallthrough
13809   case ISD::SETLE:
13810   case ISD::SETOLE: SSECC = 2; break;
13811   case ISD::SETUO:  SSECC = 3; break;
13812   case ISD::SETUNE:
13813   case ISD::SETNE:  SSECC = 4; break;
13814   case ISD::SETULE: Swap = true; // Fallthrough
13815   case ISD::SETUGE: SSECC = 5; break;
13816   case ISD::SETULT: Swap = true; // Fallthrough
13817   case ISD::SETUGT: SSECC = 6; break;
13818   case ISD::SETO:   SSECC = 7; break;
13819   case ISD::SETUEQ:
13820   case ISD::SETONE: SSECC = 8; break;
13821   }
13822   if (Swap)
13823     std::swap(Op0, Op1);
13824
13825   return SSECC;
13826 }
13827
13828 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13829 // ones, and then concatenate the result back.
13830 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13831   MVT VT = Op.getSimpleValueType();
13832
13833   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13834          "Unsupported value type for operation");
13835
13836   unsigned NumElems = VT.getVectorNumElements();
13837   SDLoc dl(Op);
13838   SDValue CC = Op.getOperand(2);
13839
13840   // Extract the LHS vectors
13841   SDValue LHS = Op.getOperand(0);
13842   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13843   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13844
13845   // Extract the RHS vectors
13846   SDValue RHS = Op.getOperand(1);
13847   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13848   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13849
13850   // Issue the operation on the smaller types and concatenate the result back
13851   MVT EltVT = VT.getVectorElementType();
13852   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13853   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13854                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13855                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13856 }
13857
13858 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13859   SDValue Op0 = Op.getOperand(0);
13860   SDValue Op1 = Op.getOperand(1);
13861   SDValue CC = Op.getOperand(2);
13862   MVT VT = Op.getSimpleValueType();
13863   SDLoc dl(Op);
13864
13865   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13866          "Unexpected type for boolean compare operation");
13867   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13868   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13869                                DAG.getConstant(-1, dl, VT));
13870   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13871                                DAG.getConstant(-1, dl, VT));
13872   switch (SetCCOpcode) {
13873   default: llvm_unreachable("Unexpected SETCC condition");
13874   case ISD::SETEQ:
13875     // (x == y) -> ~(x ^ y)
13876     return DAG.getNode(ISD::XOR, dl, VT,
13877                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13878                        DAG.getConstant(-1, dl, VT));
13879   case ISD::SETNE:
13880     // (x != y) -> (x ^ y)
13881     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13882   case ISD::SETUGT:
13883   case ISD::SETGT:
13884     // (x > y) -> (x & ~y)
13885     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13886   case ISD::SETULT:
13887   case ISD::SETLT:
13888     // (x < y) -> (~x & y)
13889     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13890   case ISD::SETULE:
13891   case ISD::SETLE:
13892     // (x <= y) -> (~x | y)
13893     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13894   case ISD::SETUGE:
13895   case ISD::SETGE:
13896     // (x >=y) -> (x | ~y)
13897     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13898   }
13899 }
13900
13901 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13902                                      const X86Subtarget *Subtarget) {
13903   SDValue Op0 = Op.getOperand(0);
13904   SDValue Op1 = Op.getOperand(1);
13905   SDValue CC = Op.getOperand(2);
13906   MVT VT = Op.getSimpleValueType();
13907   SDLoc dl(Op);
13908
13909   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13910          Op.getValueType().getScalarType() == MVT::i1 &&
13911          "Cannot set masked compare for this operation");
13912
13913   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13914   unsigned  Opc = 0;
13915   bool Unsigned = false;
13916   bool Swap = false;
13917   unsigned SSECC;
13918   switch (SetCCOpcode) {
13919   default: llvm_unreachable("Unexpected SETCC condition");
13920   case ISD::SETNE:  SSECC = 4; break;
13921   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13922   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13923   case ISD::SETLT:  Swap = true; //fall-through
13924   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13925   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13926   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13927   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13928   case ISD::SETULE: Unsigned = true; //fall-through
13929   case ISD::SETLE:  SSECC = 2; break;
13930   }
13931
13932   if (Swap)
13933     std::swap(Op0, Op1);
13934   if (Opc)
13935     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13936   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13937   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13938                      DAG.getConstant(SSECC, dl, MVT::i8));
13939 }
13940
13941 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13942 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13943 /// return an empty value.
13944 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13945 {
13946   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13947   if (!BV)
13948     return SDValue();
13949
13950   MVT VT = Op1.getSimpleValueType();
13951   MVT EVT = VT.getVectorElementType();
13952   unsigned n = VT.getVectorNumElements();
13953   SmallVector<SDValue, 8> ULTOp1;
13954
13955   for (unsigned i = 0; i < n; ++i) {
13956     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13957     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13958       return SDValue();
13959
13960     // Avoid underflow.
13961     APInt Val = Elt->getAPIntValue();
13962     if (Val == 0)
13963       return SDValue();
13964
13965     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13966   }
13967
13968   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13969 }
13970
13971 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13972                            SelectionDAG &DAG) {
13973   SDValue Op0 = Op.getOperand(0);
13974   SDValue Op1 = Op.getOperand(1);
13975   SDValue CC = Op.getOperand(2);
13976   MVT VT = Op.getSimpleValueType();
13977   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13978   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13979   SDLoc dl(Op);
13980
13981   if (isFP) {
13982 #ifndef NDEBUG
13983     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13984     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13985 #endif
13986
13987     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13988     unsigned Opc = X86ISD::CMPP;
13989     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13990       assert(VT.getVectorNumElements() <= 16);
13991       Opc = X86ISD::CMPM;
13992     }
13993     // In the two special cases we can't handle, emit two comparisons.
13994     if (SSECC == 8) {
13995       unsigned CC0, CC1;
13996       unsigned CombineOpc;
13997       if (SetCCOpcode == ISD::SETUEQ) {
13998         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13999       } else {
14000         assert(SetCCOpcode == ISD::SETONE);
14001         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14002       }
14003
14004       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14005                                  DAG.getConstant(CC0, dl, MVT::i8));
14006       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14007                                  DAG.getConstant(CC1, dl, MVT::i8));
14008       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14009     }
14010     // Handle all other FP comparisons here.
14011     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14012                        DAG.getConstant(SSECC, dl, MVT::i8));
14013   }
14014
14015   // Break 256-bit integer vector compare into smaller ones.
14016   if (VT.is256BitVector() && !Subtarget->hasInt256())
14017     return Lower256IntVSETCC(Op, DAG);
14018
14019   EVT OpVT = Op1.getValueType();
14020   if (OpVT.getVectorElementType() == MVT::i1)
14021     return LowerBoolVSETCC_AVX512(Op, DAG);
14022
14023   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14024   if (Subtarget->hasAVX512()) {
14025     if (Op1.getValueType().is512BitVector() ||
14026         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14027         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14028       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14029
14030     // In AVX-512 architecture setcc returns mask with i1 elements,
14031     // But there is no compare instruction for i8 and i16 elements in KNL.
14032     // We are not talking about 512-bit operands in this case, these
14033     // types are illegal.
14034     if (MaskResult &&
14035         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14036          OpVT.getVectorElementType().getSizeInBits() >= 8))
14037       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14038                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14039   }
14040
14041   // We are handling one of the integer comparisons here.  Since SSE only has
14042   // GT and EQ comparisons for integer, swapping operands and multiple
14043   // operations may be required for some comparisons.
14044   unsigned Opc;
14045   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14046   bool Subus = false;
14047
14048   switch (SetCCOpcode) {
14049   default: llvm_unreachable("Unexpected SETCC condition");
14050   case ISD::SETNE:  Invert = true;
14051   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14052   case ISD::SETLT:  Swap = true;
14053   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14054   case ISD::SETGE:  Swap = true;
14055   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14056                     Invert = true; break;
14057   case ISD::SETULT: Swap = true;
14058   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14059                     FlipSigns = true; break;
14060   case ISD::SETUGE: Swap = true;
14061   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14062                     FlipSigns = true; Invert = true; break;
14063   }
14064
14065   // Special case: Use min/max operations for SETULE/SETUGE
14066   MVT VET = VT.getVectorElementType();
14067   bool hasMinMax =
14068        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14069     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14070
14071   if (hasMinMax) {
14072     switch (SetCCOpcode) {
14073     default: break;
14074     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14075     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14076     }
14077
14078     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14079   }
14080
14081   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14082   if (!MinMax && hasSubus) {
14083     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14084     // Op0 u<= Op1:
14085     //   t = psubus Op0, Op1
14086     //   pcmpeq t, <0..0>
14087     switch (SetCCOpcode) {
14088     default: break;
14089     case ISD::SETULT: {
14090       // If the comparison is against a constant we can turn this into a
14091       // setule.  With psubus, setule does not require a swap.  This is
14092       // beneficial because the constant in the register is no longer
14093       // destructed as the destination so it can be hoisted out of a loop.
14094       // Only do this pre-AVX since vpcmp* is no longer destructive.
14095       if (Subtarget->hasAVX())
14096         break;
14097       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14098       if (ULEOp1.getNode()) {
14099         Op1 = ULEOp1;
14100         Subus = true; Invert = false; Swap = false;
14101       }
14102       break;
14103     }
14104     // Psubus is better than flip-sign because it requires no inversion.
14105     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14106     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14107     }
14108
14109     if (Subus) {
14110       Opc = X86ISD::SUBUS;
14111       FlipSigns = false;
14112     }
14113   }
14114
14115   if (Swap)
14116     std::swap(Op0, Op1);
14117
14118   // Check that the operation in question is available (most are plain SSE2,
14119   // but PCMPGTQ and PCMPEQQ have different requirements).
14120   if (VT == MVT::v2i64) {
14121     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14122       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14123
14124       // First cast everything to the right type.
14125       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14126       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14127
14128       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14129       // bits of the inputs before performing those operations. The lower
14130       // compare is always unsigned.
14131       SDValue SB;
14132       if (FlipSigns) {
14133         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14134       } else {
14135         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14136         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14137         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14138                          Sign, Zero, Sign, Zero);
14139       }
14140       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14141       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14142
14143       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14144       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14145       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14146
14147       // Create masks for only the low parts/high parts of the 64 bit integers.
14148       static const int MaskHi[] = { 1, 1, 3, 3 };
14149       static const int MaskLo[] = { 0, 0, 2, 2 };
14150       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14151       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14152       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14153
14154       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14155       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14156
14157       if (Invert)
14158         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14159
14160       return DAG.getBitcast(VT, Result);
14161     }
14162
14163     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14164       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14165       // pcmpeqd + pshufd + pand.
14166       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14167
14168       // First cast everything to the right type.
14169       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14170       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14171
14172       // Do the compare.
14173       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14174
14175       // Make sure the lower and upper halves are both all-ones.
14176       static const int Mask[] = { 1, 0, 3, 2 };
14177       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14178       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14179
14180       if (Invert)
14181         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14182
14183       return DAG.getBitcast(VT, Result);
14184     }
14185   }
14186
14187   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14188   // bits of the inputs before performing those operations.
14189   if (FlipSigns) {
14190     EVT EltVT = VT.getVectorElementType();
14191     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14192                                  VT);
14193     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14194     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14195   }
14196
14197   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14198
14199   // If the logical-not of the result is required, perform that now.
14200   if (Invert)
14201     Result = DAG.getNOT(dl, Result, VT);
14202
14203   if (MinMax)
14204     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14205
14206   if (Subus)
14207     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14208                          getZeroVector(VT, Subtarget, DAG, dl));
14209
14210   return Result;
14211 }
14212
14213 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14214
14215   MVT VT = Op.getSimpleValueType();
14216
14217   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14218
14219   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14220          && "SetCC type must be 8-bit or 1-bit integer");
14221   SDValue Op0 = Op.getOperand(0);
14222   SDValue Op1 = Op.getOperand(1);
14223   SDLoc dl(Op);
14224   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14225
14226   // Optimize to BT if possible.
14227   // Lower (X & (1 << N)) == 0 to BT(X, N).
14228   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14229   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14230   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14231       Op1.getOpcode() == ISD::Constant &&
14232       cast<ConstantSDNode>(Op1)->isNullValue() &&
14233       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14234     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14235     if (NewSetCC.getNode()) {
14236       if (VT == MVT::i1)
14237         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14238       return NewSetCC;
14239     }
14240   }
14241
14242   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14243   // these.
14244   if (Op1.getOpcode() == ISD::Constant &&
14245       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14246        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14247       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14248
14249     // If the input is a setcc, then reuse the input setcc or use a new one with
14250     // the inverted condition.
14251     if (Op0.getOpcode() == X86ISD::SETCC) {
14252       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14253       bool Invert = (CC == ISD::SETNE) ^
14254         cast<ConstantSDNode>(Op1)->isNullValue();
14255       if (!Invert)
14256         return Op0;
14257
14258       CCode = X86::GetOppositeBranchCondition(CCode);
14259       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14260                                   DAG.getConstant(CCode, dl, MVT::i8),
14261                                   Op0.getOperand(1));
14262       if (VT == MVT::i1)
14263         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14264       return SetCC;
14265     }
14266   }
14267   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14268       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14269       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14270
14271     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14272     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14273   }
14274
14275   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14276   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14277   if (X86CC == X86::COND_INVALID)
14278     return SDValue();
14279
14280   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14281   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14282   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14283                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14284   if (VT == MVT::i1)
14285     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14286   return SetCC;
14287 }
14288
14289 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14290 static bool isX86LogicalCmp(SDValue Op) {
14291   unsigned Opc = Op.getNode()->getOpcode();
14292   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14293       Opc == X86ISD::SAHF)
14294     return true;
14295   if (Op.getResNo() == 1 &&
14296       (Opc == X86ISD::ADD ||
14297        Opc == X86ISD::SUB ||
14298        Opc == X86ISD::ADC ||
14299        Opc == X86ISD::SBB ||
14300        Opc == X86ISD::SMUL ||
14301        Opc == X86ISD::UMUL ||
14302        Opc == X86ISD::INC ||
14303        Opc == X86ISD::DEC ||
14304        Opc == X86ISD::OR ||
14305        Opc == X86ISD::XOR ||
14306        Opc == X86ISD::AND))
14307     return true;
14308
14309   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14310     return true;
14311
14312   return false;
14313 }
14314
14315 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14316   if (V.getOpcode() != ISD::TRUNCATE)
14317     return false;
14318
14319   SDValue VOp0 = V.getOperand(0);
14320   unsigned InBits = VOp0.getValueSizeInBits();
14321   unsigned Bits = V.getValueSizeInBits();
14322   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14323 }
14324
14325 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14326   bool addTest = true;
14327   SDValue Cond  = Op.getOperand(0);
14328   SDValue Op1 = Op.getOperand(1);
14329   SDValue Op2 = Op.getOperand(2);
14330   SDLoc DL(Op);
14331   EVT VT = Op1.getValueType();
14332   SDValue CC;
14333
14334   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14335   // are available or VBLENDV if AVX is available.
14336   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14337   if (Cond.getOpcode() == ISD::SETCC &&
14338       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14339        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14340       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14341     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14342     int SSECC = translateX86FSETCC(
14343         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14344
14345     if (SSECC != 8) {
14346       if (Subtarget->hasAVX512()) {
14347         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14348                                   DAG.getConstant(SSECC, DL, MVT::i8));
14349         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14350       }
14351
14352       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14353                                 DAG.getConstant(SSECC, DL, MVT::i8));
14354
14355       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14356       // of 3 logic instructions for size savings and potentially speed.
14357       // Unfortunately, there is no scalar form of VBLENDV.
14358
14359       // If either operand is a constant, don't try this. We can expect to
14360       // optimize away at least one of the logic instructions later in that
14361       // case, so that sequence would be faster than a variable blend.
14362
14363       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14364       // uses XMM0 as the selection register. That may need just as many
14365       // instructions as the AND/ANDN/OR sequence due to register moves, so
14366       // don't bother.
14367
14368       if (Subtarget->hasAVX() &&
14369           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14370
14371         // Convert to vectors, do a VSELECT, and convert back to scalar.
14372         // All of the conversions should be optimized away.
14373
14374         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14375         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14376         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14377         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14378
14379         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14380         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14381
14382         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14383
14384         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14385                            VSel, DAG.getIntPtrConstant(0, DL));
14386       }
14387       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14388       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14389       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14390     }
14391   }
14392
14393   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14394     SDValue Op1Scalar;
14395     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14396       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14397     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14398       Op1Scalar = Op1.getOperand(0);
14399     SDValue Op2Scalar;
14400     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14401       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14402     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14403       Op2Scalar = Op2.getOperand(0);
14404     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14405       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14406                                       Op1Scalar.getValueType(),
14407                                       Cond, Op1Scalar, Op2Scalar);
14408       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14409         return DAG.getBitcast(VT, newSelect);
14410       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14411       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14412                          DAG.getIntPtrConstant(0, DL));
14413     }
14414   }
14415
14416   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14417     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14418     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14419                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14420     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14421                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14422     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14423                                     Cond, Op1, Op2);
14424     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14425   }
14426
14427   if (Cond.getOpcode() == ISD::SETCC) {
14428     SDValue NewCond = LowerSETCC(Cond, DAG);
14429     if (NewCond.getNode())
14430       Cond = NewCond;
14431   }
14432
14433   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14434   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14435   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14436   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14437   if (Cond.getOpcode() == X86ISD::SETCC &&
14438       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14439       isZero(Cond.getOperand(1).getOperand(1))) {
14440     SDValue Cmp = Cond.getOperand(1);
14441
14442     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14443
14444     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14445         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14446       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14447
14448       SDValue CmpOp0 = Cmp.getOperand(0);
14449       // Apply further optimizations for special cases
14450       // (select (x != 0), -1, 0) -> neg & sbb
14451       // (select (x == 0), 0, -1) -> neg & sbb
14452       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14453         if (YC->isNullValue() &&
14454             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14455           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14456           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14457                                     DAG.getConstant(0, DL,
14458                                                     CmpOp0.getValueType()),
14459                                     CmpOp0);
14460           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14461                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14462                                     SDValue(Neg.getNode(), 1));
14463           return Res;
14464         }
14465
14466       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14467                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14468       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14469
14470       SDValue Res =   // Res = 0 or -1.
14471         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14472                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14473
14474       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14475         Res = DAG.getNOT(DL, Res, Res.getValueType());
14476
14477       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14478       if (!N2C || !N2C->isNullValue())
14479         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14480       return Res;
14481     }
14482   }
14483
14484   // Look past (and (setcc_carry (cmp ...)), 1).
14485   if (Cond.getOpcode() == ISD::AND &&
14486       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14487     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14488     if (C && C->getAPIntValue() == 1)
14489       Cond = Cond.getOperand(0);
14490   }
14491
14492   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14493   // setting operand in place of the X86ISD::SETCC.
14494   unsigned CondOpcode = Cond.getOpcode();
14495   if (CondOpcode == X86ISD::SETCC ||
14496       CondOpcode == X86ISD::SETCC_CARRY) {
14497     CC = Cond.getOperand(0);
14498
14499     SDValue Cmp = Cond.getOperand(1);
14500     unsigned Opc = Cmp.getOpcode();
14501     MVT VT = Op.getSimpleValueType();
14502
14503     bool IllegalFPCMov = false;
14504     if (VT.isFloatingPoint() && !VT.isVector() &&
14505         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14506       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14507
14508     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14509         Opc == X86ISD::BT) { // FIXME
14510       Cond = Cmp;
14511       addTest = false;
14512     }
14513   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14514              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14515              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14516               Cond.getOperand(0).getValueType() != MVT::i8)) {
14517     SDValue LHS = Cond.getOperand(0);
14518     SDValue RHS = Cond.getOperand(1);
14519     unsigned X86Opcode;
14520     unsigned X86Cond;
14521     SDVTList VTs;
14522     switch (CondOpcode) {
14523     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14524     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14525     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14526     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14527     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14528     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14529     default: llvm_unreachable("unexpected overflowing operator");
14530     }
14531     if (CondOpcode == ISD::UMULO)
14532       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14533                           MVT::i32);
14534     else
14535       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14536
14537     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14538
14539     if (CondOpcode == ISD::UMULO)
14540       Cond = X86Op.getValue(2);
14541     else
14542       Cond = X86Op.getValue(1);
14543
14544     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14545     addTest = false;
14546   }
14547
14548   if (addTest) {
14549     // Look past the truncate if the high bits are known zero.
14550     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14551       Cond = Cond.getOperand(0);
14552
14553     // We know the result of AND is compared against zero. Try to match
14554     // it to BT.
14555     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14556       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14557       if (NewSetCC.getNode()) {
14558         CC = NewSetCC.getOperand(0);
14559         Cond = NewSetCC.getOperand(1);
14560         addTest = false;
14561       }
14562     }
14563   }
14564
14565   if (addTest) {
14566     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14567     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14568   }
14569
14570   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14571   // a <  b ?  0 : -1 -> RES = setcc_carry
14572   // a >= b ? -1 :  0 -> RES = setcc_carry
14573   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14574   if (Cond.getOpcode() == X86ISD::SUB) {
14575     Cond = ConvertCmpIfNecessary(Cond, DAG);
14576     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14577
14578     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14579         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14580       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14581                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14582                                 Cond);
14583       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14584         return DAG.getNOT(DL, Res, Res.getValueType());
14585       return Res;
14586     }
14587   }
14588
14589   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14590   // widen the cmov and push the truncate through. This avoids introducing a new
14591   // branch during isel and doesn't add any extensions.
14592   if (Op.getValueType() == MVT::i8 &&
14593       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14594     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14595     if (T1.getValueType() == T2.getValueType() &&
14596         // Blacklist CopyFromReg to avoid partial register stalls.
14597         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14598       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14599       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14600       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14601     }
14602   }
14603
14604   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14605   // condition is true.
14606   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14607   SDValue Ops[] = { Op2, Op1, CC, Cond };
14608   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14609 }
14610
14611 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14612                                        const X86Subtarget *Subtarget,
14613                                        SelectionDAG &DAG) {
14614   MVT VT = Op->getSimpleValueType(0);
14615   SDValue In = Op->getOperand(0);
14616   MVT InVT = In.getSimpleValueType();
14617   MVT VTElt = VT.getVectorElementType();
14618   MVT InVTElt = InVT.getVectorElementType();
14619   SDLoc dl(Op);
14620
14621   // SKX processor
14622   if ((InVTElt == MVT::i1) &&
14623       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14624         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14625
14626        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14627         VTElt.getSizeInBits() <= 16)) ||
14628
14629        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14630         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14631
14632        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14633         VTElt.getSizeInBits() >= 32))))
14634     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14635
14636   unsigned int NumElts = VT.getVectorNumElements();
14637
14638   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14639     return SDValue();
14640
14641   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14642     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14643       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14644     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14645   }
14646
14647   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14648   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14649   SDValue NegOne =
14650    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14651                    ExtVT);
14652   SDValue Zero =
14653    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14654
14655   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14656   if (VT.is512BitVector())
14657     return V;
14658   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14659 }
14660
14661 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14662                                              const X86Subtarget *Subtarget,
14663                                              SelectionDAG &DAG) {
14664   SDValue In = Op->getOperand(0);
14665   MVT VT = Op->getSimpleValueType(0);
14666   MVT InVT = In.getSimpleValueType();
14667   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14668
14669   MVT InSVT = InVT.getScalarType();
14670   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14671
14672   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14673     return SDValue();
14674   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14675     return SDValue();
14676
14677   SDLoc dl(Op);
14678
14679   // SSE41 targets can use the pmovsx* instructions directly.
14680   if (Subtarget->hasSSE41())
14681     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14682
14683   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14684   SDValue Curr = In;
14685   MVT CurrVT = InVT;
14686
14687   // As SRAI is only available on i16/i32 types, we expand only up to i32
14688   // and handle i64 separately.
14689   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14690     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14691     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14692     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14693     Curr = DAG.getBitcast(CurrVT, Curr);
14694   }
14695
14696   SDValue SignExt = Curr;
14697   if (CurrVT != InVT) {
14698     unsigned SignExtShift =
14699         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14700     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14701                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14702   }
14703
14704   if (CurrVT == VT)
14705     return SignExt;
14706
14707   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14708     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14709                                DAG.getConstant(31, dl, MVT::i8));
14710     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14711     return DAG.getBitcast(VT, Ext);
14712   }
14713
14714   return SDValue();
14715 }
14716
14717 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14718                                 SelectionDAG &DAG) {
14719   MVT VT = Op->getSimpleValueType(0);
14720   SDValue In = Op->getOperand(0);
14721   MVT InVT = In.getSimpleValueType();
14722   SDLoc dl(Op);
14723
14724   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14725     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14726
14727   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14728       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14729       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14730     return SDValue();
14731
14732   if (Subtarget->hasInt256())
14733     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14734
14735   // Optimize vectors in AVX mode
14736   // Sign extend  v8i16 to v8i32 and
14737   //              v4i32 to v4i64
14738   //
14739   // Divide input vector into two parts
14740   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14741   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14742   // concat the vectors to original VT
14743
14744   unsigned NumElems = InVT.getVectorNumElements();
14745   SDValue Undef = DAG.getUNDEF(InVT);
14746
14747   SmallVector<int,8> ShufMask1(NumElems, -1);
14748   for (unsigned i = 0; i != NumElems/2; ++i)
14749     ShufMask1[i] = i;
14750
14751   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14752
14753   SmallVector<int,8> ShufMask2(NumElems, -1);
14754   for (unsigned i = 0; i != NumElems/2; ++i)
14755     ShufMask2[i] = i + NumElems/2;
14756
14757   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14758
14759   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14760                                 VT.getVectorNumElements()/2);
14761
14762   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14763   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14764
14765   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14766 }
14767
14768 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14769 // may emit an illegal shuffle but the expansion is still better than scalar
14770 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14771 // we'll emit a shuffle and a arithmetic shift.
14772 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14773 // TODO: It is possible to support ZExt by zeroing the undef values during
14774 // the shuffle phase or after the shuffle.
14775 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14776                                  SelectionDAG &DAG) {
14777   MVT RegVT = Op.getSimpleValueType();
14778   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14779   assert(RegVT.isInteger() &&
14780          "We only custom lower integer vector sext loads.");
14781
14782   // Nothing useful we can do without SSE2 shuffles.
14783   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14784
14785   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14786   SDLoc dl(Ld);
14787   EVT MemVT = Ld->getMemoryVT();
14788   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14789   unsigned RegSz = RegVT.getSizeInBits();
14790
14791   ISD::LoadExtType Ext = Ld->getExtensionType();
14792
14793   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14794          && "Only anyext and sext are currently implemented.");
14795   assert(MemVT != RegVT && "Cannot extend to the same type");
14796   assert(MemVT.isVector() && "Must load a vector from memory");
14797
14798   unsigned NumElems = RegVT.getVectorNumElements();
14799   unsigned MemSz = MemVT.getSizeInBits();
14800   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14801
14802   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14803     // The only way in which we have a legal 256-bit vector result but not the
14804     // integer 256-bit operations needed to directly lower a sextload is if we
14805     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14806     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14807     // correctly legalized. We do this late to allow the canonical form of
14808     // sextload to persist throughout the rest of the DAG combiner -- it wants
14809     // to fold together any extensions it can, and so will fuse a sign_extend
14810     // of an sextload into a sextload targeting a wider value.
14811     SDValue Load;
14812     if (MemSz == 128) {
14813       // Just switch this to a normal load.
14814       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14815                                        "it must be a legal 128-bit vector "
14816                                        "type!");
14817       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14818                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14819                   Ld->isInvariant(), Ld->getAlignment());
14820     } else {
14821       assert(MemSz < 128 &&
14822              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14823       // Do an sext load to a 128-bit vector type. We want to use the same
14824       // number of elements, but elements half as wide. This will end up being
14825       // recursively lowered by this routine, but will succeed as we definitely
14826       // have all the necessary features if we're using AVX1.
14827       EVT HalfEltVT =
14828           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14829       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14830       Load =
14831           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14832                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14833                          Ld->isNonTemporal(), Ld->isInvariant(),
14834                          Ld->getAlignment());
14835     }
14836
14837     // Replace chain users with the new chain.
14838     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14839     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14840
14841     // Finally, do a normal sign-extend to the desired register.
14842     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14843   }
14844
14845   // All sizes must be a power of two.
14846   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14847          "Non-power-of-two elements are not custom lowered!");
14848
14849   // Attempt to load the original value using scalar loads.
14850   // Find the largest scalar type that divides the total loaded size.
14851   MVT SclrLoadTy = MVT::i8;
14852   for (MVT Tp : MVT::integer_valuetypes()) {
14853     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14854       SclrLoadTy = Tp;
14855     }
14856   }
14857
14858   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14859   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14860       (64 <= MemSz))
14861     SclrLoadTy = MVT::f64;
14862
14863   // Calculate the number of scalar loads that we need to perform
14864   // in order to load our vector from memory.
14865   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14866
14867   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14868          "Can only lower sext loads with a single scalar load!");
14869
14870   unsigned loadRegZize = RegSz;
14871   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14872     loadRegZize = 128;
14873
14874   // Represent our vector as a sequence of elements which are the
14875   // largest scalar that we can load.
14876   EVT LoadUnitVecVT = EVT::getVectorVT(
14877       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14878
14879   // Represent the data using the same element type that is stored in
14880   // memory. In practice, we ''widen'' MemVT.
14881   EVT WideVecVT =
14882       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14883                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14884
14885   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14886          "Invalid vector type");
14887
14888   // We can't shuffle using an illegal type.
14889   assert(TLI.isTypeLegal(WideVecVT) &&
14890          "We only lower types that form legal widened vector types");
14891
14892   SmallVector<SDValue, 8> Chains;
14893   SDValue Ptr = Ld->getBasePtr();
14894   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14895                                       TLI.getPointerTy(DAG.getDataLayout()));
14896   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14897
14898   for (unsigned i = 0; i < NumLoads; ++i) {
14899     // Perform a single load.
14900     SDValue ScalarLoad =
14901         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14902                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14903                     Ld->getAlignment());
14904     Chains.push_back(ScalarLoad.getValue(1));
14905     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14906     // another round of DAGCombining.
14907     if (i == 0)
14908       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14909     else
14910       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14911                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14912
14913     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14914   }
14915
14916   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14917
14918   // Bitcast the loaded value to a vector of the original element type, in
14919   // the size of the target vector type.
14920   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14921   unsigned SizeRatio = RegSz / MemSz;
14922
14923   if (Ext == ISD::SEXTLOAD) {
14924     // If we have SSE4.1, we can directly emit a VSEXT node.
14925     if (Subtarget->hasSSE41()) {
14926       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14927       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14928       return Sext;
14929     }
14930
14931     // Otherwise we'll shuffle the small elements in the high bits of the
14932     // larger type and perform an arithmetic shift. If the shift is not legal
14933     // it's better to scalarize.
14934     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14935            "We can't implement a sext load without an arithmetic right shift!");
14936
14937     // Redistribute the loaded elements into the different locations.
14938     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14939     for (unsigned i = 0; i != NumElems; ++i)
14940       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14941
14942     SDValue Shuff = DAG.getVectorShuffle(
14943         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14944
14945     Shuff = DAG.getBitcast(RegVT, Shuff);
14946
14947     // Build the arithmetic shift.
14948     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14949                    MemVT.getVectorElementType().getSizeInBits();
14950     Shuff =
14951         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14952                     DAG.getConstant(Amt, dl, RegVT));
14953
14954     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14955     return Shuff;
14956   }
14957
14958   // Redistribute the loaded elements into the different locations.
14959   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14960   for (unsigned i = 0; i != NumElems; ++i)
14961     ShuffleVec[i * SizeRatio] = i;
14962
14963   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14964                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14965
14966   // Bitcast to the requested type.
14967   Shuff = DAG.getBitcast(RegVT, Shuff);
14968   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14969   return Shuff;
14970 }
14971
14972 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14973 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14974 // from the AND / OR.
14975 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14976   Opc = Op.getOpcode();
14977   if (Opc != ISD::OR && Opc != ISD::AND)
14978     return false;
14979   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14980           Op.getOperand(0).hasOneUse() &&
14981           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14982           Op.getOperand(1).hasOneUse());
14983 }
14984
14985 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14986 // 1 and that the SETCC node has a single use.
14987 static bool isXor1OfSetCC(SDValue Op) {
14988   if (Op.getOpcode() != ISD::XOR)
14989     return false;
14990   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14991   if (N1C && N1C->getAPIntValue() == 1) {
14992     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14993       Op.getOperand(0).hasOneUse();
14994   }
14995   return false;
14996 }
14997
14998 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14999   bool addTest = true;
15000   SDValue Chain = Op.getOperand(0);
15001   SDValue Cond  = Op.getOperand(1);
15002   SDValue Dest  = Op.getOperand(2);
15003   SDLoc dl(Op);
15004   SDValue CC;
15005   bool Inverted = false;
15006
15007   if (Cond.getOpcode() == ISD::SETCC) {
15008     // Check for setcc([su]{add,sub,mul}o == 0).
15009     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15010         isa<ConstantSDNode>(Cond.getOperand(1)) &&
15011         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15012         Cond.getOperand(0).getResNo() == 1 &&
15013         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15014          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15015          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15016          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15017          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15018          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15019       Inverted = true;
15020       Cond = Cond.getOperand(0);
15021     } else {
15022       SDValue NewCond = LowerSETCC(Cond, DAG);
15023       if (NewCond.getNode())
15024         Cond = NewCond;
15025     }
15026   }
15027 #if 0
15028   // FIXME: LowerXALUO doesn't handle these!!
15029   else if (Cond.getOpcode() == X86ISD::ADD  ||
15030            Cond.getOpcode() == X86ISD::SUB  ||
15031            Cond.getOpcode() == X86ISD::SMUL ||
15032            Cond.getOpcode() == X86ISD::UMUL)
15033     Cond = LowerXALUO(Cond, DAG);
15034 #endif
15035
15036   // Look pass (and (setcc_carry (cmp ...)), 1).
15037   if (Cond.getOpcode() == ISD::AND &&
15038       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15039     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15040     if (C && C->getAPIntValue() == 1)
15041       Cond = Cond.getOperand(0);
15042   }
15043
15044   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15045   // setting operand in place of the X86ISD::SETCC.
15046   unsigned CondOpcode = Cond.getOpcode();
15047   if (CondOpcode == X86ISD::SETCC ||
15048       CondOpcode == X86ISD::SETCC_CARRY) {
15049     CC = Cond.getOperand(0);
15050
15051     SDValue Cmp = Cond.getOperand(1);
15052     unsigned Opc = Cmp.getOpcode();
15053     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15054     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15055       Cond = Cmp;
15056       addTest = false;
15057     } else {
15058       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15059       default: break;
15060       case X86::COND_O:
15061       case X86::COND_B:
15062         // These can only come from an arithmetic instruction with overflow,
15063         // e.g. SADDO, UADDO.
15064         Cond = Cond.getNode()->getOperand(1);
15065         addTest = false;
15066         break;
15067       }
15068     }
15069   }
15070   CondOpcode = Cond.getOpcode();
15071   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15072       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15073       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15074        Cond.getOperand(0).getValueType() != MVT::i8)) {
15075     SDValue LHS = Cond.getOperand(0);
15076     SDValue RHS = Cond.getOperand(1);
15077     unsigned X86Opcode;
15078     unsigned X86Cond;
15079     SDVTList VTs;
15080     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15081     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15082     // X86ISD::INC).
15083     switch (CondOpcode) {
15084     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15085     case ISD::SADDO:
15086       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15087         if (C->isOne()) {
15088           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15089           break;
15090         }
15091       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15092     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15093     case ISD::SSUBO:
15094       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15095         if (C->isOne()) {
15096           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15097           break;
15098         }
15099       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15100     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15101     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15102     default: llvm_unreachable("unexpected overflowing operator");
15103     }
15104     if (Inverted)
15105       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15106     if (CondOpcode == ISD::UMULO)
15107       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15108                           MVT::i32);
15109     else
15110       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15111
15112     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15113
15114     if (CondOpcode == ISD::UMULO)
15115       Cond = X86Op.getValue(2);
15116     else
15117       Cond = X86Op.getValue(1);
15118
15119     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15120     addTest = false;
15121   } else {
15122     unsigned CondOpc;
15123     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15124       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15125       if (CondOpc == ISD::OR) {
15126         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15127         // two branches instead of an explicit OR instruction with a
15128         // separate test.
15129         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15130             isX86LogicalCmp(Cmp)) {
15131           CC = Cond.getOperand(0).getOperand(0);
15132           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15133                               Chain, Dest, CC, Cmp);
15134           CC = Cond.getOperand(1).getOperand(0);
15135           Cond = Cmp;
15136           addTest = false;
15137         }
15138       } else { // ISD::AND
15139         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15140         // two branches instead of an explicit AND instruction with a
15141         // separate test. However, we only do this if this block doesn't
15142         // have a fall-through edge, because this requires an explicit
15143         // jmp when the condition is false.
15144         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15145             isX86LogicalCmp(Cmp) &&
15146             Op.getNode()->hasOneUse()) {
15147           X86::CondCode CCode =
15148             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15149           CCode = X86::GetOppositeBranchCondition(CCode);
15150           CC = DAG.getConstant(CCode, dl, MVT::i8);
15151           SDNode *User = *Op.getNode()->use_begin();
15152           // Look for an unconditional branch following this conditional branch.
15153           // We need this because we need to reverse the successors in order
15154           // to implement FCMP_OEQ.
15155           if (User->getOpcode() == ISD::BR) {
15156             SDValue FalseBB = User->getOperand(1);
15157             SDNode *NewBR =
15158               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15159             assert(NewBR == User);
15160             (void)NewBR;
15161             Dest = FalseBB;
15162
15163             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15164                                 Chain, Dest, CC, Cmp);
15165             X86::CondCode CCode =
15166               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15167             CCode = X86::GetOppositeBranchCondition(CCode);
15168             CC = DAG.getConstant(CCode, dl, MVT::i8);
15169             Cond = Cmp;
15170             addTest = false;
15171           }
15172         }
15173       }
15174     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15175       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15176       // It should be transformed during dag combiner except when the condition
15177       // is set by a arithmetics with overflow node.
15178       X86::CondCode CCode =
15179         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15180       CCode = X86::GetOppositeBranchCondition(CCode);
15181       CC = DAG.getConstant(CCode, dl, MVT::i8);
15182       Cond = Cond.getOperand(0).getOperand(1);
15183       addTest = false;
15184     } else if (Cond.getOpcode() == ISD::SETCC &&
15185                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15186       // For FCMP_OEQ, we can emit
15187       // two branches instead of an explicit AND instruction with a
15188       // separate test. However, we only do this if this block doesn't
15189       // have a fall-through edge, because this requires an explicit
15190       // jmp when the condition is false.
15191       if (Op.getNode()->hasOneUse()) {
15192         SDNode *User = *Op.getNode()->use_begin();
15193         // Look for an unconditional branch following this conditional branch.
15194         // We need this because we need to reverse the successors in order
15195         // to implement FCMP_OEQ.
15196         if (User->getOpcode() == ISD::BR) {
15197           SDValue FalseBB = User->getOperand(1);
15198           SDNode *NewBR =
15199             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15200           assert(NewBR == User);
15201           (void)NewBR;
15202           Dest = FalseBB;
15203
15204           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15205                                     Cond.getOperand(0), Cond.getOperand(1));
15206           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15207           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15208           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15209                               Chain, Dest, CC, Cmp);
15210           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15211           Cond = Cmp;
15212           addTest = false;
15213         }
15214       }
15215     } else if (Cond.getOpcode() == ISD::SETCC &&
15216                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15217       // For FCMP_UNE, we can emit
15218       // two branches instead of an explicit AND instruction with a
15219       // separate test. However, we only do this if this block doesn't
15220       // have a fall-through edge, because this requires an explicit
15221       // jmp when the condition is false.
15222       if (Op.getNode()->hasOneUse()) {
15223         SDNode *User = *Op.getNode()->use_begin();
15224         // Look for an unconditional branch following this conditional branch.
15225         // We need this because we need to reverse the successors in order
15226         // to implement FCMP_UNE.
15227         if (User->getOpcode() == ISD::BR) {
15228           SDValue FalseBB = User->getOperand(1);
15229           SDNode *NewBR =
15230             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15231           assert(NewBR == User);
15232           (void)NewBR;
15233
15234           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15235                                     Cond.getOperand(0), Cond.getOperand(1));
15236           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15237           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15238           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15239                               Chain, Dest, CC, Cmp);
15240           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15241           Cond = Cmp;
15242           addTest = false;
15243           Dest = FalseBB;
15244         }
15245       }
15246     }
15247   }
15248
15249   if (addTest) {
15250     // Look pass the truncate if the high bits are known zero.
15251     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15252         Cond = Cond.getOperand(0);
15253
15254     // We know the result of AND is compared against zero. Try to match
15255     // it to BT.
15256     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15257       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15258       if (NewSetCC.getNode()) {
15259         CC = NewSetCC.getOperand(0);
15260         Cond = NewSetCC.getOperand(1);
15261         addTest = false;
15262       }
15263     }
15264   }
15265
15266   if (addTest) {
15267     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15268     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15269     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15270   }
15271   Cond = ConvertCmpIfNecessary(Cond, DAG);
15272   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15273                      Chain, Dest, CC, Cond);
15274 }
15275
15276 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15277 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15278 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15279 // that the guard pages used by the OS virtual memory manager are allocated in
15280 // correct sequence.
15281 SDValue
15282 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15283                                            SelectionDAG &DAG) const {
15284   MachineFunction &MF = DAG.getMachineFunction();
15285   bool SplitStack = MF.shouldSplitStack();
15286   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15287                SplitStack;
15288   SDLoc dl(Op);
15289
15290   if (!Lower) {
15291     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15292     SDNode* Node = Op.getNode();
15293
15294     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15295     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15296         " not tell us which reg is the stack pointer!");
15297     EVT VT = Node->getValueType(0);
15298     SDValue Tmp1 = SDValue(Node, 0);
15299     SDValue Tmp2 = SDValue(Node, 1);
15300     SDValue Tmp3 = Node->getOperand(2);
15301     SDValue Chain = Tmp1.getOperand(0);
15302
15303     // Chain the dynamic stack allocation so that it doesn't modify the stack
15304     // pointer when other instructions are using the stack.
15305     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15306         SDLoc(Node));
15307
15308     SDValue Size = Tmp2.getOperand(1);
15309     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15310     Chain = SP.getValue(1);
15311     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15312     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15313     unsigned StackAlign = TFI.getStackAlignment();
15314     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15315     if (Align > StackAlign)
15316       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15317           DAG.getConstant(-(uint64_t)Align, dl, VT));
15318     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15319
15320     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15321         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15322         SDLoc(Node));
15323
15324     SDValue Ops[2] = { Tmp1, Tmp2 };
15325     return DAG.getMergeValues(Ops, dl);
15326   }
15327
15328   // Get the inputs.
15329   SDValue Chain = Op.getOperand(0);
15330   SDValue Size  = Op.getOperand(1);
15331   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15332   EVT VT = Op.getNode()->getValueType(0);
15333
15334   bool Is64Bit = Subtarget->is64Bit();
15335   MVT SPTy = getPointerTy(DAG.getDataLayout());
15336
15337   if (SplitStack) {
15338     MachineRegisterInfo &MRI = MF.getRegInfo();
15339
15340     if (Is64Bit) {
15341       // The 64 bit implementation of segmented stacks needs to clobber both r10
15342       // r11. This makes it impossible to use it along with nested parameters.
15343       const Function *F = MF.getFunction();
15344
15345       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15346            I != E; ++I)
15347         if (I->hasNestAttr())
15348           report_fatal_error("Cannot use segmented stacks with functions that "
15349                              "have nested arguments.");
15350     }
15351
15352     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15353     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15354     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15355     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15356                                 DAG.getRegister(Vreg, SPTy));
15357     SDValue Ops1[2] = { Value, Chain };
15358     return DAG.getMergeValues(Ops1, dl);
15359   } else {
15360     SDValue Flag;
15361     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15362
15363     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15364     Flag = Chain.getValue(1);
15365     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15366
15367     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15368
15369     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15370     unsigned SPReg = RegInfo->getStackRegister();
15371     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15372     Chain = SP.getValue(1);
15373
15374     if (Align) {
15375       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15376                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15377       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15378     }
15379
15380     SDValue Ops1[2] = { SP, Chain };
15381     return DAG.getMergeValues(Ops1, dl);
15382   }
15383 }
15384
15385 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15386   MachineFunction &MF = DAG.getMachineFunction();
15387   auto PtrVT = getPointerTy(MF.getDataLayout());
15388   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15389
15390   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15391   SDLoc DL(Op);
15392
15393   if (!Subtarget->is64Bit() ||
15394       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15395     // vastart just stores the address of the VarArgsFrameIndex slot into the
15396     // memory location argument.
15397     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15398     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15399                         MachinePointerInfo(SV), false, false, 0);
15400   }
15401
15402   // __va_list_tag:
15403   //   gp_offset         (0 - 6 * 8)
15404   //   fp_offset         (48 - 48 + 8 * 16)
15405   //   overflow_arg_area (point to parameters coming in memory).
15406   //   reg_save_area
15407   SmallVector<SDValue, 8> MemOps;
15408   SDValue FIN = Op.getOperand(1);
15409   // Store gp_offset
15410   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15411                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15412                                                DL, MVT::i32),
15413                                FIN, MachinePointerInfo(SV), false, false, 0);
15414   MemOps.push_back(Store);
15415
15416   // Store fp_offset
15417   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15418   Store = DAG.getStore(Op.getOperand(0), DL,
15419                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15420                                        MVT::i32),
15421                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15422   MemOps.push_back(Store);
15423
15424   // Store ptr to overflow_arg_area
15425   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15426   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15427   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15428                        MachinePointerInfo(SV, 8),
15429                        false, false, 0);
15430   MemOps.push_back(Store);
15431
15432   // Store ptr to reg_save_area.
15433   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15434       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15435   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15436   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15437       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15438   MemOps.push_back(Store);
15439   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15440 }
15441
15442 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15443   assert(Subtarget->is64Bit() &&
15444          "LowerVAARG only handles 64-bit va_arg!");
15445   assert(Op.getNode()->getNumOperands() == 4);
15446
15447   MachineFunction &MF = DAG.getMachineFunction();
15448   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15449     // The Win64 ABI uses char* instead of a structure.
15450     return DAG.expandVAArg(Op.getNode());
15451
15452   SDValue Chain = Op.getOperand(0);
15453   SDValue SrcPtr = Op.getOperand(1);
15454   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15455   unsigned Align = Op.getConstantOperandVal(3);
15456   SDLoc dl(Op);
15457
15458   EVT ArgVT = Op.getNode()->getValueType(0);
15459   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15460   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15461   uint8_t ArgMode;
15462
15463   // Decide which area this value should be read from.
15464   // TODO: Implement the AMD64 ABI in its entirety. This simple
15465   // selection mechanism works only for the basic types.
15466   if (ArgVT == MVT::f80) {
15467     llvm_unreachable("va_arg for f80 not yet implemented");
15468   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15469     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15470   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15471     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15472   } else {
15473     llvm_unreachable("Unhandled argument type in LowerVAARG");
15474   }
15475
15476   if (ArgMode == 2) {
15477     // Sanity Check: Make sure using fp_offset makes sense.
15478     assert(!Subtarget->useSoftFloat() &&
15479            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15480            Subtarget->hasSSE1());
15481   }
15482
15483   // Insert VAARG_64 node into the DAG
15484   // VAARG_64 returns two values: Variable Argument Address, Chain
15485   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15486                        DAG.getConstant(ArgMode, dl, MVT::i8),
15487                        DAG.getConstant(Align, dl, MVT::i32)};
15488   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15489   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15490                                           VTs, InstOps, MVT::i64,
15491                                           MachinePointerInfo(SV),
15492                                           /*Align=*/0,
15493                                           /*Volatile=*/false,
15494                                           /*ReadMem=*/true,
15495                                           /*WriteMem=*/true);
15496   Chain = VAARG.getValue(1);
15497
15498   // Load the next argument and return it
15499   return DAG.getLoad(ArgVT, dl,
15500                      Chain,
15501                      VAARG,
15502                      MachinePointerInfo(),
15503                      false, false, false, 0);
15504 }
15505
15506 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15507                            SelectionDAG &DAG) {
15508   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15509   // where a va_list is still an i8*.
15510   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15511   if (Subtarget->isCallingConvWin64(
15512         DAG.getMachineFunction().getFunction()->getCallingConv()))
15513     // Probably a Win64 va_copy.
15514     return DAG.expandVACopy(Op.getNode());
15515
15516   SDValue Chain = Op.getOperand(0);
15517   SDValue DstPtr = Op.getOperand(1);
15518   SDValue SrcPtr = Op.getOperand(2);
15519   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15520   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15521   SDLoc DL(Op);
15522
15523   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15524                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15525                        false, false,
15526                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15527 }
15528
15529 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15530 // amount is a constant. Takes immediate version of shift as input.
15531 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15532                                           SDValue SrcOp, uint64_t ShiftAmt,
15533                                           SelectionDAG &DAG) {
15534   MVT ElementType = VT.getVectorElementType();
15535
15536   // Fold this packed shift into its first operand if ShiftAmt is 0.
15537   if (ShiftAmt == 0)
15538     return SrcOp;
15539
15540   // Check for ShiftAmt >= element width
15541   if (ShiftAmt >= ElementType.getSizeInBits()) {
15542     if (Opc == X86ISD::VSRAI)
15543       ShiftAmt = ElementType.getSizeInBits() - 1;
15544     else
15545       return DAG.getConstant(0, dl, VT);
15546   }
15547
15548   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15549          && "Unknown target vector shift-by-constant node");
15550
15551   // Fold this packed vector shift into a build vector if SrcOp is a
15552   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15553   if (VT == SrcOp.getSimpleValueType() &&
15554       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15555     SmallVector<SDValue, 8> Elts;
15556     unsigned NumElts = SrcOp->getNumOperands();
15557     ConstantSDNode *ND;
15558
15559     switch(Opc) {
15560     default: llvm_unreachable(nullptr);
15561     case X86ISD::VSHLI:
15562       for (unsigned i=0; i!=NumElts; ++i) {
15563         SDValue CurrentOp = SrcOp->getOperand(i);
15564         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15565           Elts.push_back(CurrentOp);
15566           continue;
15567         }
15568         ND = cast<ConstantSDNode>(CurrentOp);
15569         const APInt &C = ND->getAPIntValue();
15570         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15571       }
15572       break;
15573     case X86ISD::VSRLI:
15574       for (unsigned i=0; i!=NumElts; ++i) {
15575         SDValue CurrentOp = SrcOp->getOperand(i);
15576         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15577           Elts.push_back(CurrentOp);
15578           continue;
15579         }
15580         ND = cast<ConstantSDNode>(CurrentOp);
15581         const APInt &C = ND->getAPIntValue();
15582         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15583       }
15584       break;
15585     case X86ISD::VSRAI:
15586       for (unsigned i=0; i!=NumElts; ++i) {
15587         SDValue CurrentOp = SrcOp->getOperand(i);
15588         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15589           Elts.push_back(CurrentOp);
15590           continue;
15591         }
15592         ND = cast<ConstantSDNode>(CurrentOp);
15593         const APInt &C = ND->getAPIntValue();
15594         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15595       }
15596       break;
15597     }
15598
15599     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15600   }
15601
15602   return DAG.getNode(Opc, dl, VT, SrcOp,
15603                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15604 }
15605
15606 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15607 // may or may not be a constant. Takes immediate version of shift as input.
15608 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15609                                    SDValue SrcOp, SDValue ShAmt,
15610                                    SelectionDAG &DAG) {
15611   MVT SVT = ShAmt.getSimpleValueType();
15612   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15613
15614   // Catch shift-by-constant.
15615   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15616     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15617                                       CShAmt->getZExtValue(), DAG);
15618
15619   // Change opcode to non-immediate version
15620   switch (Opc) {
15621     default: llvm_unreachable("Unknown target vector shift node");
15622     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15623     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15624     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15625   }
15626
15627   const X86Subtarget &Subtarget =
15628       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15629   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15630       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15631     // Let the shuffle legalizer expand this shift amount node.
15632     SDValue Op0 = ShAmt.getOperand(0);
15633     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15634     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15635   } else {
15636     // Need to build a vector containing shift amount.
15637     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15638     SmallVector<SDValue, 4> ShOps;
15639     ShOps.push_back(ShAmt);
15640     if (SVT == MVT::i32) {
15641       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15642       ShOps.push_back(DAG.getUNDEF(SVT));
15643     }
15644     ShOps.push_back(DAG.getUNDEF(SVT));
15645
15646     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15647     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15648   }
15649
15650   // The return type has to be a 128-bit type with the same element
15651   // type as the input type.
15652   MVT EltVT = VT.getVectorElementType();
15653   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15654
15655   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15656   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15657 }
15658
15659 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15660 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15661 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15662 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15663                                     SDValue PreservedSrc,
15664                                     const X86Subtarget *Subtarget,
15665                                     SelectionDAG &DAG) {
15666     EVT VT = Op.getValueType();
15667     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15668                                   MVT::i1, VT.getVectorNumElements());
15669     SDValue VMask = SDValue();
15670     unsigned OpcodeSelect = ISD::VSELECT;
15671     SDLoc dl(Op);
15672
15673     assert(MaskVT.isSimple() && "invalid mask type");
15674
15675     if (isAllOnes(Mask))
15676       return Op;
15677
15678     if (MaskVT.bitsGT(Mask.getValueType())) {
15679       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15680                                          MaskVT.getSizeInBits());
15681       VMask = DAG.getBitcast(MaskVT,
15682                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15683     } else {
15684       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15685                                        Mask.getValueType().getSizeInBits());
15686       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15687       // are extracted by EXTRACT_SUBVECTOR.
15688       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15689                           DAG.getBitcast(BitcastVT, Mask),
15690                           DAG.getIntPtrConstant(0, dl));
15691     }
15692
15693     switch (Op.getOpcode()) {
15694       default: break;
15695       case X86ISD::PCMPEQM:
15696       case X86ISD::PCMPGTM:
15697       case X86ISD::CMPM:
15698       case X86ISD::CMPMU:
15699         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15700       case X86ISD::VTRUNC:
15701       case X86ISD::VTRUNCS:
15702       case X86ISD::VTRUNCUS:
15703         // We can't use ISD::VSELECT here because it is not always "Legal"
15704         // for the destination type. For example vpmovqb require only AVX512
15705         // and vselect that can operate on byte element type require BWI
15706         OpcodeSelect = X86ISD::SELECT;
15707         break;
15708     }
15709     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15710       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15711     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15712 }
15713
15714 /// \brief Creates an SDNode for a predicated scalar operation.
15715 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15716 /// The mask is coming as MVT::i8 and it should be truncated
15717 /// to MVT::i1 while lowering masking intrinsics.
15718 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15719 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15720 /// for a scalar instruction.
15721 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15722                                     SDValue PreservedSrc,
15723                                     const X86Subtarget *Subtarget,
15724                                     SelectionDAG &DAG) {
15725     if (isAllOnes(Mask))
15726       return Op;
15727
15728     EVT VT = Op.getValueType();
15729     SDLoc dl(Op);
15730     // The mask should be of type MVT::i1
15731     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15732
15733     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15734       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15735     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15736 }
15737
15738 static int getSEHRegistrationNodeSize(const Function *Fn) {
15739   if (!Fn->hasPersonalityFn())
15740     report_fatal_error(
15741         "querying registration node size for function without personality");
15742   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15743   // WinEHStatePass for the full struct definition.
15744   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15745   case EHPersonality::MSVC_X86SEH: return 24;
15746   case EHPersonality::MSVC_CXX: return 16;
15747   default: break;
15748   }
15749   report_fatal_error("can only recover FP for MSVC EH personality functions");
15750 }
15751
15752 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15753 /// function or when returning to a parent frame after catching an exception, we
15754 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15755 /// Here's the math:
15756 ///   RegNodeBase = EntryEBP - RegNodeSize
15757 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15758 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15759 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15760 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15761                                    SDValue EntryEBP) {
15762   MachineFunction &MF = DAG.getMachineFunction();
15763   SDLoc dl;
15764
15765   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15766   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15767
15768   // It's possible that the parent function no longer has a personality function
15769   // if the exceptional code was optimized away, in which case we just return
15770   // the incoming EBP.
15771   if (!Fn->hasPersonalityFn())
15772     return EntryEBP;
15773
15774   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15775
15776   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15777   // registration.
15778   MCSymbol *OffsetSym =
15779       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15780           GlobalValue::getRealLinkageName(Fn->getName()));
15781   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15782   SDValue RegNodeFrameOffset =
15783       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15784
15785   // RegNodeBase = EntryEBP - RegNodeSize
15786   // ParentFP = RegNodeBase - RegNodeFrameOffset
15787   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15788                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15789   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15790 }
15791
15792 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15793                                        SelectionDAG &DAG) {
15794   SDLoc dl(Op);
15795   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15796   EVT VT = Op.getValueType();
15797   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15798   if (IntrData) {
15799     switch(IntrData->Type) {
15800     case INTR_TYPE_1OP:
15801       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15802     case INTR_TYPE_2OP:
15803       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15804         Op.getOperand(2));
15805     case INTR_TYPE_2OP_IMM8:
15806       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15807                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
15808     case INTR_TYPE_3OP:
15809       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15810         Op.getOperand(2), Op.getOperand(3));
15811     case INTR_TYPE_4OP:
15812       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15813         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15814     case INTR_TYPE_1OP_MASK_RM: {
15815       SDValue Src = Op.getOperand(1);
15816       SDValue PassThru = Op.getOperand(2);
15817       SDValue Mask = Op.getOperand(3);
15818       SDValue RoundingMode;
15819       // We allways add rounding mode to the Node.
15820       // If the rounding mode is not specified, we add the
15821       // "current direction" mode.
15822       if (Op.getNumOperands() == 4)
15823         RoundingMode =
15824           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15825       else
15826         RoundingMode = Op.getOperand(4);
15827       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15828       if (IntrWithRoundingModeOpcode != 0)
15829         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15830             X86::STATIC_ROUNDING::CUR_DIRECTION)
15831           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15832                                       dl, Op.getValueType(), Src, RoundingMode),
15833                                       Mask, PassThru, Subtarget, DAG);
15834       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15835                                               RoundingMode),
15836                                   Mask, PassThru, Subtarget, DAG);
15837     }
15838     case INTR_TYPE_1OP_MASK: {
15839       SDValue Src = Op.getOperand(1);
15840       SDValue PassThru = Op.getOperand(2);
15841       SDValue Mask = Op.getOperand(3);
15842       // We add rounding mode to the Node when
15843       //   - RM Opcode is specified and
15844       //   - RM is not "current direction".
15845       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15846       if (IntrWithRoundingModeOpcode != 0) {
15847         SDValue Rnd = Op.getOperand(4);
15848         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15849         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15850           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15851                                       dl, Op.getValueType(),
15852                                       Src, Rnd),
15853                                       Mask, PassThru, Subtarget, DAG);
15854         }
15855       }
15856       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15857                                   Mask, PassThru, Subtarget, DAG);
15858     }
15859     case INTR_TYPE_SCALAR_MASK_RM: {
15860       SDValue Src1 = Op.getOperand(1);
15861       SDValue Src2 = Op.getOperand(2);
15862       SDValue Src0 = Op.getOperand(3);
15863       SDValue Mask = Op.getOperand(4);
15864       // There are 2 kinds of intrinsics in this group:
15865       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15866       // (2) With rounding mode and sae - 7 operands.
15867       if (Op.getNumOperands() == 6) {
15868         SDValue Sae  = Op.getOperand(5);
15869         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15870         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15871                                                 Sae),
15872                                     Mask, Src0, Subtarget, DAG);
15873       }
15874       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15875       SDValue RoundingMode  = Op.getOperand(5);
15876       SDValue Sae  = Op.getOperand(6);
15877       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15878                                               RoundingMode, Sae),
15879                                   Mask, Src0, Subtarget, DAG);
15880     }
15881     case INTR_TYPE_2OP_MASK: {
15882       SDValue Src1 = Op.getOperand(1);
15883       SDValue Src2 = Op.getOperand(2);
15884       SDValue PassThru = Op.getOperand(3);
15885       SDValue Mask = Op.getOperand(4);
15886       // We specify 2 possible opcodes for intrinsics with rounding modes.
15887       // First, we check if the intrinsic may have non-default rounding mode,
15888       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15889       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15890       if (IntrWithRoundingModeOpcode != 0) {
15891         SDValue Rnd = Op.getOperand(5);
15892         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15893         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15894           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15895                                       dl, Op.getValueType(),
15896                                       Src1, Src2, Rnd),
15897                                       Mask, PassThru, Subtarget, DAG);
15898         }
15899       }
15900       // TODO: Intrinsics should have fast-math-flags to propagate.
15901       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
15902                                   Mask, PassThru, Subtarget, DAG);
15903     }
15904     case INTR_TYPE_2OP_MASK_RM: {
15905       SDValue Src1 = Op.getOperand(1);
15906       SDValue Src2 = Op.getOperand(2);
15907       SDValue PassThru = Op.getOperand(3);
15908       SDValue Mask = Op.getOperand(4);
15909       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15910       // First, we check if the intrinsic have rounding mode (6 operands),
15911       // if not, we set rounding mode to "current".
15912       SDValue Rnd;
15913       if (Op.getNumOperands() == 6)
15914         Rnd = Op.getOperand(5);
15915       else
15916         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15917       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15918                                               Src1, Src2, Rnd),
15919                                   Mask, PassThru, Subtarget, DAG);
15920     }
15921     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
15922       SDValue Src1 = Op.getOperand(1);
15923       SDValue Src2 = Op.getOperand(2);
15924       SDValue Src3 = Op.getOperand(3);
15925       SDValue PassThru = Op.getOperand(4);
15926       SDValue Mask = Op.getOperand(5);
15927       SDValue Sae  = Op.getOperand(6);
15928
15929       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
15930                                               Src2, Src3, Sae),
15931                                   Mask, PassThru, Subtarget, DAG);
15932     }
15933     case INTR_TYPE_3OP_MASK_RM: {
15934       SDValue Src1 = Op.getOperand(1);
15935       SDValue Src2 = Op.getOperand(2);
15936       SDValue Imm = Op.getOperand(3);
15937       SDValue PassThru = Op.getOperand(4);
15938       SDValue Mask = Op.getOperand(5);
15939       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15940       // First, we check if the intrinsic have rounding mode (7 operands),
15941       // if not, we set rounding mode to "current".
15942       SDValue Rnd;
15943       if (Op.getNumOperands() == 7)
15944         Rnd = Op.getOperand(6);
15945       else
15946         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15947       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15948         Src1, Src2, Imm, Rnd),
15949         Mask, PassThru, Subtarget, DAG);
15950     }
15951     case INTR_TYPE_3OP_IMM8_MASK:
15952     case INTR_TYPE_3OP_MASK: {
15953       SDValue Src1 = Op.getOperand(1);
15954       SDValue Src2 = Op.getOperand(2);
15955       SDValue Src3 = Op.getOperand(3);
15956       SDValue PassThru = Op.getOperand(4);
15957       SDValue Mask = Op.getOperand(5);
15958
15959       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
15960         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
15961       // We specify 2 possible opcodes for intrinsics with rounding modes.
15962       // First, we check if the intrinsic may have non-default rounding mode,
15963       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15964       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15965       if (IntrWithRoundingModeOpcode != 0) {
15966         SDValue Rnd = Op.getOperand(6);
15967         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15968         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15969           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15970                                       dl, Op.getValueType(),
15971                                       Src1, Src2, Src3, Rnd),
15972                                       Mask, PassThru, Subtarget, DAG);
15973         }
15974       }
15975       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15976                                               Src1, Src2, Src3),
15977                                   Mask, PassThru, Subtarget, DAG);
15978     }
15979     case VPERM_3OP_MASKZ:
15980     case VPERM_3OP_MASK:
15981     case FMA_OP_MASK3:
15982     case FMA_OP_MASKZ:
15983     case FMA_OP_MASK: {
15984       SDValue Src1 = Op.getOperand(1);
15985       SDValue Src2 = Op.getOperand(2);
15986       SDValue Src3 = Op.getOperand(3);
15987       SDValue Mask = Op.getOperand(4);
15988       EVT VT = Op.getValueType();
15989       SDValue PassThru = SDValue();
15990
15991       // set PassThru element
15992       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15993         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15994       else if (IntrData->Type == FMA_OP_MASK3)
15995         PassThru = Src3;
15996       else
15997         PassThru = Src1;
15998
15999       // We specify 2 possible opcodes for intrinsics with rounding modes.
16000       // First, we check if the intrinsic may have non-default rounding mode,
16001       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16002       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16003       if (IntrWithRoundingModeOpcode != 0) {
16004         SDValue Rnd = Op.getOperand(5);
16005         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16006             X86::STATIC_ROUNDING::CUR_DIRECTION)
16007           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16008                                                   dl, Op.getValueType(),
16009                                                   Src1, Src2, Src3, Rnd),
16010                                       Mask, PassThru, Subtarget, DAG);
16011       }
16012       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16013                                               dl, Op.getValueType(),
16014                                               Src1, Src2, Src3),
16015                                   Mask, PassThru, Subtarget, DAG);
16016     }
16017     case CMP_MASK:
16018     case CMP_MASK_CC: {
16019       // Comparison intrinsics with masks.
16020       // Example of transformation:
16021       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16022       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16023       // (i8 (bitcast
16024       //   (v8i1 (insert_subvector undef,
16025       //           (v2i1 (and (PCMPEQM %a, %b),
16026       //                      (extract_subvector
16027       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16028       EVT VT = Op.getOperand(1).getValueType();
16029       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16030                                     VT.getVectorNumElements());
16031       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16032       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16033                                        Mask.getValueType().getSizeInBits());
16034       SDValue Cmp;
16035       if (IntrData->Type == CMP_MASK_CC) {
16036         SDValue CC = Op.getOperand(3);
16037         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16038         // We specify 2 possible opcodes for intrinsics with rounding modes.
16039         // First, we check if the intrinsic may have non-default rounding mode,
16040         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16041         if (IntrData->Opc1 != 0) {
16042           SDValue Rnd = Op.getOperand(5);
16043           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16044               X86::STATIC_ROUNDING::CUR_DIRECTION)
16045             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16046                               Op.getOperand(2), CC, Rnd);
16047         }
16048         //default rounding mode
16049         if(!Cmp.getNode())
16050             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16051                               Op.getOperand(2), CC);
16052
16053       } else {
16054         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16055         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16056                           Op.getOperand(2));
16057       }
16058       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16059                                              DAG.getTargetConstant(0, dl,
16060                                                                    MaskVT),
16061                                              Subtarget, DAG);
16062       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16063                                 DAG.getUNDEF(BitcastVT), CmpMask,
16064                                 DAG.getIntPtrConstant(0, dl));
16065       return DAG.getBitcast(Op.getValueType(), Res);
16066     }
16067     case COMI: { // Comparison intrinsics
16068       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16069       SDValue LHS = Op.getOperand(1);
16070       SDValue RHS = Op.getOperand(2);
16071       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16072       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16073       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16074       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16075                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16076       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16077     }
16078     case VSHIFT:
16079       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16080                                  Op.getOperand(1), Op.getOperand(2), DAG);
16081     case VSHIFT_MASK:
16082       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16083                                                       Op.getSimpleValueType(),
16084                                                       Op.getOperand(1),
16085                                                       Op.getOperand(2), DAG),
16086                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16087                                   DAG);
16088     case COMPRESS_EXPAND_IN_REG: {
16089       SDValue Mask = Op.getOperand(3);
16090       SDValue DataToCompress = Op.getOperand(1);
16091       SDValue PassThru = Op.getOperand(2);
16092       if (isAllOnes(Mask)) // return data as is
16093         return Op.getOperand(1);
16094
16095       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16096                                               DataToCompress),
16097                                   Mask, PassThru, Subtarget, DAG);
16098     }
16099     case BLEND: {
16100       SDValue Mask = Op.getOperand(3);
16101       EVT VT = Op.getValueType();
16102       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16103                                     VT.getVectorNumElements());
16104       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16105                                        Mask.getValueType().getSizeInBits());
16106       SDLoc dl(Op);
16107       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16108                                   DAG.getBitcast(BitcastVT, Mask),
16109                                   DAG.getIntPtrConstant(0, dl));
16110       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16111                          Op.getOperand(2));
16112     }
16113     default:
16114       break;
16115     }
16116   }
16117
16118   switch (IntNo) {
16119   default: return SDValue();    // Don't custom lower most intrinsics.
16120
16121   case Intrinsic::x86_avx2_permd:
16122   case Intrinsic::x86_avx2_permps:
16123     // Operands intentionally swapped. Mask is last operand to intrinsic,
16124     // but second operand for node/instruction.
16125     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16126                        Op.getOperand(2), Op.getOperand(1));
16127
16128   // ptest and testp intrinsics. The intrinsic these come from are designed to
16129   // return an integer value, not just an instruction so lower it to the ptest
16130   // or testp pattern and a setcc for the result.
16131   case Intrinsic::x86_sse41_ptestz:
16132   case Intrinsic::x86_sse41_ptestc:
16133   case Intrinsic::x86_sse41_ptestnzc:
16134   case Intrinsic::x86_avx_ptestz_256:
16135   case Intrinsic::x86_avx_ptestc_256:
16136   case Intrinsic::x86_avx_ptestnzc_256:
16137   case Intrinsic::x86_avx_vtestz_ps:
16138   case Intrinsic::x86_avx_vtestc_ps:
16139   case Intrinsic::x86_avx_vtestnzc_ps:
16140   case Intrinsic::x86_avx_vtestz_pd:
16141   case Intrinsic::x86_avx_vtestc_pd:
16142   case Intrinsic::x86_avx_vtestnzc_pd:
16143   case Intrinsic::x86_avx_vtestz_ps_256:
16144   case Intrinsic::x86_avx_vtestc_ps_256:
16145   case Intrinsic::x86_avx_vtestnzc_ps_256:
16146   case Intrinsic::x86_avx_vtestz_pd_256:
16147   case Intrinsic::x86_avx_vtestc_pd_256:
16148   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16149     bool IsTestPacked = false;
16150     unsigned X86CC;
16151     switch (IntNo) {
16152     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16153     case Intrinsic::x86_avx_vtestz_ps:
16154     case Intrinsic::x86_avx_vtestz_pd:
16155     case Intrinsic::x86_avx_vtestz_ps_256:
16156     case Intrinsic::x86_avx_vtestz_pd_256:
16157       IsTestPacked = true; // Fallthrough
16158     case Intrinsic::x86_sse41_ptestz:
16159     case Intrinsic::x86_avx_ptestz_256:
16160       // ZF = 1
16161       X86CC = X86::COND_E;
16162       break;
16163     case Intrinsic::x86_avx_vtestc_ps:
16164     case Intrinsic::x86_avx_vtestc_pd:
16165     case Intrinsic::x86_avx_vtestc_ps_256:
16166     case Intrinsic::x86_avx_vtestc_pd_256:
16167       IsTestPacked = true; // Fallthrough
16168     case Intrinsic::x86_sse41_ptestc:
16169     case Intrinsic::x86_avx_ptestc_256:
16170       // CF = 1
16171       X86CC = X86::COND_B;
16172       break;
16173     case Intrinsic::x86_avx_vtestnzc_ps:
16174     case Intrinsic::x86_avx_vtestnzc_pd:
16175     case Intrinsic::x86_avx_vtestnzc_ps_256:
16176     case Intrinsic::x86_avx_vtestnzc_pd_256:
16177       IsTestPacked = true; // Fallthrough
16178     case Intrinsic::x86_sse41_ptestnzc:
16179     case Intrinsic::x86_avx_ptestnzc_256:
16180       // ZF and CF = 0
16181       X86CC = X86::COND_A;
16182       break;
16183     }
16184
16185     SDValue LHS = Op.getOperand(1);
16186     SDValue RHS = Op.getOperand(2);
16187     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16188     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16189     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16190     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16191     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16192   }
16193   case Intrinsic::x86_avx512_kortestz_w:
16194   case Intrinsic::x86_avx512_kortestc_w: {
16195     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16196     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16197     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16198     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16199     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16200     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16201     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16202   }
16203
16204   case Intrinsic::x86_sse42_pcmpistria128:
16205   case Intrinsic::x86_sse42_pcmpestria128:
16206   case Intrinsic::x86_sse42_pcmpistric128:
16207   case Intrinsic::x86_sse42_pcmpestric128:
16208   case Intrinsic::x86_sse42_pcmpistrio128:
16209   case Intrinsic::x86_sse42_pcmpestrio128:
16210   case Intrinsic::x86_sse42_pcmpistris128:
16211   case Intrinsic::x86_sse42_pcmpestris128:
16212   case Intrinsic::x86_sse42_pcmpistriz128:
16213   case Intrinsic::x86_sse42_pcmpestriz128: {
16214     unsigned Opcode;
16215     unsigned X86CC;
16216     switch (IntNo) {
16217     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16218     case Intrinsic::x86_sse42_pcmpistria128:
16219       Opcode = X86ISD::PCMPISTRI;
16220       X86CC = X86::COND_A;
16221       break;
16222     case Intrinsic::x86_sse42_pcmpestria128:
16223       Opcode = X86ISD::PCMPESTRI;
16224       X86CC = X86::COND_A;
16225       break;
16226     case Intrinsic::x86_sse42_pcmpistric128:
16227       Opcode = X86ISD::PCMPISTRI;
16228       X86CC = X86::COND_B;
16229       break;
16230     case Intrinsic::x86_sse42_pcmpestric128:
16231       Opcode = X86ISD::PCMPESTRI;
16232       X86CC = X86::COND_B;
16233       break;
16234     case Intrinsic::x86_sse42_pcmpistrio128:
16235       Opcode = X86ISD::PCMPISTRI;
16236       X86CC = X86::COND_O;
16237       break;
16238     case Intrinsic::x86_sse42_pcmpestrio128:
16239       Opcode = X86ISD::PCMPESTRI;
16240       X86CC = X86::COND_O;
16241       break;
16242     case Intrinsic::x86_sse42_pcmpistris128:
16243       Opcode = X86ISD::PCMPISTRI;
16244       X86CC = X86::COND_S;
16245       break;
16246     case Intrinsic::x86_sse42_pcmpestris128:
16247       Opcode = X86ISD::PCMPESTRI;
16248       X86CC = X86::COND_S;
16249       break;
16250     case Intrinsic::x86_sse42_pcmpistriz128:
16251       Opcode = X86ISD::PCMPISTRI;
16252       X86CC = X86::COND_E;
16253       break;
16254     case Intrinsic::x86_sse42_pcmpestriz128:
16255       Opcode = X86ISD::PCMPESTRI;
16256       X86CC = X86::COND_E;
16257       break;
16258     }
16259     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16260     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16261     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16262     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16263                                 DAG.getConstant(X86CC, dl, MVT::i8),
16264                                 SDValue(PCMP.getNode(), 1));
16265     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16266   }
16267
16268   case Intrinsic::x86_sse42_pcmpistri128:
16269   case Intrinsic::x86_sse42_pcmpestri128: {
16270     unsigned Opcode;
16271     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16272       Opcode = X86ISD::PCMPISTRI;
16273     else
16274       Opcode = X86ISD::PCMPESTRI;
16275
16276     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16277     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16278     return DAG.getNode(Opcode, dl, VTs, NewOps);
16279   }
16280
16281   case Intrinsic::x86_seh_lsda: {
16282     // Compute the symbol for the LSDA. We know it'll get emitted later.
16283     MachineFunction &MF = DAG.getMachineFunction();
16284     SDValue Op1 = Op.getOperand(1);
16285     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16286     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16287         GlobalValue::getRealLinkageName(Fn->getName()));
16288
16289     // Generate a simple absolute symbol reference. This intrinsic is only
16290     // supported on 32-bit Windows, which isn't PIC.
16291     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16292     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16293   }
16294
16295   case Intrinsic::x86_seh_recoverfp: {
16296     SDValue FnOp = Op.getOperand(1);
16297     SDValue IncomingFPOp = Op.getOperand(2);
16298     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16299     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16300     if (!Fn)
16301       report_fatal_error(
16302           "llvm.x86.seh.recoverfp must take a function as the first argument");
16303     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16304   }
16305
16306   case Intrinsic::localaddress: {
16307     // Returns one of the stack, base, or frame pointer registers, depending on
16308     // which is used to reference local variables.
16309     MachineFunction &MF = DAG.getMachineFunction();
16310     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16311     unsigned Reg;
16312     if (RegInfo->hasBasePointer(MF))
16313       Reg = RegInfo->getBaseRegister();
16314     else // This function handles the SP or FP case.
16315       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16316     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16317   }
16318   }
16319 }
16320
16321 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16322                               SDValue Src, SDValue Mask, SDValue Base,
16323                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16324                               const X86Subtarget * Subtarget) {
16325   SDLoc dl(Op);
16326   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16327   if (!C)
16328     llvm_unreachable("Invalid scale type");
16329   unsigned ScaleVal = C->getZExtValue();
16330   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16331     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16332
16333   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16334   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16335                              Index.getSimpleValueType().getVectorNumElements());
16336   SDValue MaskInReg;
16337   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16338   if (MaskC)
16339     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16340   else {
16341     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16342                                      Mask.getValueType().getSizeInBits());
16343
16344     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16345     // are extracted by EXTRACT_SUBVECTOR.
16346     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16347                             DAG.getBitcast(BitcastVT, Mask),
16348                             DAG.getIntPtrConstant(0, dl));
16349   }
16350   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16351   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16352   SDValue Segment = DAG.getRegister(0, MVT::i32);
16353   if (Src.getOpcode() == ISD::UNDEF)
16354     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16355   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16356   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16357   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16358   return DAG.getMergeValues(RetOps, dl);
16359 }
16360
16361 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16362                                SDValue Src, SDValue Mask, SDValue Base,
16363                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16364   SDLoc dl(Op);
16365   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16366   if (!C)
16367     llvm_unreachable("Invalid scale type");
16368   unsigned ScaleVal = C->getZExtValue();
16369   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16370     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16371
16372   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16373   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16374   SDValue Segment = DAG.getRegister(0, MVT::i32);
16375   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16376                              Index.getSimpleValueType().getVectorNumElements());
16377   SDValue MaskInReg;
16378   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16379   if (MaskC)
16380     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16381   else {
16382     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16383                                      Mask.getValueType().getSizeInBits());
16384
16385     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16386     // are extracted by EXTRACT_SUBVECTOR.
16387     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16388                             DAG.getBitcast(BitcastVT, Mask),
16389                             DAG.getIntPtrConstant(0, dl));
16390   }
16391   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16392   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16393   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16394   return SDValue(Res, 1);
16395 }
16396
16397 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16398                                SDValue Mask, SDValue Base, SDValue Index,
16399                                SDValue ScaleOp, SDValue Chain) {
16400   SDLoc dl(Op);
16401   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16402   assert(C && "Invalid scale type");
16403   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16404   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16405   SDValue Segment = DAG.getRegister(0, MVT::i32);
16406   EVT MaskVT =
16407     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16408   SDValue MaskInReg;
16409   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16410   if (MaskC)
16411     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16412   else
16413     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16414   //SDVTList VTs = DAG.getVTList(MVT::Other);
16415   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16416   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16417   return SDValue(Res, 0);
16418 }
16419
16420 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16421 // read performance monitor counters (x86_rdpmc).
16422 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16423                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16424                               SmallVectorImpl<SDValue> &Results) {
16425   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16426   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16427   SDValue LO, HI;
16428
16429   // The ECX register is used to select the index of the performance counter
16430   // to read.
16431   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16432                                    N->getOperand(2));
16433   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16434
16435   // Reads the content of a 64-bit performance counter and returns it in the
16436   // registers EDX:EAX.
16437   if (Subtarget->is64Bit()) {
16438     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16439     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16440                             LO.getValue(2));
16441   } else {
16442     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16443     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16444                             LO.getValue(2));
16445   }
16446   Chain = HI.getValue(1);
16447
16448   if (Subtarget->is64Bit()) {
16449     // The EAX register is loaded with the low-order 32 bits. The EDX register
16450     // is loaded with the supported high-order bits of the counter.
16451     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16452                               DAG.getConstant(32, DL, MVT::i8));
16453     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16454     Results.push_back(Chain);
16455     return;
16456   }
16457
16458   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16459   SDValue Ops[] = { LO, HI };
16460   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16461   Results.push_back(Pair);
16462   Results.push_back(Chain);
16463 }
16464
16465 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16466 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16467 // also used to custom lower READCYCLECOUNTER nodes.
16468 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16469                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16470                               SmallVectorImpl<SDValue> &Results) {
16471   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16472   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16473   SDValue LO, HI;
16474
16475   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16476   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16477   // and the EAX register is loaded with the low-order 32 bits.
16478   if (Subtarget->is64Bit()) {
16479     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16480     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16481                             LO.getValue(2));
16482   } else {
16483     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16484     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16485                             LO.getValue(2));
16486   }
16487   SDValue Chain = HI.getValue(1);
16488
16489   if (Opcode == X86ISD::RDTSCP_DAG) {
16490     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16491
16492     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16493     // the ECX register. Add 'ecx' explicitly to the chain.
16494     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16495                                      HI.getValue(2));
16496     // Explicitly store the content of ECX at the location passed in input
16497     // to the 'rdtscp' intrinsic.
16498     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16499                          MachinePointerInfo(), false, false, 0);
16500   }
16501
16502   if (Subtarget->is64Bit()) {
16503     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16504     // the EAX register is loaded with the low-order 32 bits.
16505     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16506                               DAG.getConstant(32, DL, MVT::i8));
16507     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16508     Results.push_back(Chain);
16509     return;
16510   }
16511
16512   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16513   SDValue Ops[] = { LO, HI };
16514   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16515   Results.push_back(Pair);
16516   Results.push_back(Chain);
16517 }
16518
16519 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16520                                      SelectionDAG &DAG) {
16521   SmallVector<SDValue, 2> Results;
16522   SDLoc DL(Op);
16523   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16524                           Results);
16525   return DAG.getMergeValues(Results, DL);
16526 }
16527
16528 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16529                                     SelectionDAG &DAG) {
16530   MachineFunction &MF = DAG.getMachineFunction();
16531   const Function *Fn = MF.getFunction();
16532   SDLoc dl(Op);
16533   SDValue Chain = Op.getOperand(0);
16534
16535   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16536          "using llvm.x86.seh.restoreframe requires a frame pointer");
16537
16538   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16539   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16540
16541   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16542   unsigned FrameReg =
16543       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16544   unsigned SPReg = RegInfo->getStackRegister();
16545   unsigned SlotSize = RegInfo->getSlotSize();
16546
16547   // Get incoming EBP.
16548   SDValue IncomingEBP =
16549       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16550
16551   // SP is saved in the first field of every registration node, so load
16552   // [EBP-RegNodeSize] into SP.
16553   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16554   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16555                                DAG.getConstant(-RegNodeSize, dl, VT));
16556   SDValue NewSP =
16557       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16558                   false, VT.getScalarSizeInBits() / 8);
16559   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16560
16561   if (!RegInfo->needsStackRealignment(MF)) {
16562     // Adjust EBP to point back to the original frame position.
16563     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16564     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16565   } else {
16566     assert(RegInfo->hasBasePointer(MF) &&
16567            "functions with Win32 EH must use frame or base pointer register");
16568
16569     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16570     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16571     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16572
16573     // Reload the spilled EBP value, now that the stack and base pointers are
16574     // set up.
16575     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16576     X86FI->setHasSEHFramePtrSave(true);
16577     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16578     X86FI->setSEHFramePtrSaveIndex(FI);
16579     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16580                                 MachinePointerInfo(), false, false, false,
16581                                 VT.getScalarSizeInBits() / 8);
16582     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16583   }
16584
16585   return Chain;
16586 }
16587
16588 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16589 /// return truncate Store/MaskedStore Node
16590 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16591                                                SelectionDAG &DAG,
16592                                                MVT ElementType) {
16593   SDLoc dl(Op);
16594   SDValue Mask = Op.getOperand(4);
16595   SDValue DataToTruncate = Op.getOperand(3);
16596   SDValue Addr = Op.getOperand(2);
16597   SDValue Chain = Op.getOperand(0);
16598
16599   EVT VT  = DataToTruncate.getValueType();
16600   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16601                              ElementType, VT.getVectorNumElements());
16602
16603   if (isAllOnes(Mask)) // return just a truncate store
16604     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16605                              MachinePointerInfo(), SVT, false, false,
16606                              SVT.getScalarSizeInBits()/8);
16607
16608   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16609                                 MVT::i1, VT.getVectorNumElements());
16610   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16611                                    Mask.getValueType().getSizeInBits());
16612   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16613   // are extracted by EXTRACT_SUBVECTOR.
16614   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16615                               DAG.getBitcast(BitcastVT, Mask),
16616                               DAG.getIntPtrConstant(0, dl));
16617
16618   MachineMemOperand *MMO = DAG.getMachineFunction().
16619     getMachineMemOperand(MachinePointerInfo(),
16620                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16621                          SVT.getScalarSizeInBits()/8);
16622
16623   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16624                             VMask, SVT, MMO, true);
16625 }
16626
16627 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16628                                       SelectionDAG &DAG) {
16629   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16630
16631   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16632   if (!IntrData) {
16633     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16634       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16635     return SDValue();
16636   }
16637
16638   SDLoc dl(Op);
16639   switch(IntrData->Type) {
16640   default:
16641     llvm_unreachable("Unknown Intrinsic Type");
16642     break;
16643   case RDSEED:
16644   case RDRAND: {
16645     // Emit the node with the right value type.
16646     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16647     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16648
16649     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16650     // Otherwise return the value from Rand, which is always 0, casted to i32.
16651     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16652                       DAG.getConstant(1, dl, Op->getValueType(1)),
16653                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16654                       SDValue(Result.getNode(), 1) };
16655     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16656                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16657                                   Ops);
16658
16659     // Return { result, isValid, chain }.
16660     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16661                        SDValue(Result.getNode(), 2));
16662   }
16663   case GATHER: {
16664   //gather(v1, mask, index, base, scale);
16665     SDValue Chain = Op.getOperand(0);
16666     SDValue Src   = Op.getOperand(2);
16667     SDValue Base  = Op.getOperand(3);
16668     SDValue Index = Op.getOperand(4);
16669     SDValue Mask  = Op.getOperand(5);
16670     SDValue Scale = Op.getOperand(6);
16671     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16672                          Chain, Subtarget);
16673   }
16674   case SCATTER: {
16675   //scatter(base, mask, index, v1, scale);
16676     SDValue Chain = Op.getOperand(0);
16677     SDValue Base  = Op.getOperand(2);
16678     SDValue Mask  = Op.getOperand(3);
16679     SDValue Index = Op.getOperand(4);
16680     SDValue Src   = Op.getOperand(5);
16681     SDValue Scale = Op.getOperand(6);
16682     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16683                           Scale, Chain);
16684   }
16685   case PREFETCH: {
16686     SDValue Hint = Op.getOperand(6);
16687     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16688     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16689     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16690     SDValue Chain = Op.getOperand(0);
16691     SDValue Mask  = Op.getOperand(2);
16692     SDValue Index = Op.getOperand(3);
16693     SDValue Base  = Op.getOperand(4);
16694     SDValue Scale = Op.getOperand(5);
16695     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16696   }
16697   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16698   case RDTSC: {
16699     SmallVector<SDValue, 2> Results;
16700     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16701                             Results);
16702     return DAG.getMergeValues(Results, dl);
16703   }
16704   // Read Performance Monitoring Counters.
16705   case RDPMC: {
16706     SmallVector<SDValue, 2> Results;
16707     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16708     return DAG.getMergeValues(Results, dl);
16709   }
16710   // XTEST intrinsics.
16711   case XTEST: {
16712     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16713     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16714     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16715                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16716                                 InTrans);
16717     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16718     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16719                        Ret, SDValue(InTrans.getNode(), 1));
16720   }
16721   // ADC/ADCX/SBB
16722   case ADX: {
16723     SmallVector<SDValue, 2> Results;
16724     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16725     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16726     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16727                                 DAG.getConstant(-1, dl, MVT::i8));
16728     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16729                               Op.getOperand(4), GenCF.getValue(1));
16730     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16731                                  Op.getOperand(5), MachinePointerInfo(),
16732                                  false, false, 0);
16733     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16734                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16735                                 Res.getValue(1));
16736     Results.push_back(SetCC);
16737     Results.push_back(Store);
16738     return DAG.getMergeValues(Results, dl);
16739   }
16740   case COMPRESS_TO_MEM: {
16741     SDLoc dl(Op);
16742     SDValue Mask = Op.getOperand(4);
16743     SDValue DataToCompress = Op.getOperand(3);
16744     SDValue Addr = Op.getOperand(2);
16745     SDValue Chain = Op.getOperand(0);
16746
16747     EVT VT = DataToCompress.getValueType();
16748     if (isAllOnes(Mask)) // return just a store
16749       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16750                           MachinePointerInfo(), false, false,
16751                           VT.getScalarSizeInBits()/8);
16752
16753     SDValue Compressed =
16754       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16755                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16756     return DAG.getStore(Chain, dl, Compressed, Addr,
16757                         MachinePointerInfo(), false, false,
16758                         VT.getScalarSizeInBits()/8);
16759   }
16760   case TRUNCATE_TO_MEM_VI8:
16761     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16762   case TRUNCATE_TO_MEM_VI16:
16763     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16764   case TRUNCATE_TO_MEM_VI32:
16765     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16766   case EXPAND_FROM_MEM: {
16767     SDLoc dl(Op);
16768     SDValue Mask = Op.getOperand(4);
16769     SDValue PassThru = Op.getOperand(3);
16770     SDValue Addr = Op.getOperand(2);
16771     SDValue Chain = Op.getOperand(0);
16772     EVT VT = Op.getValueType();
16773
16774     if (isAllOnes(Mask)) // return just a load
16775       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16776                          false, VT.getScalarSizeInBits()/8);
16777
16778     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16779                                        false, false, false,
16780                                        VT.getScalarSizeInBits()/8);
16781
16782     SDValue Results[] = {
16783       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16784                            Mask, PassThru, Subtarget, DAG), Chain};
16785     return DAG.getMergeValues(Results, dl);
16786   }
16787   }
16788 }
16789
16790 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16791                                            SelectionDAG &DAG) const {
16792   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16793   MFI->setReturnAddressIsTaken(true);
16794
16795   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16796     return SDValue();
16797
16798   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16799   SDLoc dl(Op);
16800   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16801
16802   if (Depth > 0) {
16803     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16804     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16805     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16806     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16807                        DAG.getNode(ISD::ADD, dl, PtrVT,
16808                                    FrameAddr, Offset),
16809                        MachinePointerInfo(), false, false, false, 0);
16810   }
16811
16812   // Just load the return address.
16813   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16814   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16815                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16816 }
16817
16818 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16819   MachineFunction &MF = DAG.getMachineFunction();
16820   MachineFrameInfo *MFI = MF.getFrameInfo();
16821   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16822   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16823   EVT VT = Op.getValueType();
16824
16825   MFI->setFrameAddressIsTaken(true);
16826
16827   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16828     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16829     // is not possible to crawl up the stack without looking at the unwind codes
16830     // simultaneously.
16831     int FrameAddrIndex = FuncInfo->getFAIndex();
16832     if (!FrameAddrIndex) {
16833       // Set up a frame object for the return address.
16834       unsigned SlotSize = RegInfo->getSlotSize();
16835       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16836           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16837       FuncInfo->setFAIndex(FrameAddrIndex);
16838     }
16839     return DAG.getFrameIndex(FrameAddrIndex, VT);
16840   }
16841
16842   unsigned FrameReg =
16843       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16844   SDLoc dl(Op);  // FIXME probably not meaningful
16845   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16846   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16847           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16848          "Invalid Frame Register!");
16849   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16850   while (Depth--)
16851     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16852                             MachinePointerInfo(),
16853                             false, false, false, 0);
16854   return FrameAddr;
16855 }
16856
16857 // FIXME? Maybe this could be a TableGen attribute on some registers and
16858 // this table could be generated automatically from RegInfo.
16859 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16860                                               SelectionDAG &DAG) const {
16861   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16862   const MachineFunction &MF = DAG.getMachineFunction();
16863
16864   unsigned Reg = StringSwitch<unsigned>(RegName)
16865                        .Case("esp", X86::ESP)
16866                        .Case("rsp", X86::RSP)
16867                        .Case("ebp", X86::EBP)
16868                        .Case("rbp", X86::RBP)
16869                        .Default(0);
16870
16871   if (Reg == X86::EBP || Reg == X86::RBP) {
16872     if (!TFI.hasFP(MF))
16873       report_fatal_error("register " + StringRef(RegName) +
16874                          " is allocatable: function has no frame pointer");
16875 #ifndef NDEBUG
16876     else {
16877       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16878       unsigned FrameReg =
16879           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16880       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16881              "Invalid Frame Register!");
16882     }
16883 #endif
16884   }
16885
16886   if (Reg)
16887     return Reg;
16888
16889   report_fatal_error("Invalid register name global variable");
16890 }
16891
16892 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16893                                                      SelectionDAG &DAG) const {
16894   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16895   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16896 }
16897
16898 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16899   SDValue Chain     = Op.getOperand(0);
16900   SDValue Offset    = Op.getOperand(1);
16901   SDValue Handler   = Op.getOperand(2);
16902   SDLoc dl      (Op);
16903
16904   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16905   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16906   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16907   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16908           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16909          "Invalid Frame Register!");
16910   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16911   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16912
16913   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16914                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16915                                                        dl));
16916   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16917   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16918                        false, false, 0);
16919   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16920
16921   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16922                      DAG.getRegister(StoreAddrReg, PtrVT));
16923 }
16924
16925 SDValue X86TargetLowering::LowerCATCHRET(SDValue Op, SelectionDAG &DAG) const {
16926   SDValue Chain = Op.getOperand(0);
16927   SDValue Dest = Op.getOperand(1);
16928   SDLoc DL(Op);
16929
16930   MVT PtrVT = getPointerTy(DAG.getDataLayout());
16931
16932   MachineFunction &MF = DAG.getMachineFunction();
16933   if (isAsynchronousEHPersonality(
16934           classifyEHPersonality(MF.getFunction()->getPersonalityFn()))) {
16935     // For SEH, codegen catchret as a branch for now.
16936     // FIXME: Insert something to restore the frame.
16937     return DAG.getNode(ISD::BR, DL, MVT::Other, Chain, Dest);
16938   }
16939
16940   unsigned ReturnReg = (PtrVT == MVT::i64 ? X86::RAX : X86::EAX);
16941
16942   // Load the address of the destination block.
16943   // FIXME: Do this without creating a BlockAddress.
16944   MachineBasicBlock *DestMBB = cast<BasicBlockSDNode>(Dest)->getBasicBlock();
16945   BlockAddress *BA =
16946       BlockAddress::get(const_cast<Function *>(MF.getFunction()),
16947                         const_cast<BasicBlock *>(DestMBB->getBasicBlock()));
16948   DestMBB->setHasAddressTaken();
16949   SDValue BlockPtr = DAG.getBlockAddress(BA, PtrVT);
16950   Chain = DAG.getCopyToReg(Chain, DL, ReturnReg, BlockPtr);
16951   return DAG.getNode(X86ISD::CATCHRET, DL, MVT::Other, Chain,
16952                      DAG.getRegister(ReturnReg, PtrVT));
16953 }
16954
16955 SDValue X86TargetLowering::LowerCLEANUPRET(SDValue Op, SelectionDAG &DAG) const {
16956   return DAG.getNode(X86ISD::CLEANUPRET, SDLoc(Op), MVT::Other,
16957                      Op.getOperand(0));
16958 }
16959
16960 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16961                                                SelectionDAG &DAG) const {
16962   SDLoc DL(Op);
16963   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16964                      DAG.getVTList(MVT::i32, MVT::Other),
16965                      Op.getOperand(0), Op.getOperand(1));
16966 }
16967
16968 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16969                                                 SelectionDAG &DAG) const {
16970   SDLoc DL(Op);
16971   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16972                      Op.getOperand(0), Op.getOperand(1));
16973 }
16974
16975 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16976   return Op.getOperand(0);
16977 }
16978
16979 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16980                                                 SelectionDAG &DAG) const {
16981   SDValue Root = Op.getOperand(0);
16982   SDValue Trmp = Op.getOperand(1); // trampoline
16983   SDValue FPtr = Op.getOperand(2); // nested function
16984   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16985   SDLoc dl (Op);
16986
16987   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16988   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16989
16990   if (Subtarget->is64Bit()) {
16991     SDValue OutChains[6];
16992
16993     // Large code-model.
16994     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16995     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16996
16997     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16998     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16999
17000     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17001
17002     // Load the pointer to the nested function into R11.
17003     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17004     SDValue Addr = Trmp;
17005     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17006                                 Addr, MachinePointerInfo(TrmpAddr),
17007                                 false, false, 0);
17008
17009     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17010                        DAG.getConstant(2, dl, MVT::i64));
17011     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17012                                 MachinePointerInfo(TrmpAddr, 2),
17013                                 false, false, 2);
17014
17015     // Load the 'nest' parameter value into R10.
17016     // R10 is specified in X86CallingConv.td
17017     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17018     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17019                        DAG.getConstant(10, dl, MVT::i64));
17020     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17021                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17022                                 false, false, 0);
17023
17024     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17025                        DAG.getConstant(12, dl, MVT::i64));
17026     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17027                                 MachinePointerInfo(TrmpAddr, 12),
17028                                 false, false, 2);
17029
17030     // Jump to the nested function.
17031     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17032     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17033                        DAG.getConstant(20, dl, MVT::i64));
17034     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17035                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17036                                 false, false, 0);
17037
17038     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17039     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17040                        DAG.getConstant(22, dl, MVT::i64));
17041     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17042                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17043                                 false, false, 0);
17044
17045     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17046   } else {
17047     const Function *Func =
17048       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17049     CallingConv::ID CC = Func->getCallingConv();
17050     unsigned NestReg;
17051
17052     switch (CC) {
17053     default:
17054       llvm_unreachable("Unsupported calling convention");
17055     case CallingConv::C:
17056     case CallingConv::X86_StdCall: {
17057       // Pass 'nest' parameter in ECX.
17058       // Must be kept in sync with X86CallingConv.td
17059       NestReg = X86::ECX;
17060
17061       // Check that ECX wasn't needed by an 'inreg' parameter.
17062       FunctionType *FTy = Func->getFunctionType();
17063       const AttributeSet &Attrs = Func->getAttributes();
17064
17065       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17066         unsigned InRegCount = 0;
17067         unsigned Idx = 1;
17068
17069         for (FunctionType::param_iterator I = FTy->param_begin(),
17070              E = FTy->param_end(); I != E; ++I, ++Idx)
17071           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17072             auto &DL = DAG.getDataLayout();
17073             // FIXME: should only count parameters that are lowered to integers.
17074             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17075           }
17076
17077         if (InRegCount > 2) {
17078           report_fatal_error("Nest register in use - reduce number of inreg"
17079                              " parameters!");
17080         }
17081       }
17082       break;
17083     }
17084     case CallingConv::X86_FastCall:
17085     case CallingConv::X86_ThisCall:
17086     case CallingConv::Fast:
17087       // Pass 'nest' parameter in EAX.
17088       // Must be kept in sync with X86CallingConv.td
17089       NestReg = X86::EAX;
17090       break;
17091     }
17092
17093     SDValue OutChains[4];
17094     SDValue Addr, Disp;
17095
17096     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17097                        DAG.getConstant(10, dl, MVT::i32));
17098     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17099
17100     // This is storing the opcode for MOV32ri.
17101     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17102     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17103     OutChains[0] = DAG.getStore(Root, dl,
17104                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17105                                 Trmp, MachinePointerInfo(TrmpAddr),
17106                                 false, false, 0);
17107
17108     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17109                        DAG.getConstant(1, dl, MVT::i32));
17110     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17111                                 MachinePointerInfo(TrmpAddr, 1),
17112                                 false, false, 1);
17113
17114     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17115     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17116                        DAG.getConstant(5, dl, MVT::i32));
17117     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17118                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17119                                 false, false, 1);
17120
17121     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17122                        DAG.getConstant(6, dl, MVT::i32));
17123     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17124                                 MachinePointerInfo(TrmpAddr, 6),
17125                                 false, false, 1);
17126
17127     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17128   }
17129 }
17130
17131 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17132                                             SelectionDAG &DAG) const {
17133   /*
17134    The rounding mode is in bits 11:10 of FPSR, and has the following
17135    settings:
17136      00 Round to nearest
17137      01 Round to -inf
17138      10 Round to +inf
17139      11 Round to 0
17140
17141   FLT_ROUNDS, on the other hand, expects the following:
17142     -1 Undefined
17143      0 Round to 0
17144      1 Round to nearest
17145      2 Round to +inf
17146      3 Round to -inf
17147
17148   To perform the conversion, we do:
17149     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17150   */
17151
17152   MachineFunction &MF = DAG.getMachineFunction();
17153   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17154   unsigned StackAlignment = TFI.getStackAlignment();
17155   MVT VT = Op.getSimpleValueType();
17156   SDLoc DL(Op);
17157
17158   // Save FP Control Word to stack slot
17159   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17160   SDValue StackSlot =
17161       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17162
17163   MachineMemOperand *MMO =
17164       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17165                               MachineMemOperand::MOStore, 2, 2);
17166
17167   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17168   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17169                                           DAG.getVTList(MVT::Other),
17170                                           Ops, MVT::i16, MMO);
17171
17172   // Load FP Control Word from stack slot
17173   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17174                             MachinePointerInfo(), false, false, false, 0);
17175
17176   // Transform as necessary
17177   SDValue CWD1 =
17178     DAG.getNode(ISD::SRL, DL, MVT::i16,
17179                 DAG.getNode(ISD::AND, DL, MVT::i16,
17180                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17181                 DAG.getConstant(11, DL, MVT::i8));
17182   SDValue CWD2 =
17183     DAG.getNode(ISD::SRL, DL, MVT::i16,
17184                 DAG.getNode(ISD::AND, DL, MVT::i16,
17185                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17186                 DAG.getConstant(9, DL, MVT::i8));
17187
17188   SDValue RetVal =
17189     DAG.getNode(ISD::AND, DL, MVT::i16,
17190                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17191                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17192                             DAG.getConstant(1, DL, MVT::i16)),
17193                 DAG.getConstant(3, DL, MVT::i16));
17194
17195   return DAG.getNode((VT.getSizeInBits() < 16 ?
17196                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17197 }
17198
17199 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17200   MVT VT = Op.getSimpleValueType();
17201   EVT OpVT = VT;
17202   unsigned NumBits = VT.getSizeInBits();
17203   SDLoc dl(Op);
17204
17205   Op = Op.getOperand(0);
17206   if (VT == MVT::i8) {
17207     // Zero extend to i32 since there is not an i8 bsr.
17208     OpVT = MVT::i32;
17209     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17210   }
17211
17212   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17213   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17214   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17215
17216   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17217   SDValue Ops[] = {
17218     Op,
17219     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17220     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17221     Op.getValue(1)
17222   };
17223   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17224
17225   // Finally xor with NumBits-1.
17226   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17227                    DAG.getConstant(NumBits - 1, dl, OpVT));
17228
17229   if (VT == MVT::i8)
17230     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17231   return Op;
17232 }
17233
17234 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17235   MVT VT = Op.getSimpleValueType();
17236   EVT OpVT = VT;
17237   unsigned NumBits = VT.getSizeInBits();
17238   SDLoc dl(Op);
17239
17240   Op = Op.getOperand(0);
17241   if (VT == MVT::i8) {
17242     // Zero extend to i32 since there is not an i8 bsr.
17243     OpVT = MVT::i32;
17244     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17245   }
17246
17247   // Issue a bsr (scan bits in reverse).
17248   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17249   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17250
17251   // And xor with NumBits-1.
17252   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17253                    DAG.getConstant(NumBits - 1, dl, OpVT));
17254
17255   if (VT == MVT::i8)
17256     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17257   return Op;
17258 }
17259
17260 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17261   MVT VT = Op.getSimpleValueType();
17262   unsigned NumBits = VT.getSizeInBits();
17263   SDLoc dl(Op);
17264   Op = Op.getOperand(0);
17265
17266   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17267   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17268   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
17269
17270   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17271   SDValue Ops[] = {
17272     Op,
17273     DAG.getConstant(NumBits, dl, VT),
17274     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17275     Op.getValue(1)
17276   };
17277   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17278 }
17279
17280 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17281 // ones, and then concatenate the result back.
17282 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17283   MVT VT = Op.getSimpleValueType();
17284
17285   assert(VT.is256BitVector() && VT.isInteger() &&
17286          "Unsupported value type for operation");
17287
17288   unsigned NumElems = VT.getVectorNumElements();
17289   SDLoc dl(Op);
17290
17291   // Extract the LHS vectors
17292   SDValue LHS = Op.getOperand(0);
17293   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17294   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17295
17296   // Extract the RHS vectors
17297   SDValue RHS = Op.getOperand(1);
17298   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17299   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17300
17301   MVT EltVT = VT.getVectorElementType();
17302   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17303
17304   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17305                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17306                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17307 }
17308
17309 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17310   if (Op.getValueType() == MVT::i1)
17311     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17312                        Op.getOperand(0), Op.getOperand(1));
17313   assert(Op.getSimpleValueType().is256BitVector() &&
17314          Op.getSimpleValueType().isInteger() &&
17315          "Only handle AVX 256-bit vector integer operation");
17316   return Lower256IntArith(Op, DAG);
17317 }
17318
17319 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17320   if (Op.getValueType() == MVT::i1)
17321     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17322                        Op.getOperand(0), Op.getOperand(1));
17323   assert(Op.getSimpleValueType().is256BitVector() &&
17324          Op.getSimpleValueType().isInteger() &&
17325          "Only handle AVX 256-bit vector integer operation");
17326   return Lower256IntArith(Op, DAG);
17327 }
17328
17329 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17330   assert(Op.getSimpleValueType().is256BitVector() &&
17331          Op.getSimpleValueType().isInteger() &&
17332          "Only handle AVX 256-bit vector integer operation");
17333   return Lower256IntArith(Op, DAG);
17334 }
17335
17336 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17337                         SelectionDAG &DAG) {
17338   SDLoc dl(Op);
17339   MVT VT = Op.getSimpleValueType();
17340
17341   if (VT == MVT::i1)
17342     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17343
17344   // Decompose 256-bit ops into smaller 128-bit ops.
17345   if (VT.is256BitVector() && !Subtarget->hasInt256())
17346     return Lower256IntArith(Op, DAG);
17347
17348   SDValue A = Op.getOperand(0);
17349   SDValue B = Op.getOperand(1);
17350
17351   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17352   // pairs, multiply and truncate.
17353   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17354     if (Subtarget->hasInt256()) {
17355       if (VT == MVT::v32i8) {
17356         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17357         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17358         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17359         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17360         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17361         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17362         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17363         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17364                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17365                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17366       }
17367
17368       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17369       return DAG.getNode(
17370           ISD::TRUNCATE, dl, VT,
17371           DAG.getNode(ISD::MUL, dl, ExVT,
17372                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17373                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17374     }
17375
17376     assert(VT == MVT::v16i8 &&
17377            "Pre-AVX2 support only supports v16i8 multiplication");
17378     MVT ExVT = MVT::v8i16;
17379
17380     // Extract the lo parts and sign extend to i16
17381     SDValue ALo, BLo;
17382     if (Subtarget->hasSSE41()) {
17383       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17384       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17385     } else {
17386       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17387                               -1, 4, -1, 5, -1, 6, -1, 7};
17388       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17389       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17390       ALo = DAG.getBitcast(ExVT, ALo);
17391       BLo = DAG.getBitcast(ExVT, BLo);
17392       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17393       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17394     }
17395
17396     // Extract the hi parts and sign extend to i16
17397     SDValue AHi, BHi;
17398     if (Subtarget->hasSSE41()) {
17399       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17400                               -1, -1, -1, -1, -1, -1, -1, -1};
17401       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17402       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17403       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17404       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17405     } else {
17406       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17407                               -1, 12, -1, 13, -1, 14, -1, 15};
17408       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17409       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17410       AHi = DAG.getBitcast(ExVT, AHi);
17411       BHi = DAG.getBitcast(ExVT, BHi);
17412       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17413       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17414     }
17415
17416     // Multiply, mask the lower 8bits of the lo/hi results and pack
17417     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17418     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17419     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17420     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17421     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17422   }
17423
17424   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17425   if (VT == MVT::v4i32) {
17426     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17427            "Should not custom lower when pmuldq is available!");
17428
17429     // Extract the odd parts.
17430     static const int UnpackMask[] = { 1, -1, 3, -1 };
17431     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17432     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17433
17434     // Multiply the even parts.
17435     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17436     // Now multiply odd parts.
17437     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17438
17439     Evens = DAG.getBitcast(VT, Evens);
17440     Odds = DAG.getBitcast(VT, Odds);
17441
17442     // Merge the two vectors back together with a shuffle. This expands into 2
17443     // shuffles.
17444     static const int ShufMask[] = { 0, 4, 2, 6 };
17445     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17446   }
17447
17448   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17449          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17450
17451   //  Ahi = psrlqi(a, 32);
17452   //  Bhi = psrlqi(b, 32);
17453   //
17454   //  AloBlo = pmuludq(a, b);
17455   //  AloBhi = pmuludq(a, Bhi);
17456   //  AhiBlo = pmuludq(Ahi, b);
17457
17458   //  AloBhi = psllqi(AloBhi, 32);
17459   //  AhiBlo = psllqi(AhiBlo, 32);
17460   //  return AloBlo + AloBhi + AhiBlo;
17461
17462   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17463   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17464
17465   SDValue AhiBlo = Ahi;
17466   SDValue AloBhi = Bhi;
17467   // Bit cast to 32-bit vectors for MULUDQ
17468   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17469                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17470   A = DAG.getBitcast(MulVT, A);
17471   B = DAG.getBitcast(MulVT, B);
17472   Ahi = DAG.getBitcast(MulVT, Ahi);
17473   Bhi = DAG.getBitcast(MulVT, Bhi);
17474
17475   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17476   // After shifting right const values the result may be all-zero.
17477   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17478     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17479     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17480   }
17481   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17482     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17483     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17484   }
17485
17486   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17487   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17488 }
17489
17490 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17491   assert(Subtarget->isTargetWin64() && "Unexpected target");
17492   EVT VT = Op.getValueType();
17493   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17494          "Unexpected return type for lowering");
17495
17496   RTLIB::Libcall LC;
17497   bool isSigned;
17498   switch (Op->getOpcode()) {
17499   default: llvm_unreachable("Unexpected request for libcall!");
17500   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17501   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17502   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17503   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17504   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17505   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17506   }
17507
17508   SDLoc dl(Op);
17509   SDValue InChain = DAG.getEntryNode();
17510
17511   TargetLowering::ArgListTy Args;
17512   TargetLowering::ArgListEntry Entry;
17513   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17514     EVT ArgVT = Op->getOperand(i).getValueType();
17515     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17516            "Unexpected argument type for lowering");
17517     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17518     Entry.Node = StackPtr;
17519     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17520                            false, false, 16);
17521     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17522     Entry.Ty = PointerType::get(ArgTy,0);
17523     Entry.isSExt = false;
17524     Entry.isZExt = false;
17525     Args.push_back(Entry);
17526   }
17527
17528   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17529                                          getPointerTy(DAG.getDataLayout()));
17530
17531   TargetLowering::CallLoweringInfo CLI(DAG);
17532   CLI.setDebugLoc(dl).setChain(InChain)
17533     .setCallee(getLibcallCallingConv(LC),
17534                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17535                Callee, std::move(Args), 0)
17536     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17537
17538   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17539   return DAG.getBitcast(VT, CallInfo.first);
17540 }
17541
17542 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17543                              SelectionDAG &DAG) {
17544   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17545   EVT VT = Op0.getValueType();
17546   SDLoc dl(Op);
17547
17548   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17549          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17550
17551   // PMULxD operations multiply each even value (starting at 0) of LHS with
17552   // the related value of RHS and produce a widen result.
17553   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17554   // => <2 x i64> <ae|cg>
17555   //
17556   // In other word, to have all the results, we need to perform two PMULxD:
17557   // 1. one with the even values.
17558   // 2. one with the odd values.
17559   // To achieve #2, with need to place the odd values at an even position.
17560   //
17561   // Place the odd value at an even position (basically, shift all values 1
17562   // step to the left):
17563   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17564   // <a|b|c|d> => <b|undef|d|undef>
17565   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17566   // <e|f|g|h> => <f|undef|h|undef>
17567   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17568
17569   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17570   // ints.
17571   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17572   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17573   unsigned Opcode =
17574       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17575   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17576   // => <2 x i64> <ae|cg>
17577   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17578   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17579   // => <2 x i64> <bf|dh>
17580   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17581
17582   // Shuffle it back into the right order.
17583   SDValue Highs, Lows;
17584   if (VT == MVT::v8i32) {
17585     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17586     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17587     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17588     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17589   } else {
17590     const int HighMask[] = {1, 5, 3, 7};
17591     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17592     const int LowMask[] = {0, 4, 2, 6};
17593     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17594   }
17595
17596   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17597   // unsigned multiply.
17598   if (IsSigned && !Subtarget->hasSSE41()) {
17599     SDValue ShAmt = DAG.getConstant(
17600         31, dl,
17601         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17602     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17603                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17604     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17605                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17606
17607     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17608     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17609   }
17610
17611   // The first result of MUL_LOHI is actually the low value, followed by the
17612   // high value.
17613   SDValue Ops[] = {Lows, Highs};
17614   return DAG.getMergeValues(Ops, dl);
17615 }
17616
17617 // Return true if the required (according to Opcode) shift-imm form is natively
17618 // supported by the Subtarget
17619 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17620                                         unsigned Opcode) {
17621   if (VT.getScalarSizeInBits() < 16)
17622     return false;
17623
17624   if (VT.is512BitVector() &&
17625       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17626     return true;
17627
17628   bool LShift = VT.is128BitVector() ||
17629     (VT.is256BitVector() && Subtarget->hasInt256());
17630
17631   bool AShift = LShift && (Subtarget->hasVLX() ||
17632     (VT != MVT::v2i64 && VT != MVT::v4i64));
17633   return (Opcode == ISD::SRA) ? AShift : LShift;
17634 }
17635
17636 // The shift amount is a variable, but it is the same for all vector lanes.
17637 // These instructions are defined together with shift-immediate.
17638 static
17639 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17640                                       unsigned Opcode) {
17641   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17642 }
17643
17644 // Return true if the required (according to Opcode) variable-shift form is
17645 // natively supported by the Subtarget
17646 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17647                                     unsigned Opcode) {
17648
17649   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17650     return false;
17651
17652   // vXi16 supported only on AVX-512, BWI
17653   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17654     return false;
17655
17656   if (VT.is512BitVector() || Subtarget->hasVLX())
17657     return true;
17658
17659   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17660   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17661   return (Opcode == ISD::SRA) ? AShift : LShift;
17662 }
17663
17664 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17665                                          const X86Subtarget *Subtarget) {
17666   MVT VT = Op.getSimpleValueType();
17667   SDLoc dl(Op);
17668   SDValue R = Op.getOperand(0);
17669   SDValue Amt = Op.getOperand(1);
17670
17671   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17672     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17673
17674   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17675     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17676     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17677     SDValue Ex = DAG.getBitcast(ExVT, R);
17678
17679     if (ShiftAmt >= 32) {
17680       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17681       SDValue Upper =
17682           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17683       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17684                                                  ShiftAmt - 32, DAG);
17685       if (VT == MVT::v2i64)
17686         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17687       if (VT == MVT::v4i64)
17688         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17689                                   {9, 1, 11, 3, 13, 5, 15, 7});
17690     } else {
17691       // SRA upper i32, SHL whole i64 and select lower i32.
17692       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17693                                                  ShiftAmt, DAG);
17694       SDValue Lower =
17695           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17696       Lower = DAG.getBitcast(ExVT, Lower);
17697       if (VT == MVT::v2i64)
17698         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17699       if (VT == MVT::v4i64)
17700         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17701                                   {8, 1, 10, 3, 12, 5, 14, 7});
17702     }
17703     return DAG.getBitcast(VT, Ex);
17704   };
17705
17706   // Optimize shl/srl/sra with constant shift amount.
17707   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17708     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17709       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17710
17711       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17712         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17713
17714       // i64 SRA needs to be performed as partial shifts.
17715       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17716           Op.getOpcode() == ISD::SRA)
17717         return ArithmeticShiftRight64(ShiftAmt);
17718
17719       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17720         unsigned NumElts = VT.getVectorNumElements();
17721         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17722
17723         if (Op.getOpcode() == ISD::SHL) {
17724           // Simple i8 add case
17725           if (ShiftAmt == 1)
17726             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17727
17728           // Make a large shift.
17729           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17730                                                    R, ShiftAmt, DAG);
17731           SHL = DAG.getBitcast(VT, SHL);
17732           // Zero out the rightmost bits.
17733           SmallVector<SDValue, 32> V(
17734               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17735           return DAG.getNode(ISD::AND, dl, VT, SHL,
17736                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17737         }
17738         if (Op.getOpcode() == ISD::SRL) {
17739           // Make a large shift.
17740           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17741                                                    R, ShiftAmt, DAG);
17742           SRL = DAG.getBitcast(VT, SRL);
17743           // Zero out the leftmost bits.
17744           SmallVector<SDValue, 32> V(
17745               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17746           return DAG.getNode(ISD::AND, dl, VT, SRL,
17747                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17748         }
17749         if (Op.getOpcode() == ISD::SRA) {
17750           if (ShiftAmt == 7) {
17751             // ashr(R, 7)  === cmp_slt(R, 0)
17752             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17753             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17754           }
17755
17756           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17757           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17758           SmallVector<SDValue, 32> V(NumElts,
17759                                      DAG.getConstant(128 >> ShiftAmt, dl,
17760                                                      MVT::i8));
17761           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17762           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17763           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17764           return Res;
17765         }
17766         llvm_unreachable("Unknown shift opcode.");
17767       }
17768     }
17769   }
17770
17771   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17772   if (!Subtarget->is64Bit() &&
17773       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17774
17775     // Peek through any splat that was introduced for i64 shift vectorization.
17776     int SplatIndex = -1;
17777     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17778       if (SVN->isSplat()) {
17779         SplatIndex = SVN->getSplatIndex();
17780         Amt = Amt.getOperand(0);
17781         assert(SplatIndex < (int)VT.getVectorNumElements() &&
17782                "Splat shuffle referencing second operand");
17783       }
17784
17785     if (Amt.getOpcode() != ISD::BITCAST ||
17786         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17787       return SDValue();
17788
17789     Amt = Amt.getOperand(0);
17790     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17791                      VT.getVectorNumElements();
17792     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17793     uint64_t ShiftAmt = 0;
17794     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17795     for (unsigned i = 0; i != Ratio; ++i) {
17796       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17797       if (!C)
17798         return SDValue();
17799       // 6 == Log2(64)
17800       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17801     }
17802
17803     // Check remaining shift amounts (if not a splat).
17804     if (SplatIndex < 0) {
17805       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17806         uint64_t ShAmt = 0;
17807         for (unsigned j = 0; j != Ratio; ++j) {
17808           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17809           if (!C)
17810             return SDValue();
17811           // 6 == Log2(64)
17812           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17813         }
17814         if (ShAmt != ShiftAmt)
17815           return SDValue();
17816       }
17817     }
17818
17819     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17820       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17821
17822     if (Op.getOpcode() == ISD::SRA)
17823       return ArithmeticShiftRight64(ShiftAmt);
17824   }
17825
17826   return SDValue();
17827 }
17828
17829 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17830                                         const X86Subtarget* Subtarget) {
17831   MVT VT = Op.getSimpleValueType();
17832   SDLoc dl(Op);
17833   SDValue R = Op.getOperand(0);
17834   SDValue Amt = Op.getOperand(1);
17835
17836   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17837     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17838
17839   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17840     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17841
17842   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17843     SDValue BaseShAmt;
17844     EVT EltVT = VT.getVectorElementType();
17845
17846     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17847       // Check if this build_vector node is doing a splat.
17848       // If so, then set BaseShAmt equal to the splat value.
17849       BaseShAmt = BV->getSplatValue();
17850       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17851         BaseShAmt = SDValue();
17852     } else {
17853       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17854         Amt = Amt.getOperand(0);
17855
17856       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17857       if (SVN && SVN->isSplat()) {
17858         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17859         SDValue InVec = Amt.getOperand(0);
17860         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17861           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17862                  "Unexpected shuffle index found!");
17863           BaseShAmt = InVec.getOperand(SplatIdx);
17864         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17865            if (ConstantSDNode *C =
17866                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17867              if (C->getZExtValue() == SplatIdx)
17868                BaseShAmt = InVec.getOperand(1);
17869            }
17870         }
17871
17872         if (!BaseShAmt)
17873           // Avoid introducing an extract element from a shuffle.
17874           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17875                                   DAG.getIntPtrConstant(SplatIdx, dl));
17876       }
17877     }
17878
17879     if (BaseShAmt.getNode()) {
17880       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17881       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17882         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17883       else if (EltVT.bitsLT(MVT::i32))
17884         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17885
17886       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17887     }
17888   }
17889
17890   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17891   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17892       Amt.getOpcode() == ISD::BITCAST &&
17893       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17894     Amt = Amt.getOperand(0);
17895     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17896                      VT.getVectorNumElements();
17897     std::vector<SDValue> Vals(Ratio);
17898     for (unsigned i = 0; i != Ratio; ++i)
17899       Vals[i] = Amt.getOperand(i);
17900     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17901       for (unsigned j = 0; j != Ratio; ++j)
17902         if (Vals[j] != Amt.getOperand(i + j))
17903           return SDValue();
17904     }
17905
17906     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17907       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17908   }
17909   return SDValue();
17910 }
17911
17912 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17913                           SelectionDAG &DAG) {
17914   MVT VT = Op.getSimpleValueType();
17915   SDLoc dl(Op);
17916   SDValue R = Op.getOperand(0);
17917   SDValue Amt = Op.getOperand(1);
17918
17919   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17920   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17921
17922   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17923     return V;
17924
17925   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17926       return V;
17927
17928   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17929     return Op;
17930
17931   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17932   // shifts per-lane and then shuffle the partial results back together.
17933   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17934     // Splat the shift amounts so the scalar shifts above will catch it.
17935     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17936     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17937     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17938     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17939     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17940   }
17941
17942   // i64 vector arithmetic shift can be emulated with the transform:
17943   // M = lshr(SIGN_BIT, Amt)
17944   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17945   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17946       Op.getOpcode() == ISD::SRA) {
17947     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17948     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17949     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17950     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17951     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17952     return R;
17953   }
17954
17955   // If possible, lower this packed shift into a vector multiply instead of
17956   // expanding it into a sequence of scalar shifts.
17957   // Do this only if the vector shift count is a constant build_vector.
17958   if (Op.getOpcode() == ISD::SHL &&
17959       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17960        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17961       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17962     SmallVector<SDValue, 8> Elts;
17963     EVT SVT = VT.getScalarType();
17964     unsigned SVTBits = SVT.getSizeInBits();
17965     const APInt &One = APInt(SVTBits, 1);
17966     unsigned NumElems = VT.getVectorNumElements();
17967
17968     for (unsigned i=0; i !=NumElems; ++i) {
17969       SDValue Op = Amt->getOperand(i);
17970       if (Op->getOpcode() == ISD::UNDEF) {
17971         Elts.push_back(Op);
17972         continue;
17973       }
17974
17975       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17976       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17977       uint64_t ShAmt = C.getZExtValue();
17978       if (ShAmt >= SVTBits) {
17979         Elts.push_back(DAG.getUNDEF(SVT));
17980         continue;
17981       }
17982       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17983     }
17984     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17985     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17986   }
17987
17988   // Lower SHL with variable shift amount.
17989   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17990     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17991
17992     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17993                      DAG.getConstant(0x3f800000U, dl, VT));
17994     Op = DAG.getBitcast(MVT::v4f32, Op);
17995     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17996     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17997   }
17998
17999   // If possible, lower this shift as a sequence of two shifts by
18000   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18001   // Example:
18002   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18003   //
18004   // Could be rewritten as:
18005   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18006   //
18007   // The advantage is that the two shifts from the example would be
18008   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18009   // the vector shift into four scalar shifts plus four pairs of vector
18010   // insert/extract.
18011   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18012       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18013     unsigned TargetOpcode = X86ISD::MOVSS;
18014     bool CanBeSimplified;
18015     // The splat value for the first packed shift (the 'X' from the example).
18016     SDValue Amt1 = Amt->getOperand(0);
18017     // The splat value for the second packed shift (the 'Y' from the example).
18018     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18019                                         Amt->getOperand(2);
18020
18021     // See if it is possible to replace this node with a sequence of
18022     // two shifts followed by a MOVSS/MOVSD
18023     if (VT == MVT::v4i32) {
18024       // Check if it is legal to use a MOVSS.
18025       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18026                         Amt2 == Amt->getOperand(3);
18027       if (!CanBeSimplified) {
18028         // Otherwise, check if we can still simplify this node using a MOVSD.
18029         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18030                           Amt->getOperand(2) == Amt->getOperand(3);
18031         TargetOpcode = X86ISD::MOVSD;
18032         Amt2 = Amt->getOperand(2);
18033       }
18034     } else {
18035       // Do similar checks for the case where the machine value type
18036       // is MVT::v8i16.
18037       CanBeSimplified = Amt1 == Amt->getOperand(1);
18038       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18039         CanBeSimplified = Amt2 == Amt->getOperand(i);
18040
18041       if (!CanBeSimplified) {
18042         TargetOpcode = X86ISD::MOVSD;
18043         CanBeSimplified = true;
18044         Amt2 = Amt->getOperand(4);
18045         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18046           CanBeSimplified = Amt1 == Amt->getOperand(i);
18047         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18048           CanBeSimplified = Amt2 == Amt->getOperand(j);
18049       }
18050     }
18051
18052     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18053         isa<ConstantSDNode>(Amt2)) {
18054       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18055       EVT CastVT = MVT::v4i32;
18056       SDValue Splat1 =
18057         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18058       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18059       SDValue Splat2 =
18060         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18061       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18062       if (TargetOpcode == X86ISD::MOVSD)
18063         CastVT = MVT::v2i64;
18064       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18065       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18066       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18067                                             BitCast1, DAG);
18068       return DAG.getBitcast(VT, Result);
18069     }
18070   }
18071
18072   // v4i32 Non Uniform Shifts.
18073   // If the shift amount is constant we can shift each lane using the SSE2
18074   // immediate shifts, else we need to zero-extend each lane to the lower i64
18075   // and shift using the SSE2 variable shifts.
18076   // The separate results can then be blended together.
18077   if (VT == MVT::v4i32) {
18078     unsigned Opc = Op.getOpcode();
18079     SDValue Amt0, Amt1, Amt2, Amt3;
18080     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18081       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18082       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18083       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18084       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18085     } else {
18086       // ISD::SHL is handled above but we include it here for completeness.
18087       switch (Opc) {
18088       default:
18089         llvm_unreachable("Unknown target vector shift node");
18090       case ISD::SHL:
18091         Opc = X86ISD::VSHL;
18092         break;
18093       case ISD::SRL:
18094         Opc = X86ISD::VSRL;
18095         break;
18096       case ISD::SRA:
18097         Opc = X86ISD::VSRA;
18098         break;
18099       }
18100       // The SSE2 shifts use the lower i64 as the same shift amount for
18101       // all lanes and the upper i64 is ignored. These shuffle masks
18102       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18103       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18104       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18105       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18106       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18107       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18108     }
18109
18110     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18111     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18112     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18113     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18114     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18115     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18116     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18117   }
18118
18119   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
18120     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18121     unsigned ShiftOpcode = Op->getOpcode();
18122
18123     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18124       // On SSE41 targets we make use of the fact that VSELECT lowers
18125       // to PBLENDVB which selects bytes based just on the sign bit.
18126       if (Subtarget->hasSSE41()) {
18127         V0 = DAG.getBitcast(VT, V0);
18128         V1 = DAG.getBitcast(VT, V1);
18129         Sel = DAG.getBitcast(VT, Sel);
18130         return DAG.getBitcast(SelVT,
18131                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18132       }
18133       // On pre-SSE41 targets we test for the sign bit by comparing to
18134       // zero - a negative value will set all bits of the lanes to true
18135       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18136       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18137       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18138       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18139     };
18140
18141     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18142     // We can safely do this using i16 shifts as we're only interested in
18143     // the 3 lower bits of each byte.
18144     Amt = DAG.getBitcast(ExtVT, Amt);
18145     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18146     Amt = DAG.getBitcast(VT, Amt);
18147
18148     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18149       // r = VSELECT(r, shift(r, 4), a);
18150       SDValue M =
18151           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18152       R = SignBitSelect(VT, Amt, M, R);
18153
18154       // a += a
18155       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18156
18157       // r = VSELECT(r, shift(r, 2), a);
18158       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18159       R = SignBitSelect(VT, Amt, M, R);
18160
18161       // a += a
18162       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18163
18164       // return VSELECT(r, shift(r, 1), a);
18165       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18166       R = SignBitSelect(VT, Amt, M, R);
18167       return R;
18168     }
18169
18170     if (Op->getOpcode() == ISD::SRA) {
18171       // For SRA we need to unpack each byte to the higher byte of a i16 vector
18172       // so we can correctly sign extend. We don't care what happens to the
18173       // lower byte.
18174       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18175       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18176       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18177       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18178       ALo = DAG.getBitcast(ExtVT, ALo);
18179       AHi = DAG.getBitcast(ExtVT, AHi);
18180       RLo = DAG.getBitcast(ExtVT, RLo);
18181       RHi = DAG.getBitcast(ExtVT, RHi);
18182
18183       // r = VSELECT(r, shift(r, 4), a);
18184       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18185                                 DAG.getConstant(4, dl, ExtVT));
18186       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18187                                 DAG.getConstant(4, dl, ExtVT));
18188       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18189       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18190
18191       // a += a
18192       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18193       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18194
18195       // r = VSELECT(r, shift(r, 2), a);
18196       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18197                         DAG.getConstant(2, dl, ExtVT));
18198       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18199                         DAG.getConstant(2, dl, ExtVT));
18200       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18201       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18202
18203       // a += a
18204       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18205       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18206
18207       // r = VSELECT(r, shift(r, 1), a);
18208       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18209                         DAG.getConstant(1, dl, ExtVT));
18210       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18211                         DAG.getConstant(1, dl, ExtVT));
18212       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18213       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18214
18215       // Logical shift the result back to the lower byte, leaving a zero upper
18216       // byte
18217       // meaning that we can safely pack with PACKUSWB.
18218       RLo =
18219           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18220       RHi =
18221           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18222       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18223     }
18224   }
18225
18226   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18227   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18228   // solution better.
18229   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18230     MVT ExtVT = MVT::v8i32;
18231     unsigned ExtOpc =
18232         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18233     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18234     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18235     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18236                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18237   }
18238
18239   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
18240     MVT ExtVT = MVT::v8i32;
18241     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18242     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18243     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18244     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18245     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18246     ALo = DAG.getBitcast(ExtVT, ALo);
18247     AHi = DAG.getBitcast(ExtVT, AHi);
18248     RLo = DAG.getBitcast(ExtVT, RLo);
18249     RHi = DAG.getBitcast(ExtVT, RHi);
18250     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18251     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18252     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18253     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18254     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18255   }
18256
18257   if (VT == MVT::v8i16) {
18258     unsigned ShiftOpcode = Op->getOpcode();
18259
18260     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18261       // On SSE41 targets we make use of the fact that VSELECT lowers
18262       // to PBLENDVB which selects bytes based just on the sign bit.
18263       if (Subtarget->hasSSE41()) {
18264         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18265         V0 = DAG.getBitcast(ExtVT, V0);
18266         V1 = DAG.getBitcast(ExtVT, V1);
18267         Sel = DAG.getBitcast(ExtVT, Sel);
18268         return DAG.getBitcast(
18269             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18270       }
18271       // On pre-SSE41 targets we splat the sign bit - a negative value will
18272       // set all bits of the lanes to true and VSELECT uses that in
18273       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18274       SDValue C =
18275           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18276       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18277     };
18278
18279     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18280     if (Subtarget->hasSSE41()) {
18281       // On SSE41 targets we need to replicate the shift mask in both
18282       // bytes for PBLENDVB.
18283       Amt = DAG.getNode(
18284           ISD::OR, dl, VT,
18285           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18286           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18287     } else {
18288       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18289     }
18290
18291     // r = VSELECT(r, shift(r, 8), a);
18292     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18293     R = SignBitSelect(Amt, M, R);
18294
18295     // a += a
18296     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18297
18298     // r = VSELECT(r, shift(r, 4), a);
18299     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18300     R = SignBitSelect(Amt, M, R);
18301
18302     // a += a
18303     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18304
18305     // r = VSELECT(r, shift(r, 2), a);
18306     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18307     R = SignBitSelect(Amt, M, R);
18308
18309     // a += a
18310     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18311
18312     // return VSELECT(r, shift(r, 1), a);
18313     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18314     R = SignBitSelect(Amt, M, R);
18315     return R;
18316   }
18317
18318   // Decompose 256-bit shifts into smaller 128-bit shifts.
18319   if (VT.is256BitVector()) {
18320     unsigned NumElems = VT.getVectorNumElements();
18321     MVT EltVT = VT.getVectorElementType();
18322     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18323
18324     // Extract the two vectors
18325     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18326     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18327
18328     // Recreate the shift amount vectors
18329     SDValue Amt1, Amt2;
18330     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18331       // Constant shift amount
18332       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18333       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18334       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18335
18336       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18337       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18338     } else {
18339       // Variable shift amount
18340       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18341       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18342     }
18343
18344     // Issue new vector shifts for the smaller types
18345     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18346     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18347
18348     // Concatenate the result back
18349     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18350   }
18351
18352   return SDValue();
18353 }
18354
18355 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18356   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18357   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18358   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18359   // has only one use.
18360   SDNode *N = Op.getNode();
18361   SDValue LHS = N->getOperand(0);
18362   SDValue RHS = N->getOperand(1);
18363   unsigned BaseOp = 0;
18364   unsigned Cond = 0;
18365   SDLoc DL(Op);
18366   switch (Op.getOpcode()) {
18367   default: llvm_unreachable("Unknown ovf instruction!");
18368   case ISD::SADDO:
18369     // A subtract of one will be selected as a INC. Note that INC doesn't
18370     // set CF, so we can't do this for UADDO.
18371     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18372       if (C->isOne()) {
18373         BaseOp = X86ISD::INC;
18374         Cond = X86::COND_O;
18375         break;
18376       }
18377     BaseOp = X86ISD::ADD;
18378     Cond = X86::COND_O;
18379     break;
18380   case ISD::UADDO:
18381     BaseOp = X86ISD::ADD;
18382     Cond = X86::COND_B;
18383     break;
18384   case ISD::SSUBO:
18385     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18386     // set CF, so we can't do this for USUBO.
18387     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18388       if (C->isOne()) {
18389         BaseOp = X86ISD::DEC;
18390         Cond = X86::COND_O;
18391         break;
18392       }
18393     BaseOp = X86ISD::SUB;
18394     Cond = X86::COND_O;
18395     break;
18396   case ISD::USUBO:
18397     BaseOp = X86ISD::SUB;
18398     Cond = X86::COND_B;
18399     break;
18400   case ISD::SMULO:
18401     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18402     Cond = X86::COND_O;
18403     break;
18404   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18405     if (N->getValueType(0) == MVT::i8) {
18406       BaseOp = X86ISD::UMUL8;
18407       Cond = X86::COND_O;
18408       break;
18409     }
18410     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18411                                  MVT::i32);
18412     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18413
18414     SDValue SetCC =
18415       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18416                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18417                   SDValue(Sum.getNode(), 2));
18418
18419     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18420   }
18421   }
18422
18423   // Also sets EFLAGS.
18424   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18425   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18426
18427   SDValue SetCC =
18428     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18429                 DAG.getConstant(Cond, DL, MVT::i32),
18430                 SDValue(Sum.getNode(), 1));
18431
18432   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18433 }
18434
18435 /// Returns true if the operand type is exactly twice the native width, and
18436 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18437 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18438 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18439 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18440   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18441
18442   if (OpWidth == 64)
18443     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18444   else if (OpWidth == 128)
18445     return Subtarget->hasCmpxchg16b();
18446   else
18447     return false;
18448 }
18449
18450 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18451   return needsCmpXchgNb(SI->getValueOperand()->getType());
18452 }
18453
18454 // Note: this turns large loads into lock cmpxchg8b/16b.
18455 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18456 TargetLowering::AtomicExpansionKind
18457 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18458   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18459   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
18460                                                : AtomicExpansionKind::None;
18461 }
18462
18463 TargetLowering::AtomicExpansionKind
18464 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18465   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18466   Type *MemType = AI->getType();
18467
18468   // If the operand is too big, we must see if cmpxchg8/16b is available
18469   // and default to library calls otherwise.
18470   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18471     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
18472                                    : AtomicExpansionKind::None;
18473   }
18474
18475   AtomicRMWInst::BinOp Op = AI->getOperation();
18476   switch (Op) {
18477   default:
18478     llvm_unreachable("Unknown atomic operation");
18479   case AtomicRMWInst::Xchg:
18480   case AtomicRMWInst::Add:
18481   case AtomicRMWInst::Sub:
18482     // It's better to use xadd, xsub or xchg for these in all cases.
18483     return AtomicExpansionKind::None;
18484   case AtomicRMWInst::Or:
18485   case AtomicRMWInst::And:
18486   case AtomicRMWInst::Xor:
18487     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18488     // prefix to a normal instruction for these operations.
18489     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
18490                             : AtomicExpansionKind::None;
18491   case AtomicRMWInst::Nand:
18492   case AtomicRMWInst::Max:
18493   case AtomicRMWInst::Min:
18494   case AtomicRMWInst::UMax:
18495   case AtomicRMWInst::UMin:
18496     // These always require a non-trivial set of data operations on x86. We must
18497     // use a cmpxchg loop.
18498     return AtomicExpansionKind::CmpXChg;
18499   }
18500 }
18501
18502 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18503   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18504   // no-sse2). There isn't any reason to disable it if the target processor
18505   // supports it.
18506   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18507 }
18508
18509 LoadInst *
18510 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18511   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18512   Type *MemType = AI->getType();
18513   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18514   // there is no benefit in turning such RMWs into loads, and it is actually
18515   // harmful as it introduces a mfence.
18516   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18517     return nullptr;
18518
18519   auto Builder = IRBuilder<>(AI);
18520   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18521   auto SynchScope = AI->getSynchScope();
18522   // We must restrict the ordering to avoid generating loads with Release or
18523   // ReleaseAcquire orderings.
18524   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18525   auto Ptr = AI->getPointerOperand();
18526
18527   // Before the load we need a fence. Here is an example lifted from
18528   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18529   // is required:
18530   // Thread 0:
18531   //   x.store(1, relaxed);
18532   //   r1 = y.fetch_add(0, release);
18533   // Thread 1:
18534   //   y.fetch_add(42, acquire);
18535   //   r2 = x.load(relaxed);
18536   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18537   // lowered to just a load without a fence. A mfence flushes the store buffer,
18538   // making the optimization clearly correct.
18539   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18540   // otherwise, we might be able to be more aggressive on relaxed idempotent
18541   // rmw. In practice, they do not look useful, so we don't try to be
18542   // especially clever.
18543   if (SynchScope == SingleThread)
18544     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18545     // the IR level, so we must wrap it in an intrinsic.
18546     return nullptr;
18547
18548   if (!hasMFENCE(*Subtarget))
18549     // FIXME: it might make sense to use a locked operation here but on a
18550     // different cache-line to prevent cache-line bouncing. In practice it
18551     // is probably a small win, and x86 processors without mfence are rare
18552     // enough that we do not bother.
18553     return nullptr;
18554
18555   Function *MFence =
18556       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18557   Builder.CreateCall(MFence, {});
18558
18559   // Finally we can emit the atomic load.
18560   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18561           AI->getType()->getPrimitiveSizeInBits());
18562   Loaded->setAtomic(Order, SynchScope);
18563   AI->replaceAllUsesWith(Loaded);
18564   AI->eraseFromParent();
18565   return Loaded;
18566 }
18567
18568 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18569                                  SelectionDAG &DAG) {
18570   SDLoc dl(Op);
18571   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18572     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18573   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18574     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18575
18576   // The only fence that needs an instruction is a sequentially-consistent
18577   // cross-thread fence.
18578   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18579     if (hasMFENCE(*Subtarget))
18580       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18581
18582     SDValue Chain = Op.getOperand(0);
18583     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18584     SDValue Ops[] = {
18585       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18586       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18587       DAG.getRegister(0, MVT::i32),            // Index
18588       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18589       DAG.getRegister(0, MVT::i32),            // Segment.
18590       Zero,
18591       Chain
18592     };
18593     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18594     return SDValue(Res, 0);
18595   }
18596
18597   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18598   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18599 }
18600
18601 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18602                              SelectionDAG &DAG) {
18603   MVT T = Op.getSimpleValueType();
18604   SDLoc DL(Op);
18605   unsigned Reg = 0;
18606   unsigned size = 0;
18607   switch(T.SimpleTy) {
18608   default: llvm_unreachable("Invalid value type!");
18609   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18610   case MVT::i16: Reg = X86::AX;  size = 2; break;
18611   case MVT::i32: Reg = X86::EAX; size = 4; break;
18612   case MVT::i64:
18613     assert(Subtarget->is64Bit() && "Node not type legal!");
18614     Reg = X86::RAX; size = 8;
18615     break;
18616   }
18617   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18618                                   Op.getOperand(2), SDValue());
18619   SDValue Ops[] = { cpIn.getValue(0),
18620                     Op.getOperand(1),
18621                     Op.getOperand(3),
18622                     DAG.getTargetConstant(size, DL, MVT::i8),
18623                     cpIn.getValue(1) };
18624   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18625   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18626   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18627                                            Ops, T, MMO);
18628
18629   SDValue cpOut =
18630     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18631   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18632                                       MVT::i32, cpOut.getValue(2));
18633   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18634                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18635                                 EFLAGS);
18636
18637   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18638   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18639   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18640   return SDValue();
18641 }
18642
18643 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18644                             SelectionDAG &DAG) {
18645   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18646   MVT DstVT = Op.getSimpleValueType();
18647
18648   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18649     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18650     if (DstVT != MVT::f64)
18651       // This conversion needs to be expanded.
18652       return SDValue();
18653
18654     SDValue InVec = Op->getOperand(0);
18655     SDLoc dl(Op);
18656     unsigned NumElts = SrcVT.getVectorNumElements();
18657     EVT SVT = SrcVT.getVectorElementType();
18658
18659     // Widen the vector in input in the case of MVT::v2i32.
18660     // Example: from MVT::v2i32 to MVT::v4i32.
18661     SmallVector<SDValue, 16> Elts;
18662     for (unsigned i = 0, e = NumElts; i != e; ++i)
18663       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18664                                  DAG.getIntPtrConstant(i, dl)));
18665
18666     // Explicitly mark the extra elements as Undef.
18667     Elts.append(NumElts, DAG.getUNDEF(SVT));
18668
18669     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18670     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18671     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18672     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18673                        DAG.getIntPtrConstant(0, dl));
18674   }
18675
18676   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18677          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18678   assert((DstVT == MVT::i64 ||
18679           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18680          "Unexpected custom BITCAST");
18681   // i64 <=> MMX conversions are Legal.
18682   if (SrcVT==MVT::i64 && DstVT.isVector())
18683     return Op;
18684   if (DstVT==MVT::i64 && SrcVT.isVector())
18685     return Op;
18686   // MMX <=> MMX conversions are Legal.
18687   if (SrcVT.isVector() && DstVT.isVector())
18688     return Op;
18689   // All other conversions need to be expanded.
18690   return SDValue();
18691 }
18692
18693 /// Compute the horizontal sum of bytes in V for the elements of VT.
18694 ///
18695 /// Requires V to be a byte vector and VT to be an integer vector type with
18696 /// wider elements than V's type. The width of the elements of VT determines
18697 /// how many bytes of V are summed horizontally to produce each element of the
18698 /// result.
18699 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18700                                       const X86Subtarget *Subtarget,
18701                                       SelectionDAG &DAG) {
18702   SDLoc DL(V);
18703   MVT ByteVecVT = V.getSimpleValueType();
18704   MVT EltVT = VT.getVectorElementType();
18705   int NumElts = VT.getVectorNumElements();
18706   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18707          "Expected value to have byte element type.");
18708   assert(EltVT != MVT::i8 &&
18709          "Horizontal byte sum only makes sense for wider elements!");
18710   unsigned VecSize = VT.getSizeInBits();
18711   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18712
18713   // PSADBW instruction horizontally add all bytes and leave the result in i64
18714   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18715   if (EltVT == MVT::i64) {
18716     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18717     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18718     return DAG.getBitcast(VT, V);
18719   }
18720
18721   if (EltVT == MVT::i32) {
18722     // We unpack the low half and high half into i32s interleaved with zeros so
18723     // that we can use PSADBW to horizontally sum them. The most useful part of
18724     // this is that it lines up the results of two PSADBW instructions to be
18725     // two v2i64 vectors which concatenated are the 4 population counts. We can
18726     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18727     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18728     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18729     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18730
18731     // Do the horizontal sums into two v2i64s.
18732     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18733     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18734                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18735     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18736                        DAG.getBitcast(ByteVecVT, High), Zeros);
18737
18738     // Merge them together.
18739     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18740     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18741                     DAG.getBitcast(ShortVecVT, Low),
18742                     DAG.getBitcast(ShortVecVT, High));
18743
18744     return DAG.getBitcast(VT, V);
18745   }
18746
18747   // The only element type left is i16.
18748   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18749
18750   // To obtain pop count for each i16 element starting from the pop count for
18751   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18752   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18753   // directly supported.
18754   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18755   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18756   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18757   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18758                   DAG.getBitcast(ByteVecVT, V));
18759   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18760 }
18761
18762 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18763                                         const X86Subtarget *Subtarget,
18764                                         SelectionDAG &DAG) {
18765   MVT VT = Op.getSimpleValueType();
18766   MVT EltVT = VT.getVectorElementType();
18767   unsigned VecSize = VT.getSizeInBits();
18768
18769   // Implement a lookup table in register by using an algorithm based on:
18770   // http://wm.ite.pl/articles/sse-popcount.html
18771   //
18772   // The general idea is that every lower byte nibble in the input vector is an
18773   // index into a in-register pre-computed pop count table. We then split up the
18774   // input vector in two new ones: (1) a vector with only the shifted-right
18775   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18776   // masked out higher ones) for each byte. PSHUB is used separately with both
18777   // to index the in-register table. Next, both are added and the result is a
18778   // i8 vector where each element contains the pop count for input byte.
18779   //
18780   // To obtain the pop count for elements != i8, we follow up with the same
18781   // approach and use additional tricks as described below.
18782   //
18783   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18784                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18785                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18786                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18787
18788   int NumByteElts = VecSize / 8;
18789   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18790   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18791   SmallVector<SDValue, 16> LUTVec;
18792   for (int i = 0; i < NumByteElts; ++i)
18793     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18794   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18795   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18796                                   DAG.getConstant(0x0F, DL, MVT::i8));
18797   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18798
18799   // High nibbles
18800   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18801   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18802   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18803
18804   // Low nibbles
18805   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18806
18807   // The input vector is used as the shuffle mask that index elements into the
18808   // LUT. After counting low and high nibbles, add the vector to obtain the
18809   // final pop count per i8 element.
18810   SDValue HighPopCnt =
18811       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18812   SDValue LowPopCnt =
18813       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18814   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18815
18816   if (EltVT == MVT::i8)
18817     return PopCnt;
18818
18819   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18820 }
18821
18822 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18823                                        const X86Subtarget *Subtarget,
18824                                        SelectionDAG &DAG) {
18825   MVT VT = Op.getSimpleValueType();
18826   assert(VT.is128BitVector() &&
18827          "Only 128-bit vector bitmath lowering supported.");
18828
18829   int VecSize = VT.getSizeInBits();
18830   MVT EltVT = VT.getVectorElementType();
18831   int Len = EltVT.getSizeInBits();
18832
18833   // This is the vectorized version of the "best" algorithm from
18834   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18835   // with a minor tweak to use a series of adds + shifts instead of vector
18836   // multiplications. Implemented for all integer vector types. We only use
18837   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18838   // much faster, even faster than using native popcnt instructions.
18839
18840   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18841     MVT VT = V.getSimpleValueType();
18842     SmallVector<SDValue, 32> Shifters(
18843         VT.getVectorNumElements(),
18844         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18845     return DAG.getNode(OpCode, DL, VT, V,
18846                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18847   };
18848   auto GetMask = [&](SDValue V, APInt Mask) {
18849     MVT VT = V.getSimpleValueType();
18850     SmallVector<SDValue, 32> Masks(
18851         VT.getVectorNumElements(),
18852         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18853     return DAG.getNode(ISD::AND, DL, VT, V,
18854                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18855   };
18856
18857   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18858   // x86, so set the SRL type to have elements at least i16 wide. This is
18859   // correct because all of our SRLs are followed immediately by a mask anyways
18860   // that handles any bits that sneak into the high bits of the byte elements.
18861   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18862
18863   SDValue V = Op;
18864
18865   // v = v - ((v >> 1) & 0x55555555...)
18866   SDValue Srl =
18867       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18868   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18869   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18870
18871   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18872   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18873   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18874   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18875   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18876
18877   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18878   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18879   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18880   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18881
18882   // At this point, V contains the byte-wise population count, and we are
18883   // merely doing a horizontal sum if necessary to get the wider element
18884   // counts.
18885   if (EltVT == MVT::i8)
18886     return V;
18887
18888   return LowerHorizontalByteSum(
18889       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18890       DAG);
18891 }
18892
18893 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18894                                 SelectionDAG &DAG) {
18895   MVT VT = Op.getSimpleValueType();
18896   // FIXME: Need to add AVX-512 support here!
18897   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18898          "Unknown CTPOP type to handle");
18899   SDLoc DL(Op.getNode());
18900   SDValue Op0 = Op.getOperand(0);
18901
18902   if (!Subtarget->hasSSSE3()) {
18903     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18904     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18905     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18906   }
18907
18908   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18909     unsigned NumElems = VT.getVectorNumElements();
18910
18911     // Extract each 128-bit vector, compute pop count and concat the result.
18912     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18913     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18914
18915     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18916                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18917                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18918   }
18919
18920   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18921 }
18922
18923 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18924                           SelectionDAG &DAG) {
18925   assert(Op.getValueType().isVector() &&
18926          "We only do custom lowering for vector population count.");
18927   return LowerVectorCTPOP(Op, Subtarget, DAG);
18928 }
18929
18930 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18931   SDNode *Node = Op.getNode();
18932   SDLoc dl(Node);
18933   EVT T = Node->getValueType(0);
18934   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18935                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18936   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18937                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18938                        Node->getOperand(0),
18939                        Node->getOperand(1), negOp,
18940                        cast<AtomicSDNode>(Node)->getMemOperand(),
18941                        cast<AtomicSDNode>(Node)->getOrdering(),
18942                        cast<AtomicSDNode>(Node)->getSynchScope());
18943 }
18944
18945 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18946   SDNode *Node = Op.getNode();
18947   SDLoc dl(Node);
18948   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18949
18950   // Convert seq_cst store -> xchg
18951   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18952   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18953   //        (The only way to get a 16-byte store is cmpxchg16b)
18954   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18955   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18956       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18957     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18958                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18959                                  Node->getOperand(0),
18960                                  Node->getOperand(1), Node->getOperand(2),
18961                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18962                                  cast<AtomicSDNode>(Node)->getOrdering(),
18963                                  cast<AtomicSDNode>(Node)->getSynchScope());
18964     return Swap.getValue(1);
18965   }
18966   // Other atomic stores have a simple pattern.
18967   return Op;
18968 }
18969
18970 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18971   EVT VT = Op.getNode()->getSimpleValueType(0);
18972
18973   // Let legalize expand this if it isn't a legal type yet.
18974   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18975     return SDValue();
18976
18977   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18978
18979   unsigned Opc;
18980   bool ExtraOp = false;
18981   switch (Op.getOpcode()) {
18982   default: llvm_unreachable("Invalid code");
18983   case ISD::ADDC: Opc = X86ISD::ADD; break;
18984   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18985   case ISD::SUBC: Opc = X86ISD::SUB; break;
18986   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18987   }
18988
18989   if (!ExtraOp)
18990     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18991                        Op.getOperand(1));
18992   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18993                      Op.getOperand(1), Op.getOperand(2));
18994 }
18995
18996 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18997                             SelectionDAG &DAG) {
18998   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18999
19000   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19001   // which returns the values as { float, float } (in XMM0) or
19002   // { double, double } (which is returned in XMM0, XMM1).
19003   SDLoc dl(Op);
19004   SDValue Arg = Op.getOperand(0);
19005   EVT ArgVT = Arg.getValueType();
19006   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19007
19008   TargetLowering::ArgListTy Args;
19009   TargetLowering::ArgListEntry Entry;
19010
19011   Entry.Node = Arg;
19012   Entry.Ty = ArgTy;
19013   Entry.isSExt = false;
19014   Entry.isZExt = false;
19015   Args.push_back(Entry);
19016
19017   bool isF64 = ArgVT == MVT::f64;
19018   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19019   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19020   // the results are returned via SRet in memory.
19021   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19022   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19023   SDValue Callee =
19024       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19025
19026   Type *RetTy = isF64
19027     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19028     : (Type*)VectorType::get(ArgTy, 4);
19029
19030   TargetLowering::CallLoweringInfo CLI(DAG);
19031   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19032     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19033
19034   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19035
19036   if (isF64)
19037     // Returned in xmm0 and xmm1.
19038     return CallResult.first;
19039
19040   // Returned in bits 0:31 and 32:64 xmm0.
19041   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19042                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19043   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19044                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19045   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19046   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19047 }
19048
19049 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19050                              SelectionDAG &DAG) {
19051   assert(Subtarget->hasAVX512() &&
19052          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19053
19054   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19055   EVT VT = N->getValue().getValueType();
19056   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19057   SDLoc dl(Op);
19058
19059   // X86 scatter kills mask register, so its type should be added to
19060   // the list of return values
19061   if (N->getNumValues() == 1) {
19062     SDValue Index = N->getIndex();
19063     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19064         !Index.getValueType().is512BitVector())
19065       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19066
19067     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19068     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19069                       N->getOperand(3), Index };
19070
19071     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19072     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19073     return SDValue(NewScatter.getNode(), 0);
19074   }
19075   return Op;
19076 }
19077
19078 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19079                             SelectionDAG &DAG) {
19080   assert(Subtarget->hasAVX512() &&
19081          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19082
19083   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19084   EVT VT = Op.getValueType();
19085   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19086   SDLoc dl(Op);
19087
19088   SDValue Index = N->getIndex();
19089   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19090       !Index.getValueType().is512BitVector()) {
19091     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19092     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19093                       N->getOperand(3), Index };
19094     DAG.UpdateNodeOperands(N, Ops);
19095   }
19096   return Op;
19097 }
19098
19099 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19100                                                     SelectionDAG &DAG) const {
19101   // TODO: Eventually, the lowering of these nodes should be informed by or
19102   // deferred to the GC strategy for the function in which they appear. For
19103   // now, however, they must be lowered to something. Since they are logically
19104   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19105   // require special handling for these nodes), lower them as literal NOOPs for
19106   // the time being.
19107   SmallVector<SDValue, 2> Ops;
19108
19109   Ops.push_back(Op.getOperand(0));
19110   if (Op->getGluedNode())
19111     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19112
19113   SDLoc OpDL(Op);
19114   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19115   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19116
19117   return NOOP;
19118 }
19119
19120 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19121                                                   SelectionDAG &DAG) const {
19122   // TODO: Eventually, the lowering of these nodes should be informed by or
19123   // deferred to the GC strategy for the function in which they appear. For
19124   // now, however, they must be lowered to something. Since they are logically
19125   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19126   // require special handling for these nodes), lower them as literal NOOPs for
19127   // the time being.
19128   SmallVector<SDValue, 2> Ops;
19129
19130   Ops.push_back(Op.getOperand(0));
19131   if (Op->getGluedNode())
19132     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19133
19134   SDLoc OpDL(Op);
19135   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19136   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19137
19138   return NOOP;
19139 }
19140
19141 /// LowerOperation - Provide custom lowering hooks for some operations.
19142 ///
19143 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19144   switch (Op.getOpcode()) {
19145   default: llvm_unreachable("Should not custom lower this!");
19146   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19147   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19148     return LowerCMP_SWAP(Op, Subtarget, DAG);
19149   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
19150   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19151   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19152   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19153   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19154   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
19155   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19156   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19157   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19158   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19159   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19160   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19161   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19162   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19163   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19164   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19165   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19166   case ISD::SHL_PARTS:
19167   case ISD::SRA_PARTS:
19168   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19169   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19170   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19171   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19172   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19173   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19174   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19175   case ISD::SIGN_EXTEND_VECTOR_INREG:
19176     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19177   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19178   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19179   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19180   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19181   case ISD::FABS:
19182   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19183   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19184   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19185   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19186   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19187   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19188   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19189   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19190   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19191   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19192   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19193   case ISD::INTRINSIC_VOID:
19194   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19195   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19196   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19197   case ISD::FRAME_TO_ARGS_OFFSET:
19198                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19199   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19200   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19201   case ISD::CLEANUPRET:         return LowerCLEANUPRET(Op, DAG);
19202   case ISD::CATCHRET:           return LowerCATCHRET(Op, DAG);
19203   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19204   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19205   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19206   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19207   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19208   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
19209   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19210   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
19211   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19212   case ISD::UMUL_LOHI:
19213   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19214   case ISD::SRA:
19215   case ISD::SRL:
19216   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19217   case ISD::SADDO:
19218   case ISD::UADDO:
19219   case ISD::SSUBO:
19220   case ISD::USUBO:
19221   case ISD::SMULO:
19222   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19223   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19224   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19225   case ISD::ADDC:
19226   case ISD::ADDE:
19227   case ISD::SUBC:
19228   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19229   case ISD::ADD:                return LowerADD(Op, DAG);
19230   case ISD::SUB:                return LowerSUB(Op, DAG);
19231   case ISD::SMAX:
19232   case ISD::SMIN:
19233   case ISD::UMAX:
19234   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
19235   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19236   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
19237   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
19238   case ISD::GC_TRANSITION_START:
19239                                 return LowerGC_TRANSITION_START(Op, DAG);
19240   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
19241   }
19242 }
19243
19244 /// ReplaceNodeResults - Replace a node with an illegal result type
19245 /// with a new node built out of custom code.
19246 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19247                                            SmallVectorImpl<SDValue>&Results,
19248                                            SelectionDAG &DAG) const {
19249   SDLoc dl(N);
19250   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19251   switch (N->getOpcode()) {
19252   default:
19253     llvm_unreachable("Do not know how to custom type legalize this operation!");
19254   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19255   case X86ISD::FMINC:
19256   case X86ISD::FMIN:
19257   case X86ISD::FMAXC:
19258   case X86ISD::FMAX: {
19259     EVT VT = N->getValueType(0);
19260     if (VT != MVT::v2f32)
19261       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19262     SDValue UNDEF = DAG.getUNDEF(VT);
19263     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19264                               N->getOperand(0), UNDEF);
19265     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19266                               N->getOperand(1), UNDEF);
19267     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19268     return;
19269   }
19270   case ISD::SIGN_EXTEND_INREG:
19271   case ISD::ADDC:
19272   case ISD::ADDE:
19273   case ISD::SUBC:
19274   case ISD::SUBE:
19275     // We don't want to expand or promote these.
19276     return;
19277   case ISD::SDIV:
19278   case ISD::UDIV:
19279   case ISD::SREM:
19280   case ISD::UREM:
19281   case ISD::SDIVREM:
19282   case ISD::UDIVREM: {
19283     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19284     Results.push_back(V);
19285     return;
19286   }
19287   case ISD::FP_TO_SINT:
19288   case ISD::FP_TO_UINT: {
19289     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19290
19291     std::pair<SDValue,SDValue> Vals =
19292         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19293     SDValue FIST = Vals.first, StackSlot = Vals.second;
19294     if (FIST.getNode()) {
19295       EVT VT = N->getValueType(0);
19296       // Return a load from the stack slot.
19297       if (StackSlot.getNode())
19298         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19299                                       MachinePointerInfo(),
19300                                       false, false, false, 0));
19301       else
19302         Results.push_back(FIST);
19303     }
19304     return;
19305   }
19306   case ISD::UINT_TO_FP: {
19307     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19308     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19309         N->getValueType(0) != MVT::v2f32)
19310       return;
19311     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19312                                  N->getOperand(0));
19313     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19314                                      MVT::f64);
19315     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19316     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19317                              DAG.getBitcast(MVT::v2i64, VBias));
19318     Or = DAG.getBitcast(MVT::v2f64, Or);
19319     // TODO: Are there any fast-math-flags to propagate here?
19320     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19321     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19322     return;
19323   }
19324   case ISD::FP_ROUND: {
19325     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19326         return;
19327     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19328     Results.push_back(V);
19329     return;
19330   }
19331   case ISD::FP_EXTEND: {
19332     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19333     // No other ValueType for FP_EXTEND should reach this point.
19334     assert(N->getValueType(0) == MVT::v2f32 &&
19335            "Do not know how to legalize this Node");
19336     return;
19337   }
19338   case ISD::INTRINSIC_W_CHAIN: {
19339     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19340     switch (IntNo) {
19341     default : llvm_unreachable("Do not know how to custom type "
19342                                "legalize this intrinsic operation!");
19343     case Intrinsic::x86_rdtsc:
19344       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19345                                      Results);
19346     case Intrinsic::x86_rdtscp:
19347       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19348                                      Results);
19349     case Intrinsic::x86_rdpmc:
19350       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19351     }
19352   }
19353   case ISD::READCYCLECOUNTER: {
19354     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19355                                    Results);
19356   }
19357   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19358     EVT T = N->getValueType(0);
19359     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19360     bool Regs64bit = T == MVT::i128;
19361     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19362     SDValue cpInL, cpInH;
19363     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19364                         DAG.getConstant(0, dl, HalfT));
19365     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19366                         DAG.getConstant(1, dl, HalfT));
19367     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19368                              Regs64bit ? X86::RAX : X86::EAX,
19369                              cpInL, SDValue());
19370     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19371                              Regs64bit ? X86::RDX : X86::EDX,
19372                              cpInH, cpInL.getValue(1));
19373     SDValue swapInL, swapInH;
19374     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19375                           DAG.getConstant(0, dl, HalfT));
19376     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19377                           DAG.getConstant(1, dl, HalfT));
19378     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19379                                Regs64bit ? X86::RBX : X86::EBX,
19380                                swapInL, cpInH.getValue(1));
19381     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19382                                Regs64bit ? X86::RCX : X86::ECX,
19383                                swapInH, swapInL.getValue(1));
19384     SDValue Ops[] = { swapInH.getValue(0),
19385                       N->getOperand(1),
19386                       swapInH.getValue(1) };
19387     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19388     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19389     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19390                                   X86ISD::LCMPXCHG8_DAG;
19391     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19392     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19393                                         Regs64bit ? X86::RAX : X86::EAX,
19394                                         HalfT, Result.getValue(1));
19395     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19396                                         Regs64bit ? X86::RDX : X86::EDX,
19397                                         HalfT, cpOutL.getValue(2));
19398     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19399
19400     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19401                                         MVT::i32, cpOutH.getValue(2));
19402     SDValue Success =
19403         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19404                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19405     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19406
19407     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19408     Results.push_back(Success);
19409     Results.push_back(EFLAGS.getValue(1));
19410     return;
19411   }
19412   case ISD::ATOMIC_SWAP:
19413   case ISD::ATOMIC_LOAD_ADD:
19414   case ISD::ATOMIC_LOAD_SUB:
19415   case ISD::ATOMIC_LOAD_AND:
19416   case ISD::ATOMIC_LOAD_OR:
19417   case ISD::ATOMIC_LOAD_XOR:
19418   case ISD::ATOMIC_LOAD_NAND:
19419   case ISD::ATOMIC_LOAD_MIN:
19420   case ISD::ATOMIC_LOAD_MAX:
19421   case ISD::ATOMIC_LOAD_UMIN:
19422   case ISD::ATOMIC_LOAD_UMAX:
19423   case ISD::ATOMIC_LOAD: {
19424     // Delegate to generic TypeLegalization. Situations we can really handle
19425     // should have already been dealt with by AtomicExpandPass.cpp.
19426     break;
19427   }
19428   case ISD::BITCAST: {
19429     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19430     EVT DstVT = N->getValueType(0);
19431     EVT SrcVT = N->getOperand(0)->getValueType(0);
19432
19433     if (SrcVT != MVT::f64 ||
19434         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19435       return;
19436
19437     unsigned NumElts = DstVT.getVectorNumElements();
19438     EVT SVT = DstVT.getVectorElementType();
19439     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19440     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19441                                    MVT::v2f64, N->getOperand(0));
19442     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19443
19444     if (ExperimentalVectorWideningLegalization) {
19445       // If we are legalizing vectors by widening, we already have the desired
19446       // legal vector type, just return it.
19447       Results.push_back(ToVecInt);
19448       return;
19449     }
19450
19451     SmallVector<SDValue, 8> Elts;
19452     for (unsigned i = 0, e = NumElts; i != e; ++i)
19453       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19454                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19455
19456     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19457   }
19458   }
19459 }
19460
19461 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19462   switch ((X86ISD::NodeType)Opcode) {
19463   case X86ISD::FIRST_NUMBER:       break;
19464   case X86ISD::BSF:                return "X86ISD::BSF";
19465   case X86ISD::BSR:                return "X86ISD::BSR";
19466   case X86ISD::SHLD:               return "X86ISD::SHLD";
19467   case X86ISD::SHRD:               return "X86ISD::SHRD";
19468   case X86ISD::FAND:               return "X86ISD::FAND";
19469   case X86ISD::FANDN:              return "X86ISD::FANDN";
19470   case X86ISD::FOR:                return "X86ISD::FOR";
19471   case X86ISD::FXOR:               return "X86ISD::FXOR";
19472   case X86ISD::FILD:               return "X86ISD::FILD";
19473   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19474   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19475   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19476   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19477   case X86ISD::FLD:                return "X86ISD::FLD";
19478   case X86ISD::FST:                return "X86ISD::FST";
19479   case X86ISD::CALL:               return "X86ISD::CALL";
19480   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19481   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19482   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19483   case X86ISD::BT:                 return "X86ISD::BT";
19484   case X86ISD::CMP:                return "X86ISD::CMP";
19485   case X86ISD::COMI:               return "X86ISD::COMI";
19486   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19487   case X86ISD::CMPM:               return "X86ISD::CMPM";
19488   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19489   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19490   case X86ISD::SETCC:              return "X86ISD::SETCC";
19491   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19492   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19493   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19494   case X86ISD::CMOV:               return "X86ISD::CMOV";
19495   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19496   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19497   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19498   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19499   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19500   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19501   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19502   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19503   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19504   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19505   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19506   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19507   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19508   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19509   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19510   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19511   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19512   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19513   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19514   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19515   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19516   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19517   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19518   case X86ISD::HADD:               return "X86ISD::HADD";
19519   case X86ISD::HSUB:               return "X86ISD::HSUB";
19520   case X86ISD::FHADD:              return "X86ISD::FHADD";
19521   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19522   case X86ISD::ABS:                return "X86ISD::ABS";
19523   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
19524   case X86ISD::FMAX:               return "X86ISD::FMAX";
19525   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19526   case X86ISD::FMIN:               return "X86ISD::FMIN";
19527   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19528   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19529   case X86ISD::FMINC:              return "X86ISD::FMINC";
19530   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19531   case X86ISD::FRCP:               return "X86ISD::FRCP";
19532   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19533   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19534   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19535   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19536   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19537   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19538   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19539   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19540   case X86ISD::CATCHRET:           return "X86ISD::CATCHRET";
19541   case X86ISD::CLEANUPRET:         return "X86ISD::CLEANUPRET";
19542   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19543   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19544   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19545   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19546   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19547   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19548   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19549   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19550   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19551   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19552   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19553   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19554   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19555   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19556   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19557   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19558   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19559   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19560   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19561   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19562   case X86ISD::VSHL:               return "X86ISD::VSHL";
19563   case X86ISD::VSRL:               return "X86ISD::VSRL";
19564   case X86ISD::VSRA:               return "X86ISD::VSRA";
19565   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19566   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19567   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19568   case X86ISD::CMPP:               return "X86ISD::CMPP";
19569   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19570   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19571   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19572   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19573   case X86ISD::ADD:                return "X86ISD::ADD";
19574   case X86ISD::SUB:                return "X86ISD::SUB";
19575   case X86ISD::ADC:                return "X86ISD::ADC";
19576   case X86ISD::SBB:                return "X86ISD::SBB";
19577   case X86ISD::SMUL:               return "X86ISD::SMUL";
19578   case X86ISD::UMUL:               return "X86ISD::UMUL";
19579   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19580   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19581   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19582   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19583   case X86ISD::INC:                return "X86ISD::INC";
19584   case X86ISD::DEC:                return "X86ISD::DEC";
19585   case X86ISD::OR:                 return "X86ISD::OR";
19586   case X86ISD::XOR:                return "X86ISD::XOR";
19587   case X86ISD::AND:                return "X86ISD::AND";
19588   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19589   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19590   case X86ISD::PTEST:              return "X86ISD::PTEST";
19591   case X86ISD::TESTP:              return "X86ISD::TESTP";
19592   case X86ISD::TESTM:              return "X86ISD::TESTM";
19593   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19594   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19595   case X86ISD::KTEST:              return "X86ISD::KTEST";
19596   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19597   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19598   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19599   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19600   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19601   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19602   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19603   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19604   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19605   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19606   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19607   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19608   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19609   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19610   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19611   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19612   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19613   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19614   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19615   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19616   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19617   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19618   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19619   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19620   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19621   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19622   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19623   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19624   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19625   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19626   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19627   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19628   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19629   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19630   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19631   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19632   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
19633   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19634   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19635   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19636   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19637   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19638   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19639   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19640   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19641   case X86ISD::SAHF:               return "X86ISD::SAHF";
19642   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19643   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19644   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19645   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19646   case X86ISD::FMADD:              return "X86ISD::FMADD";
19647   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19648   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19649   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19650   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19651   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19652   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19653   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19654   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19655   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19656   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19657   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19658   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19659   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19660   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
19661   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19662   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19663   case X86ISD::XTEST:              return "X86ISD::XTEST";
19664   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19665   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19666   case X86ISD::SELECT:             return "X86ISD::SELECT";
19667   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19668   case X86ISD::RCP28:              return "X86ISD::RCP28";
19669   case X86ISD::EXP2:               return "X86ISD::EXP2";
19670   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19671   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19672   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19673   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19674   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19675   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19676   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19677   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19678   case X86ISD::ADDS:               return "X86ISD::ADDS";
19679   case X86ISD::SUBS:               return "X86ISD::SUBS";
19680   case X86ISD::AVG:                return "X86ISD::AVG";
19681   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19682   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19683   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19684   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19685   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19686   }
19687   return nullptr;
19688 }
19689
19690 // isLegalAddressingMode - Return true if the addressing mode represented
19691 // by AM is legal for this target, for a load/store of the specified type.
19692 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19693                                               const AddrMode &AM, Type *Ty,
19694                                               unsigned AS) const {
19695   // X86 supports extremely general addressing modes.
19696   CodeModel::Model M = getTargetMachine().getCodeModel();
19697   Reloc::Model R = getTargetMachine().getRelocationModel();
19698
19699   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19700   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19701     return false;
19702
19703   if (AM.BaseGV) {
19704     unsigned GVFlags =
19705       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19706
19707     // If a reference to this global requires an extra load, we can't fold it.
19708     if (isGlobalStubReference(GVFlags))
19709       return false;
19710
19711     // If BaseGV requires a register for the PIC base, we cannot also have a
19712     // BaseReg specified.
19713     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19714       return false;
19715
19716     // If lower 4G is not available, then we must use rip-relative addressing.
19717     if ((M != CodeModel::Small || R != Reloc::Static) &&
19718         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19719       return false;
19720   }
19721
19722   switch (AM.Scale) {
19723   case 0:
19724   case 1:
19725   case 2:
19726   case 4:
19727   case 8:
19728     // These scales always work.
19729     break;
19730   case 3:
19731   case 5:
19732   case 9:
19733     // These scales are formed with basereg+scalereg.  Only accept if there is
19734     // no basereg yet.
19735     if (AM.HasBaseReg)
19736       return false;
19737     break;
19738   default:  // Other stuff never works.
19739     return false;
19740   }
19741
19742   return true;
19743 }
19744
19745 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19746   unsigned Bits = Ty->getScalarSizeInBits();
19747
19748   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19749   // particularly cheaper than those without.
19750   if (Bits == 8)
19751     return false;
19752
19753   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19754   // variable shifts just as cheap as scalar ones.
19755   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19756     return false;
19757
19758   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19759   // fully general vector.
19760   return true;
19761 }
19762
19763 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19764   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19765     return false;
19766   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19767   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19768   return NumBits1 > NumBits2;
19769 }
19770
19771 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19772   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19773     return false;
19774
19775   if (!isTypeLegal(EVT::getEVT(Ty1)))
19776     return false;
19777
19778   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19779
19780   // Assuming the caller doesn't have a zeroext or signext return parameter,
19781   // truncation all the way down to i1 is valid.
19782   return true;
19783 }
19784
19785 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19786   return isInt<32>(Imm);
19787 }
19788
19789 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19790   // Can also use sub to handle negated immediates.
19791   return isInt<32>(Imm);
19792 }
19793
19794 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19795   if (!VT1.isInteger() || !VT2.isInteger())
19796     return false;
19797   unsigned NumBits1 = VT1.getSizeInBits();
19798   unsigned NumBits2 = VT2.getSizeInBits();
19799   return NumBits1 > NumBits2;
19800 }
19801
19802 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19803   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19804   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19805 }
19806
19807 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19808   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19809   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19810 }
19811
19812 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19813   EVT VT1 = Val.getValueType();
19814   if (isZExtFree(VT1, VT2))
19815     return true;
19816
19817   if (Val.getOpcode() != ISD::LOAD)
19818     return false;
19819
19820   if (!VT1.isSimple() || !VT1.isInteger() ||
19821       !VT2.isSimple() || !VT2.isInteger())
19822     return false;
19823
19824   switch (VT1.getSimpleVT().SimpleTy) {
19825   default: break;
19826   case MVT::i8:
19827   case MVT::i16:
19828   case MVT::i32:
19829     // X86 has 8, 16, and 32-bit zero-extending loads.
19830     return true;
19831   }
19832
19833   return false;
19834 }
19835
19836 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19837
19838 bool
19839 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19840   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19841     return false;
19842
19843   VT = VT.getScalarType();
19844
19845   if (!VT.isSimple())
19846     return false;
19847
19848   switch (VT.getSimpleVT().SimpleTy) {
19849   case MVT::f32:
19850   case MVT::f64:
19851     return true;
19852   default:
19853     break;
19854   }
19855
19856   return false;
19857 }
19858
19859 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19860   // i16 instructions are longer (0x66 prefix) and potentially slower.
19861   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19862 }
19863
19864 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19865 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19866 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19867 /// are assumed to be legal.
19868 bool
19869 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19870                                       EVT VT) const {
19871   if (!VT.isSimple())
19872     return false;
19873
19874   // Not for i1 vectors
19875   if (VT.getScalarType() == MVT::i1)
19876     return false;
19877
19878   // Very little shuffling can be done for 64-bit vectors right now.
19879   if (VT.getSizeInBits() == 64)
19880     return false;
19881
19882   // We only care that the types being shuffled are legal. The lowering can
19883   // handle any possible shuffle mask that results.
19884   return isTypeLegal(VT.getSimpleVT());
19885 }
19886
19887 bool
19888 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19889                                           EVT VT) const {
19890   // Just delegate to the generic legality, clear masks aren't special.
19891   return isShuffleMaskLegal(Mask, VT);
19892 }
19893
19894 //===----------------------------------------------------------------------===//
19895 //                           X86 Scheduler Hooks
19896 //===----------------------------------------------------------------------===//
19897
19898 /// Utility function to emit xbegin specifying the start of an RTM region.
19899 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19900                                      const TargetInstrInfo *TII) {
19901   DebugLoc DL = MI->getDebugLoc();
19902
19903   const BasicBlock *BB = MBB->getBasicBlock();
19904   MachineFunction::iterator I = MBB;
19905   ++I;
19906
19907   // For the v = xbegin(), we generate
19908   //
19909   // thisMBB:
19910   //  xbegin sinkMBB
19911   //
19912   // mainMBB:
19913   //  eax = -1
19914   //
19915   // sinkMBB:
19916   //  v = eax
19917
19918   MachineBasicBlock *thisMBB = MBB;
19919   MachineFunction *MF = MBB->getParent();
19920   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19921   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19922   MF->insert(I, mainMBB);
19923   MF->insert(I, sinkMBB);
19924
19925   // Transfer the remainder of BB and its successor edges to sinkMBB.
19926   sinkMBB->splice(sinkMBB->begin(), MBB,
19927                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19928   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19929
19930   // thisMBB:
19931   //  xbegin sinkMBB
19932   //  # fallthrough to mainMBB
19933   //  # abortion to sinkMBB
19934   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19935   thisMBB->addSuccessor(mainMBB);
19936   thisMBB->addSuccessor(sinkMBB);
19937
19938   // mainMBB:
19939   //  EAX = -1
19940   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19941   mainMBB->addSuccessor(sinkMBB);
19942
19943   // sinkMBB:
19944   // EAX is live into the sinkMBB
19945   sinkMBB->addLiveIn(X86::EAX);
19946   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19947           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19948     .addReg(X86::EAX);
19949
19950   MI->eraseFromParent();
19951   return sinkMBB;
19952 }
19953
19954 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19955 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19956 // in the .td file.
19957 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19958                                        const TargetInstrInfo *TII) {
19959   unsigned Opc;
19960   switch (MI->getOpcode()) {
19961   default: llvm_unreachable("illegal opcode!");
19962   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19963   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19964   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19965   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19966   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19967   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19968   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19969   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19970   }
19971
19972   DebugLoc dl = MI->getDebugLoc();
19973   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19974
19975   unsigned NumArgs = MI->getNumOperands();
19976   for (unsigned i = 1; i < NumArgs; ++i) {
19977     MachineOperand &Op = MI->getOperand(i);
19978     if (!(Op.isReg() && Op.isImplicit()))
19979       MIB.addOperand(Op);
19980   }
19981   if (MI->hasOneMemOperand())
19982     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19983
19984   BuildMI(*BB, MI, dl,
19985     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19986     .addReg(X86::XMM0);
19987
19988   MI->eraseFromParent();
19989   return BB;
19990 }
19991
19992 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19993 // defs in an instruction pattern
19994 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19995                                        const TargetInstrInfo *TII) {
19996   unsigned Opc;
19997   switch (MI->getOpcode()) {
19998   default: llvm_unreachable("illegal opcode!");
19999   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20000   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20001   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20002   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20003   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20004   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20005   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20006   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20007   }
20008
20009   DebugLoc dl = MI->getDebugLoc();
20010   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20011
20012   unsigned NumArgs = MI->getNumOperands(); // remove the results
20013   for (unsigned i = 1; i < NumArgs; ++i) {
20014     MachineOperand &Op = MI->getOperand(i);
20015     if (!(Op.isReg() && Op.isImplicit()))
20016       MIB.addOperand(Op);
20017   }
20018   if (MI->hasOneMemOperand())
20019     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20020
20021   BuildMI(*BB, MI, dl,
20022     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20023     .addReg(X86::ECX);
20024
20025   MI->eraseFromParent();
20026   return BB;
20027 }
20028
20029 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20030                                       const X86Subtarget *Subtarget) {
20031   DebugLoc dl = MI->getDebugLoc();
20032   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20033   // Address into RAX/EAX, other two args into ECX, EDX.
20034   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20035   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20036   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20037   for (int i = 0; i < X86::AddrNumOperands; ++i)
20038     MIB.addOperand(MI->getOperand(i));
20039
20040   unsigned ValOps = X86::AddrNumOperands;
20041   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20042     .addReg(MI->getOperand(ValOps).getReg());
20043   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20044     .addReg(MI->getOperand(ValOps+1).getReg());
20045
20046   // The instruction doesn't actually take any operands though.
20047   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20048
20049   MI->eraseFromParent(); // The pseudo is gone now.
20050   return BB;
20051 }
20052
20053 MachineBasicBlock *
20054 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20055                                                  MachineBasicBlock *MBB) const {
20056   // Emit va_arg instruction on X86-64.
20057
20058   // Operands to this pseudo-instruction:
20059   // 0  ) Output        : destination address (reg)
20060   // 1-5) Input         : va_list address (addr, i64mem)
20061   // 6  ) ArgSize       : Size (in bytes) of vararg type
20062   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20063   // 8  ) Align         : Alignment of type
20064   // 9  ) EFLAGS (implicit-def)
20065
20066   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20067   static_assert(X86::AddrNumOperands == 5,
20068                 "VAARG_64 assumes 5 address operands");
20069
20070   unsigned DestReg = MI->getOperand(0).getReg();
20071   MachineOperand &Base = MI->getOperand(1);
20072   MachineOperand &Scale = MI->getOperand(2);
20073   MachineOperand &Index = MI->getOperand(3);
20074   MachineOperand &Disp = MI->getOperand(4);
20075   MachineOperand &Segment = MI->getOperand(5);
20076   unsigned ArgSize = MI->getOperand(6).getImm();
20077   unsigned ArgMode = MI->getOperand(7).getImm();
20078   unsigned Align = MI->getOperand(8).getImm();
20079
20080   // Memory Reference
20081   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20082   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20083   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20084
20085   // Machine Information
20086   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20087   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20088   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20089   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20090   DebugLoc DL = MI->getDebugLoc();
20091
20092   // struct va_list {
20093   //   i32   gp_offset
20094   //   i32   fp_offset
20095   //   i64   overflow_area (address)
20096   //   i64   reg_save_area (address)
20097   // }
20098   // sizeof(va_list) = 24
20099   // alignment(va_list) = 8
20100
20101   unsigned TotalNumIntRegs = 6;
20102   unsigned TotalNumXMMRegs = 8;
20103   bool UseGPOffset = (ArgMode == 1);
20104   bool UseFPOffset = (ArgMode == 2);
20105   unsigned MaxOffset = TotalNumIntRegs * 8 +
20106                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20107
20108   /* Align ArgSize to a multiple of 8 */
20109   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20110   bool NeedsAlign = (Align > 8);
20111
20112   MachineBasicBlock *thisMBB = MBB;
20113   MachineBasicBlock *overflowMBB;
20114   MachineBasicBlock *offsetMBB;
20115   MachineBasicBlock *endMBB;
20116
20117   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20118   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20119   unsigned OffsetReg = 0;
20120
20121   if (!UseGPOffset && !UseFPOffset) {
20122     // If we only pull from the overflow region, we don't create a branch.
20123     // We don't need to alter control flow.
20124     OffsetDestReg = 0; // unused
20125     OverflowDestReg = DestReg;
20126
20127     offsetMBB = nullptr;
20128     overflowMBB = thisMBB;
20129     endMBB = thisMBB;
20130   } else {
20131     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20132     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20133     // If not, pull from overflow_area. (branch to overflowMBB)
20134     //
20135     //       thisMBB
20136     //         |     .
20137     //         |        .
20138     //     offsetMBB   overflowMBB
20139     //         |        .
20140     //         |     .
20141     //        endMBB
20142
20143     // Registers for the PHI in endMBB
20144     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20145     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20146
20147     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20148     MachineFunction *MF = MBB->getParent();
20149     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20150     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20151     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20152
20153     MachineFunction::iterator MBBIter = MBB;
20154     ++MBBIter;
20155
20156     // Insert the new basic blocks
20157     MF->insert(MBBIter, offsetMBB);
20158     MF->insert(MBBIter, overflowMBB);
20159     MF->insert(MBBIter, endMBB);
20160
20161     // Transfer the remainder of MBB and its successor edges to endMBB.
20162     endMBB->splice(endMBB->begin(), thisMBB,
20163                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20164     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20165
20166     // Make offsetMBB and overflowMBB successors of thisMBB
20167     thisMBB->addSuccessor(offsetMBB);
20168     thisMBB->addSuccessor(overflowMBB);
20169
20170     // endMBB is a successor of both offsetMBB and overflowMBB
20171     offsetMBB->addSuccessor(endMBB);
20172     overflowMBB->addSuccessor(endMBB);
20173
20174     // Load the offset value into a register
20175     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20176     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20177       .addOperand(Base)
20178       .addOperand(Scale)
20179       .addOperand(Index)
20180       .addDisp(Disp, UseFPOffset ? 4 : 0)
20181       .addOperand(Segment)
20182       .setMemRefs(MMOBegin, MMOEnd);
20183
20184     // Check if there is enough room left to pull this argument.
20185     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20186       .addReg(OffsetReg)
20187       .addImm(MaxOffset + 8 - ArgSizeA8);
20188
20189     // Branch to "overflowMBB" if offset >= max
20190     // Fall through to "offsetMBB" otherwise
20191     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20192       .addMBB(overflowMBB);
20193   }
20194
20195   // In offsetMBB, emit code to use the reg_save_area.
20196   if (offsetMBB) {
20197     assert(OffsetReg != 0);
20198
20199     // Read the reg_save_area address.
20200     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20201     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20202       .addOperand(Base)
20203       .addOperand(Scale)
20204       .addOperand(Index)
20205       .addDisp(Disp, 16)
20206       .addOperand(Segment)
20207       .setMemRefs(MMOBegin, MMOEnd);
20208
20209     // Zero-extend the offset
20210     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20211       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20212         .addImm(0)
20213         .addReg(OffsetReg)
20214         .addImm(X86::sub_32bit);
20215
20216     // Add the offset to the reg_save_area to get the final address.
20217     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20218       .addReg(OffsetReg64)
20219       .addReg(RegSaveReg);
20220
20221     // Compute the offset for the next argument
20222     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20223     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20224       .addReg(OffsetReg)
20225       .addImm(UseFPOffset ? 16 : 8);
20226
20227     // Store it back into the va_list.
20228     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20229       .addOperand(Base)
20230       .addOperand(Scale)
20231       .addOperand(Index)
20232       .addDisp(Disp, UseFPOffset ? 4 : 0)
20233       .addOperand(Segment)
20234       .addReg(NextOffsetReg)
20235       .setMemRefs(MMOBegin, MMOEnd);
20236
20237     // Jump to endMBB
20238     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20239       .addMBB(endMBB);
20240   }
20241
20242   //
20243   // Emit code to use overflow area
20244   //
20245
20246   // Load the overflow_area address into a register.
20247   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20248   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20249     .addOperand(Base)
20250     .addOperand(Scale)
20251     .addOperand(Index)
20252     .addDisp(Disp, 8)
20253     .addOperand(Segment)
20254     .setMemRefs(MMOBegin, MMOEnd);
20255
20256   // If we need to align it, do so. Otherwise, just copy the address
20257   // to OverflowDestReg.
20258   if (NeedsAlign) {
20259     // Align the overflow address
20260     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20261     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20262
20263     // aligned_addr = (addr + (align-1)) & ~(align-1)
20264     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20265       .addReg(OverflowAddrReg)
20266       .addImm(Align-1);
20267
20268     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20269       .addReg(TmpReg)
20270       .addImm(~(uint64_t)(Align-1));
20271   } else {
20272     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20273       .addReg(OverflowAddrReg);
20274   }
20275
20276   // Compute the next overflow address after this argument.
20277   // (the overflow address should be kept 8-byte aligned)
20278   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20279   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20280     .addReg(OverflowDestReg)
20281     .addImm(ArgSizeA8);
20282
20283   // Store the new overflow address.
20284   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20285     .addOperand(Base)
20286     .addOperand(Scale)
20287     .addOperand(Index)
20288     .addDisp(Disp, 8)
20289     .addOperand(Segment)
20290     .addReg(NextAddrReg)
20291     .setMemRefs(MMOBegin, MMOEnd);
20292
20293   // If we branched, emit the PHI to the front of endMBB.
20294   if (offsetMBB) {
20295     BuildMI(*endMBB, endMBB->begin(), DL,
20296             TII->get(X86::PHI), DestReg)
20297       .addReg(OffsetDestReg).addMBB(offsetMBB)
20298       .addReg(OverflowDestReg).addMBB(overflowMBB);
20299   }
20300
20301   // Erase the pseudo instruction
20302   MI->eraseFromParent();
20303
20304   return endMBB;
20305 }
20306
20307 MachineBasicBlock *
20308 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20309                                                  MachineInstr *MI,
20310                                                  MachineBasicBlock *MBB) const {
20311   // Emit code to save XMM registers to the stack. The ABI says that the
20312   // number of registers to save is given in %al, so it's theoretically
20313   // possible to do an indirect jump trick to avoid saving all of them,
20314   // however this code takes a simpler approach and just executes all
20315   // of the stores if %al is non-zero. It's less code, and it's probably
20316   // easier on the hardware branch predictor, and stores aren't all that
20317   // expensive anyway.
20318
20319   // Create the new basic blocks. One block contains all the XMM stores,
20320   // and one block is the final destination regardless of whether any
20321   // stores were performed.
20322   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20323   MachineFunction *F = MBB->getParent();
20324   MachineFunction::iterator MBBIter = MBB;
20325   ++MBBIter;
20326   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20327   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20328   F->insert(MBBIter, XMMSaveMBB);
20329   F->insert(MBBIter, EndMBB);
20330
20331   // Transfer the remainder of MBB and its successor edges to EndMBB.
20332   EndMBB->splice(EndMBB->begin(), MBB,
20333                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20334   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20335
20336   // The original block will now fall through to the XMM save block.
20337   MBB->addSuccessor(XMMSaveMBB);
20338   // The XMMSaveMBB will fall through to the end block.
20339   XMMSaveMBB->addSuccessor(EndMBB);
20340
20341   // Now add the instructions.
20342   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20343   DebugLoc DL = MI->getDebugLoc();
20344
20345   unsigned CountReg = MI->getOperand(0).getReg();
20346   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20347   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20348
20349   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20350     // If %al is 0, branch around the XMM save block.
20351     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20352     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20353     MBB->addSuccessor(EndMBB);
20354   }
20355
20356   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20357   // that was just emitted, but clearly shouldn't be "saved".
20358   assert((MI->getNumOperands() <= 3 ||
20359           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20360           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20361          && "Expected last argument to be EFLAGS");
20362   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20363   // In the XMM save block, save all the XMM argument registers.
20364   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20365     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20366     MachineMemOperand *MMO = F->getMachineMemOperand(
20367         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20368         MachineMemOperand::MOStore,
20369         /*Size=*/16, /*Align=*/16);
20370     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20371       .addFrameIndex(RegSaveFrameIndex)
20372       .addImm(/*Scale=*/1)
20373       .addReg(/*IndexReg=*/0)
20374       .addImm(/*Disp=*/Offset)
20375       .addReg(/*Segment=*/0)
20376       .addReg(MI->getOperand(i).getReg())
20377       .addMemOperand(MMO);
20378   }
20379
20380   MI->eraseFromParent();   // The pseudo instruction is gone now.
20381
20382   return EndMBB;
20383 }
20384
20385 // The EFLAGS operand of SelectItr might be missing a kill marker
20386 // because there were multiple uses of EFLAGS, and ISel didn't know
20387 // which to mark. Figure out whether SelectItr should have had a
20388 // kill marker, and set it if it should. Returns the correct kill
20389 // marker value.
20390 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20391                                      MachineBasicBlock* BB,
20392                                      const TargetRegisterInfo* TRI) {
20393   // Scan forward through BB for a use/def of EFLAGS.
20394   MachineBasicBlock::iterator miI(std::next(SelectItr));
20395   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20396     const MachineInstr& mi = *miI;
20397     if (mi.readsRegister(X86::EFLAGS))
20398       return false;
20399     if (mi.definesRegister(X86::EFLAGS))
20400       break; // Should have kill-flag - update below.
20401   }
20402
20403   // If we hit the end of the block, check whether EFLAGS is live into a
20404   // successor.
20405   if (miI == BB->end()) {
20406     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20407                                           sEnd = BB->succ_end();
20408          sItr != sEnd; ++sItr) {
20409       MachineBasicBlock* succ = *sItr;
20410       if (succ->isLiveIn(X86::EFLAGS))
20411         return false;
20412     }
20413   }
20414
20415   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20416   // out. SelectMI should have a kill flag on EFLAGS.
20417   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20418   return true;
20419 }
20420
20421 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20422 // together with other CMOV pseudo-opcodes into a single basic-block with
20423 // conditional jump around it.
20424 static bool isCMOVPseudo(MachineInstr *MI) {
20425   switch (MI->getOpcode()) {
20426   case X86::CMOV_FR32:
20427   case X86::CMOV_FR64:
20428   case X86::CMOV_GR8:
20429   case X86::CMOV_GR16:
20430   case X86::CMOV_GR32:
20431   case X86::CMOV_RFP32:
20432   case X86::CMOV_RFP64:
20433   case X86::CMOV_RFP80:
20434   case X86::CMOV_V2F64:
20435   case X86::CMOV_V2I64:
20436   case X86::CMOV_V4F32:
20437   case X86::CMOV_V4F64:
20438   case X86::CMOV_V4I64:
20439   case X86::CMOV_V16F32:
20440   case X86::CMOV_V8F32:
20441   case X86::CMOV_V8F64:
20442   case X86::CMOV_V8I64:
20443   case X86::CMOV_V8I1:
20444   case X86::CMOV_V16I1:
20445   case X86::CMOV_V32I1:
20446   case X86::CMOV_V64I1:
20447     return true;
20448
20449   default:
20450     return false;
20451   }
20452 }
20453
20454 MachineBasicBlock *
20455 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20456                                      MachineBasicBlock *BB) const {
20457   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20458   DebugLoc DL = MI->getDebugLoc();
20459
20460   // To "insert" a SELECT_CC instruction, we actually have to insert the
20461   // diamond control-flow pattern.  The incoming instruction knows the
20462   // destination vreg to set, the condition code register to branch on, the
20463   // true/false values to select between, and a branch opcode to use.
20464   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20465   MachineFunction::iterator It = BB;
20466   ++It;
20467
20468   //  thisMBB:
20469   //  ...
20470   //   TrueVal = ...
20471   //   cmpTY ccX, r1, r2
20472   //   bCC copy1MBB
20473   //   fallthrough --> copy0MBB
20474   MachineBasicBlock *thisMBB = BB;
20475   MachineFunction *F = BB->getParent();
20476
20477   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20478   // as described above, by inserting a BB, and then making a PHI at the join
20479   // point to select the true and false operands of the CMOV in the PHI.
20480   //
20481   // The code also handles two different cases of multiple CMOV opcodes
20482   // in a row.
20483   //
20484   // Case 1:
20485   // In this case, there are multiple CMOVs in a row, all which are based on
20486   // the same condition setting (or the exact opposite condition setting).
20487   // In this case we can lower all the CMOVs using a single inserted BB, and
20488   // then make a number of PHIs at the join point to model the CMOVs. The only
20489   // trickiness here, is that in a case like:
20490   //
20491   // t2 = CMOV cond1 t1, f1
20492   // t3 = CMOV cond1 t2, f2
20493   //
20494   // when rewriting this into PHIs, we have to perform some renaming on the
20495   // temps since you cannot have a PHI operand refer to a PHI result earlier
20496   // in the same block.  The "simple" but wrong lowering would be:
20497   //
20498   // t2 = PHI t1(BB1), f1(BB2)
20499   // t3 = PHI t2(BB1), f2(BB2)
20500   //
20501   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20502   // renaming is to note that on the path through BB1, t2 is really just a
20503   // copy of t1, and do that renaming, properly generating:
20504   //
20505   // t2 = PHI t1(BB1), f1(BB2)
20506   // t3 = PHI t1(BB1), f2(BB2)
20507   //
20508   // Case 2, we lower cascaded CMOVs such as
20509   //
20510   //   (CMOV (CMOV F, T, cc1), T, cc2)
20511   //
20512   // to two successives branches.  For that, we look for another CMOV as the
20513   // following instruction.
20514   //
20515   // Without this, we would add a PHI between the two jumps, which ends up
20516   // creating a few copies all around. For instance, for
20517   //
20518   //    (sitofp (zext (fcmp une)))
20519   //
20520   // we would generate:
20521   //
20522   //         ucomiss %xmm1, %xmm0
20523   //         movss  <1.0f>, %xmm0
20524   //         movaps  %xmm0, %xmm1
20525   //         jne     .LBB5_2
20526   //         xorps   %xmm1, %xmm1
20527   // .LBB5_2:
20528   //         jp      .LBB5_4
20529   //         movaps  %xmm1, %xmm0
20530   // .LBB5_4:
20531   //         retq
20532   //
20533   // because this custom-inserter would have generated:
20534   //
20535   //   A
20536   //   | \
20537   //   |  B
20538   //   | /
20539   //   C
20540   //   | \
20541   //   |  D
20542   //   | /
20543   //   E
20544   //
20545   // A: X = ...; Y = ...
20546   // B: empty
20547   // C: Z = PHI [X, A], [Y, B]
20548   // D: empty
20549   // E: PHI [X, C], [Z, D]
20550   //
20551   // If we lower both CMOVs in a single step, we can instead generate:
20552   //
20553   //   A
20554   //   | \
20555   //   |  C
20556   //   | /|
20557   //   |/ |
20558   //   |  |
20559   //   |  D
20560   //   | /
20561   //   E
20562   //
20563   // A: X = ...; Y = ...
20564   // D: empty
20565   // E: PHI [X, A], [X, C], [Y, D]
20566   //
20567   // Which, in our sitofp/fcmp example, gives us something like:
20568   //
20569   //         ucomiss %xmm1, %xmm0
20570   //         movss  <1.0f>, %xmm0
20571   //         jne     .LBB5_4
20572   //         jp      .LBB5_4
20573   //         xorps   %xmm0, %xmm0
20574   // .LBB5_4:
20575   //         retq
20576   //
20577   MachineInstr *CascadedCMOV = nullptr;
20578   MachineInstr *LastCMOV = MI;
20579   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20580   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20581   MachineBasicBlock::iterator NextMIIt =
20582       std::next(MachineBasicBlock::iterator(MI));
20583
20584   // Check for case 1, where there are multiple CMOVs with the same condition
20585   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
20586   // number of jumps the most.
20587
20588   if (isCMOVPseudo(MI)) {
20589     // See if we have a string of CMOVS with the same condition.
20590     while (NextMIIt != BB->end() &&
20591            isCMOVPseudo(NextMIIt) &&
20592            (NextMIIt->getOperand(3).getImm() == CC ||
20593             NextMIIt->getOperand(3).getImm() == OppCC)) {
20594       LastCMOV = &*NextMIIt;
20595       ++NextMIIt;
20596     }
20597   }
20598
20599   // This checks for case 2, but only do this if we didn't already find
20600   // case 1, as indicated by LastCMOV == MI.
20601   if (LastCMOV == MI &&
20602       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20603       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20604       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20605     CascadedCMOV = &*NextMIIt;
20606   }
20607
20608   MachineBasicBlock *jcc1MBB = nullptr;
20609
20610   // If we have a cascaded CMOV, we lower it to two successive branches to
20611   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20612   if (CascadedCMOV) {
20613     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20614     F->insert(It, jcc1MBB);
20615     jcc1MBB->addLiveIn(X86::EFLAGS);
20616   }
20617
20618   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20619   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20620   F->insert(It, copy0MBB);
20621   F->insert(It, sinkMBB);
20622
20623   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20624   // live into the sink and copy blocks.
20625   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20626
20627   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20628   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20629       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20630     copy0MBB->addLiveIn(X86::EFLAGS);
20631     sinkMBB->addLiveIn(X86::EFLAGS);
20632   }
20633
20634   // Transfer the remainder of BB and its successor edges to sinkMBB.
20635   sinkMBB->splice(sinkMBB->begin(), BB,
20636                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20637   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20638
20639   // Add the true and fallthrough blocks as its successors.
20640   if (CascadedCMOV) {
20641     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20642     BB->addSuccessor(jcc1MBB);
20643
20644     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20645     // jump to the sinkMBB.
20646     jcc1MBB->addSuccessor(copy0MBB);
20647     jcc1MBB->addSuccessor(sinkMBB);
20648   } else {
20649     BB->addSuccessor(copy0MBB);
20650   }
20651
20652   // The true block target of the first (or only) branch is always sinkMBB.
20653   BB->addSuccessor(sinkMBB);
20654
20655   // Create the conditional branch instruction.
20656   unsigned Opc = X86::GetCondBranchFromCond(CC);
20657   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20658
20659   if (CascadedCMOV) {
20660     unsigned Opc2 = X86::GetCondBranchFromCond(
20661         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20662     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20663   }
20664
20665   //  copy0MBB:
20666   //   %FalseValue = ...
20667   //   # fallthrough to sinkMBB
20668   copy0MBB->addSuccessor(sinkMBB);
20669
20670   //  sinkMBB:
20671   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20672   //  ...
20673   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20674   MachineBasicBlock::iterator MIItEnd =
20675     std::next(MachineBasicBlock::iterator(LastCMOV));
20676   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20677   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20678   MachineInstrBuilder MIB;
20679
20680   // As we are creating the PHIs, we have to be careful if there is more than
20681   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
20682   // PHIs have to reference the individual true/false inputs from earlier PHIs.
20683   // That also means that PHI construction must work forward from earlier to
20684   // later, and that the code must maintain a mapping from earlier PHI's
20685   // destination registers, and the registers that went into the PHI.
20686
20687   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20688     unsigned DestReg = MIIt->getOperand(0).getReg();
20689     unsigned Op1Reg = MIIt->getOperand(1).getReg();
20690     unsigned Op2Reg = MIIt->getOperand(2).getReg();
20691
20692     // If this CMOV we are generating is the opposite condition from
20693     // the jump we generated, then we have to swap the operands for the
20694     // PHI that is going to be generated.
20695     if (MIIt->getOperand(3).getImm() == OppCC)
20696         std::swap(Op1Reg, Op2Reg);
20697
20698     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20699       Op1Reg = RegRewriteTable[Op1Reg].first;
20700
20701     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20702       Op2Reg = RegRewriteTable[Op2Reg].second;
20703
20704     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20705                   TII->get(X86::PHI), DestReg)
20706           .addReg(Op1Reg).addMBB(copy0MBB)
20707           .addReg(Op2Reg).addMBB(thisMBB);
20708
20709     // Add this PHI to the rewrite table.
20710     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20711   }
20712
20713   // If we have a cascaded CMOV, the second Jcc provides the same incoming
20714   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20715   if (CascadedCMOV) {
20716     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20717     // Copy the PHI result to the register defined by the second CMOV.
20718     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20719             DL, TII->get(TargetOpcode::COPY),
20720             CascadedCMOV->getOperand(0).getReg())
20721         .addReg(MI->getOperand(0).getReg());
20722     CascadedCMOV->eraseFromParent();
20723   }
20724
20725   // Now remove the CMOV(s).
20726   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20727     (MIIt++)->eraseFromParent();
20728
20729   return sinkMBB;
20730 }
20731
20732 MachineBasicBlock *
20733 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20734                                        MachineBasicBlock *BB) const {
20735   // Combine the following atomic floating-point modification pattern:
20736   //   a.store(reg OP a.load(acquire), release)
20737   // Transform them into:
20738   //   OPss (%gpr), %xmm
20739   //   movss %xmm, (%gpr)
20740   // Or sd equivalent for 64-bit operations.
20741   unsigned MOp, FOp;
20742   switch (MI->getOpcode()) {
20743   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20744   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20745   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20746   }
20747   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20748   DebugLoc DL = MI->getDebugLoc();
20749   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20750   unsigned MSrc = MI->getOperand(0).getReg();
20751   unsigned VSrc = MI->getOperand(5).getReg();
20752   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20753                                 .addReg(/*Base=*/MSrc)
20754                                 .addImm(/*Scale=*/1)
20755                                 .addReg(/*Index=*/0)
20756                                 .addImm(0)
20757                                 .addReg(0);
20758   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20759                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20760                           .addReg(VSrc)
20761                           .addReg(/*Base=*/MSrc)
20762                           .addImm(/*Scale=*/1)
20763                           .addReg(/*Index=*/0)
20764                           .addImm(/*Disp=*/0)
20765                           .addReg(/*Segment=*/0);
20766   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20767   MI->eraseFromParent(); // The pseudo instruction is gone now.
20768   return BB;
20769 }
20770
20771 MachineBasicBlock *
20772 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20773                                         MachineBasicBlock *BB) const {
20774   MachineFunction *MF = BB->getParent();
20775   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20776   DebugLoc DL = MI->getDebugLoc();
20777   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20778
20779   assert(MF->shouldSplitStack());
20780
20781   const bool Is64Bit = Subtarget->is64Bit();
20782   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20783
20784   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20785   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20786
20787   // BB:
20788   //  ... [Till the alloca]
20789   // If stacklet is not large enough, jump to mallocMBB
20790   //
20791   // bumpMBB:
20792   //  Allocate by subtracting from RSP
20793   //  Jump to continueMBB
20794   //
20795   // mallocMBB:
20796   //  Allocate by call to runtime
20797   //
20798   // continueMBB:
20799   //  ...
20800   //  [rest of original BB]
20801   //
20802
20803   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20804   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20805   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20806
20807   MachineRegisterInfo &MRI = MF->getRegInfo();
20808   const TargetRegisterClass *AddrRegClass =
20809       getRegClassFor(getPointerTy(MF->getDataLayout()));
20810
20811   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20812     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20813     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20814     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20815     sizeVReg = MI->getOperand(1).getReg(),
20816     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20817
20818   MachineFunction::iterator MBBIter = BB;
20819   ++MBBIter;
20820
20821   MF->insert(MBBIter, bumpMBB);
20822   MF->insert(MBBIter, mallocMBB);
20823   MF->insert(MBBIter, continueMBB);
20824
20825   continueMBB->splice(continueMBB->begin(), BB,
20826                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20827   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20828
20829   // Add code to the main basic block to check if the stack limit has been hit,
20830   // and if so, jump to mallocMBB otherwise to bumpMBB.
20831   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20832   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20833     .addReg(tmpSPVReg).addReg(sizeVReg);
20834   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20835     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20836     .addReg(SPLimitVReg);
20837   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20838
20839   // bumpMBB simply decreases the stack pointer, since we know the current
20840   // stacklet has enough space.
20841   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20842     .addReg(SPLimitVReg);
20843   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20844     .addReg(SPLimitVReg);
20845   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20846
20847   // Calls into a routine in libgcc to allocate more space from the heap.
20848   const uint32_t *RegMask =
20849       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20850   if (IsLP64) {
20851     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20852       .addReg(sizeVReg);
20853     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20854       .addExternalSymbol("__morestack_allocate_stack_space")
20855       .addRegMask(RegMask)
20856       .addReg(X86::RDI, RegState::Implicit)
20857       .addReg(X86::RAX, RegState::ImplicitDefine);
20858   } else if (Is64Bit) {
20859     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20860       .addReg(sizeVReg);
20861     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20862       .addExternalSymbol("__morestack_allocate_stack_space")
20863       .addRegMask(RegMask)
20864       .addReg(X86::EDI, RegState::Implicit)
20865       .addReg(X86::EAX, RegState::ImplicitDefine);
20866   } else {
20867     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20868       .addImm(12);
20869     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20870     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20871       .addExternalSymbol("__morestack_allocate_stack_space")
20872       .addRegMask(RegMask)
20873       .addReg(X86::EAX, RegState::ImplicitDefine);
20874   }
20875
20876   if (!Is64Bit)
20877     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20878       .addImm(16);
20879
20880   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20881     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20882   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20883
20884   // Set up the CFG correctly.
20885   BB->addSuccessor(bumpMBB);
20886   BB->addSuccessor(mallocMBB);
20887   mallocMBB->addSuccessor(continueMBB);
20888   bumpMBB->addSuccessor(continueMBB);
20889
20890   // Take care of the PHI nodes.
20891   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20892           MI->getOperand(0).getReg())
20893     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20894     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20895
20896   // Delete the original pseudo instruction.
20897   MI->eraseFromParent();
20898
20899   // And we're done.
20900   return continueMBB;
20901 }
20902
20903 MachineBasicBlock *
20904 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20905                                         MachineBasicBlock *BB) const {
20906   DebugLoc DL = MI->getDebugLoc();
20907
20908   assert(!Subtarget->isTargetMachO());
20909
20910   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20911                                                     DL);
20912
20913   MI->eraseFromParent();   // The pseudo instruction is gone now.
20914   return BB;
20915 }
20916
20917 MachineBasicBlock *
20918 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20919                                       MachineBasicBlock *BB) const {
20920   // This is pretty easy.  We're taking the value that we received from
20921   // our load from the relocation, sticking it in either RDI (x86-64)
20922   // or EAX and doing an indirect call.  The return value will then
20923   // be in the normal return register.
20924   MachineFunction *F = BB->getParent();
20925   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20926   DebugLoc DL = MI->getDebugLoc();
20927
20928   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20929   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20930
20931   // Get a register mask for the lowered call.
20932   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20933   // proper register mask.
20934   const uint32_t *RegMask =
20935       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20936   if (Subtarget->is64Bit()) {
20937     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20938                                       TII->get(X86::MOV64rm), X86::RDI)
20939     .addReg(X86::RIP)
20940     .addImm(0).addReg(0)
20941     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20942                       MI->getOperand(3).getTargetFlags())
20943     .addReg(0);
20944     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20945     addDirectMem(MIB, X86::RDI);
20946     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20947   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20948     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20949                                       TII->get(X86::MOV32rm), X86::EAX)
20950     .addReg(0)
20951     .addImm(0).addReg(0)
20952     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20953                       MI->getOperand(3).getTargetFlags())
20954     .addReg(0);
20955     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20956     addDirectMem(MIB, X86::EAX);
20957     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20958   } else {
20959     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20960                                       TII->get(X86::MOV32rm), X86::EAX)
20961     .addReg(TII->getGlobalBaseReg(F))
20962     .addImm(0).addReg(0)
20963     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20964                       MI->getOperand(3).getTargetFlags())
20965     .addReg(0);
20966     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20967     addDirectMem(MIB, X86::EAX);
20968     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20969   }
20970
20971   MI->eraseFromParent(); // The pseudo instruction is gone now.
20972   return BB;
20973 }
20974
20975 MachineBasicBlock *
20976 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20977                                     MachineBasicBlock *MBB) const {
20978   DebugLoc DL = MI->getDebugLoc();
20979   MachineFunction *MF = MBB->getParent();
20980   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20981   MachineRegisterInfo &MRI = MF->getRegInfo();
20982
20983   const BasicBlock *BB = MBB->getBasicBlock();
20984   MachineFunction::iterator I = MBB;
20985   ++I;
20986
20987   // Memory Reference
20988   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20989   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20990
20991   unsigned DstReg;
20992   unsigned MemOpndSlot = 0;
20993
20994   unsigned CurOp = 0;
20995
20996   DstReg = MI->getOperand(CurOp++).getReg();
20997   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20998   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20999   unsigned mainDstReg = MRI.createVirtualRegister(RC);
21000   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21001
21002   MemOpndSlot = CurOp;
21003
21004   MVT PVT = getPointerTy(MF->getDataLayout());
21005   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21006          "Invalid Pointer Size!");
21007
21008   // For v = setjmp(buf), we generate
21009   //
21010   // thisMBB:
21011   //  buf[LabelOffset] = restoreMBB
21012   //  SjLjSetup restoreMBB
21013   //
21014   // mainMBB:
21015   //  v_main = 0
21016   //
21017   // sinkMBB:
21018   //  v = phi(main, restore)
21019   //
21020   // restoreMBB:
21021   //  if base pointer being used, load it from frame
21022   //  v_restore = 1
21023
21024   MachineBasicBlock *thisMBB = MBB;
21025   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21026   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21027   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21028   MF->insert(I, mainMBB);
21029   MF->insert(I, sinkMBB);
21030   MF->push_back(restoreMBB);
21031
21032   MachineInstrBuilder MIB;
21033
21034   // Transfer the remainder of BB and its successor edges to sinkMBB.
21035   sinkMBB->splice(sinkMBB->begin(), MBB,
21036                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21037   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21038
21039   // thisMBB:
21040   unsigned PtrStoreOpc = 0;
21041   unsigned LabelReg = 0;
21042   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21043   Reloc::Model RM = MF->getTarget().getRelocationModel();
21044   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21045                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21046
21047   // Prepare IP either in reg or imm.
21048   if (!UseImmLabel) {
21049     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21050     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21051     LabelReg = MRI.createVirtualRegister(PtrRC);
21052     if (Subtarget->is64Bit()) {
21053       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21054               .addReg(X86::RIP)
21055               .addImm(0)
21056               .addReg(0)
21057               .addMBB(restoreMBB)
21058               .addReg(0);
21059     } else {
21060       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21061       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21062               .addReg(XII->getGlobalBaseReg(MF))
21063               .addImm(0)
21064               .addReg(0)
21065               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21066               .addReg(0);
21067     }
21068   } else
21069     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21070   // Store IP
21071   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21072   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21073     if (i == X86::AddrDisp)
21074       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21075     else
21076       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21077   }
21078   if (!UseImmLabel)
21079     MIB.addReg(LabelReg);
21080   else
21081     MIB.addMBB(restoreMBB);
21082   MIB.setMemRefs(MMOBegin, MMOEnd);
21083   // Setup
21084   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21085           .addMBB(restoreMBB);
21086
21087   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21088   MIB.addRegMask(RegInfo->getNoPreservedMask());
21089   thisMBB->addSuccessor(mainMBB);
21090   thisMBB->addSuccessor(restoreMBB);
21091
21092   // mainMBB:
21093   //  EAX = 0
21094   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21095   mainMBB->addSuccessor(sinkMBB);
21096
21097   // sinkMBB:
21098   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21099           TII->get(X86::PHI), DstReg)
21100     .addReg(mainDstReg).addMBB(mainMBB)
21101     .addReg(restoreDstReg).addMBB(restoreMBB);
21102
21103   // restoreMBB:
21104   if (RegInfo->hasBasePointer(*MF)) {
21105     const bool Uses64BitFramePtr =
21106         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21107     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21108     X86FI->setRestoreBasePointer(MF);
21109     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21110     unsigned BasePtr = RegInfo->getBaseRegister();
21111     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21112     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21113                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
21114       .setMIFlag(MachineInstr::FrameSetup);
21115   }
21116   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21117   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21118   restoreMBB->addSuccessor(sinkMBB);
21119
21120   MI->eraseFromParent();
21121   return sinkMBB;
21122 }
21123
21124 MachineBasicBlock *
21125 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21126                                      MachineBasicBlock *MBB) const {
21127   DebugLoc DL = MI->getDebugLoc();
21128   MachineFunction *MF = MBB->getParent();
21129   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21130   MachineRegisterInfo &MRI = MF->getRegInfo();
21131
21132   // Memory Reference
21133   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21134   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21135
21136   MVT PVT = getPointerTy(MF->getDataLayout());
21137   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21138          "Invalid Pointer Size!");
21139
21140   const TargetRegisterClass *RC =
21141     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21142   unsigned Tmp = MRI.createVirtualRegister(RC);
21143   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21144   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21145   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21146   unsigned SP = RegInfo->getStackRegister();
21147
21148   MachineInstrBuilder MIB;
21149
21150   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21151   const int64_t SPOffset = 2 * PVT.getStoreSize();
21152
21153   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21154   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21155
21156   // Reload FP
21157   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21158   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21159     MIB.addOperand(MI->getOperand(i));
21160   MIB.setMemRefs(MMOBegin, MMOEnd);
21161   // Reload IP
21162   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21163   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21164     if (i == X86::AddrDisp)
21165       MIB.addDisp(MI->getOperand(i), LabelOffset);
21166     else
21167       MIB.addOperand(MI->getOperand(i));
21168   }
21169   MIB.setMemRefs(MMOBegin, MMOEnd);
21170   // Reload SP
21171   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21172   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21173     if (i == X86::AddrDisp)
21174       MIB.addDisp(MI->getOperand(i), SPOffset);
21175     else
21176       MIB.addOperand(MI->getOperand(i));
21177   }
21178   MIB.setMemRefs(MMOBegin, MMOEnd);
21179   // Jump
21180   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21181
21182   MI->eraseFromParent();
21183   return MBB;
21184 }
21185
21186 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21187 // accumulator loops. Writing back to the accumulator allows the coalescer
21188 // to remove extra copies in the loop.
21189 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
21190 MachineBasicBlock *
21191 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21192                                  MachineBasicBlock *MBB) const {
21193   MachineOperand &AddendOp = MI->getOperand(3);
21194
21195   // Bail out early if the addend isn't a register - we can't switch these.
21196   if (!AddendOp.isReg())
21197     return MBB;
21198
21199   MachineFunction &MF = *MBB->getParent();
21200   MachineRegisterInfo &MRI = MF.getRegInfo();
21201
21202   // Check whether the addend is defined by a PHI:
21203   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21204   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21205   if (!AddendDef.isPHI())
21206     return MBB;
21207
21208   // Look for the following pattern:
21209   // loop:
21210   //   %addend = phi [%entry, 0], [%loop, %result]
21211   //   ...
21212   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21213
21214   // Replace with:
21215   //   loop:
21216   //   %addend = phi [%entry, 0], [%loop, %result]
21217   //   ...
21218   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21219
21220   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21221     assert(AddendDef.getOperand(i).isReg());
21222     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21223     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21224     if (&PHISrcInst == MI) {
21225       // Found a matching instruction.
21226       unsigned NewFMAOpc = 0;
21227       switch (MI->getOpcode()) {
21228         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21229         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21230         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21231         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21232         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21233         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21234         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21235         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21236         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21237         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21238         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21239         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21240         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21241         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21242         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21243         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21244         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21245         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21246         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21247         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21248
21249         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21250         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21251         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21252         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21253         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21254         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21255         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21256         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21257         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21258         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21259         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21260         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21261         default: llvm_unreachable("Unrecognized FMA variant.");
21262       }
21263
21264       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21265       MachineInstrBuilder MIB =
21266         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21267         .addOperand(MI->getOperand(0))
21268         .addOperand(MI->getOperand(3))
21269         .addOperand(MI->getOperand(2))
21270         .addOperand(MI->getOperand(1));
21271       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21272       MI->eraseFromParent();
21273     }
21274   }
21275
21276   return MBB;
21277 }
21278
21279 MachineBasicBlock *
21280 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21281                                                MachineBasicBlock *BB) const {
21282   switch (MI->getOpcode()) {
21283   default: llvm_unreachable("Unexpected instr type to insert");
21284   case X86::TAILJMPd64:
21285   case X86::TAILJMPr64:
21286   case X86::TAILJMPm64:
21287   case X86::TAILJMPd64_REX:
21288   case X86::TAILJMPr64_REX:
21289   case X86::TAILJMPm64_REX:
21290     llvm_unreachable("TAILJMP64 would not be touched here.");
21291   case X86::TCRETURNdi64:
21292   case X86::TCRETURNri64:
21293   case X86::TCRETURNmi64:
21294     return BB;
21295   case X86::WIN_ALLOCA:
21296     return EmitLoweredWinAlloca(MI, BB);
21297   case X86::SEG_ALLOCA_32:
21298   case X86::SEG_ALLOCA_64:
21299     return EmitLoweredSegAlloca(MI, BB);
21300   case X86::TLSCall_32:
21301   case X86::TLSCall_64:
21302     return EmitLoweredTLSCall(MI, BB);
21303   case X86::CMOV_FR32:
21304   case X86::CMOV_FR64:
21305   case X86::CMOV_GR8:
21306   case X86::CMOV_GR16:
21307   case X86::CMOV_GR32:
21308   case X86::CMOV_RFP32:
21309   case X86::CMOV_RFP64:
21310   case X86::CMOV_RFP80:
21311   case X86::CMOV_V2F64:
21312   case X86::CMOV_V2I64:
21313   case X86::CMOV_V4F32:
21314   case X86::CMOV_V4F64:
21315   case X86::CMOV_V4I64:
21316   case X86::CMOV_V16F32:
21317   case X86::CMOV_V8F32:
21318   case X86::CMOV_V8F64:
21319   case X86::CMOV_V8I64:
21320   case X86::CMOV_V8I1:
21321   case X86::CMOV_V16I1:
21322   case X86::CMOV_V32I1:
21323   case X86::CMOV_V64I1:
21324     return EmitLoweredSelect(MI, BB);
21325
21326   case X86::RELEASE_FADD32mr:
21327   case X86::RELEASE_FADD64mr:
21328     return EmitLoweredAtomicFP(MI, BB);
21329
21330   case X86::FP32_TO_INT16_IN_MEM:
21331   case X86::FP32_TO_INT32_IN_MEM:
21332   case X86::FP32_TO_INT64_IN_MEM:
21333   case X86::FP64_TO_INT16_IN_MEM:
21334   case X86::FP64_TO_INT32_IN_MEM:
21335   case X86::FP64_TO_INT64_IN_MEM:
21336   case X86::FP80_TO_INT16_IN_MEM:
21337   case X86::FP80_TO_INT32_IN_MEM:
21338   case X86::FP80_TO_INT64_IN_MEM: {
21339     MachineFunction *F = BB->getParent();
21340     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21341     DebugLoc DL = MI->getDebugLoc();
21342
21343     // Change the floating point control register to use "round towards zero"
21344     // mode when truncating to an integer value.
21345     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21346     addFrameReference(BuildMI(*BB, MI, DL,
21347                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21348
21349     // Load the old value of the high byte of the control word...
21350     unsigned OldCW =
21351       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21352     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21353                       CWFrameIdx);
21354
21355     // Set the high part to be round to zero...
21356     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21357       .addImm(0xC7F);
21358
21359     // Reload the modified control word now...
21360     addFrameReference(BuildMI(*BB, MI, DL,
21361                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21362
21363     // Restore the memory image of control word to original value
21364     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21365       .addReg(OldCW);
21366
21367     // Get the X86 opcode to use.
21368     unsigned Opc;
21369     switch (MI->getOpcode()) {
21370     default: llvm_unreachable("illegal opcode!");
21371     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21372     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21373     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21374     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21375     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21376     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21377     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21378     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21379     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21380     }
21381
21382     X86AddressMode AM;
21383     MachineOperand &Op = MI->getOperand(0);
21384     if (Op.isReg()) {
21385       AM.BaseType = X86AddressMode::RegBase;
21386       AM.Base.Reg = Op.getReg();
21387     } else {
21388       AM.BaseType = X86AddressMode::FrameIndexBase;
21389       AM.Base.FrameIndex = Op.getIndex();
21390     }
21391     Op = MI->getOperand(1);
21392     if (Op.isImm())
21393       AM.Scale = Op.getImm();
21394     Op = MI->getOperand(2);
21395     if (Op.isImm())
21396       AM.IndexReg = Op.getImm();
21397     Op = MI->getOperand(3);
21398     if (Op.isGlobal()) {
21399       AM.GV = Op.getGlobal();
21400     } else {
21401       AM.Disp = Op.getImm();
21402     }
21403     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21404                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21405
21406     // Reload the original control word now.
21407     addFrameReference(BuildMI(*BB, MI, DL,
21408                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21409
21410     MI->eraseFromParent();   // The pseudo instruction is gone now.
21411     return BB;
21412   }
21413     // String/text processing lowering.
21414   case X86::PCMPISTRM128REG:
21415   case X86::VPCMPISTRM128REG:
21416   case X86::PCMPISTRM128MEM:
21417   case X86::VPCMPISTRM128MEM:
21418   case X86::PCMPESTRM128REG:
21419   case X86::VPCMPESTRM128REG:
21420   case X86::PCMPESTRM128MEM:
21421   case X86::VPCMPESTRM128MEM:
21422     assert(Subtarget->hasSSE42() &&
21423            "Target must have SSE4.2 or AVX features enabled");
21424     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21425
21426   // String/text processing lowering.
21427   case X86::PCMPISTRIREG:
21428   case X86::VPCMPISTRIREG:
21429   case X86::PCMPISTRIMEM:
21430   case X86::VPCMPISTRIMEM:
21431   case X86::PCMPESTRIREG:
21432   case X86::VPCMPESTRIREG:
21433   case X86::PCMPESTRIMEM:
21434   case X86::VPCMPESTRIMEM:
21435     assert(Subtarget->hasSSE42() &&
21436            "Target must have SSE4.2 or AVX features enabled");
21437     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21438
21439   // Thread synchronization.
21440   case X86::MONITOR:
21441     return EmitMonitor(MI, BB, Subtarget);
21442
21443   // xbegin
21444   case X86::XBEGIN:
21445     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21446
21447   case X86::VASTART_SAVE_XMM_REGS:
21448     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21449
21450   case X86::VAARG_64:
21451     return EmitVAARG64WithCustomInserter(MI, BB);
21452
21453   case X86::EH_SjLj_SetJmp32:
21454   case X86::EH_SjLj_SetJmp64:
21455     return emitEHSjLjSetJmp(MI, BB);
21456
21457   case X86::EH_SjLj_LongJmp32:
21458   case X86::EH_SjLj_LongJmp64:
21459     return emitEHSjLjLongJmp(MI, BB);
21460
21461   case TargetOpcode::STATEPOINT:
21462     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21463     // this point in the process.  We diverge later.
21464     return emitPatchPoint(MI, BB);
21465
21466   case TargetOpcode::STACKMAP:
21467   case TargetOpcode::PATCHPOINT:
21468     return emitPatchPoint(MI, BB);
21469
21470   case X86::VFMADDPDr213r:
21471   case X86::VFMADDPSr213r:
21472   case X86::VFMADDSDr213r:
21473   case X86::VFMADDSSr213r:
21474   case X86::VFMSUBPDr213r:
21475   case X86::VFMSUBPSr213r:
21476   case X86::VFMSUBSDr213r:
21477   case X86::VFMSUBSSr213r:
21478   case X86::VFNMADDPDr213r:
21479   case X86::VFNMADDPSr213r:
21480   case X86::VFNMADDSDr213r:
21481   case X86::VFNMADDSSr213r:
21482   case X86::VFNMSUBPDr213r:
21483   case X86::VFNMSUBPSr213r:
21484   case X86::VFNMSUBSDr213r:
21485   case X86::VFNMSUBSSr213r:
21486   case X86::VFMADDSUBPDr213r:
21487   case X86::VFMADDSUBPSr213r:
21488   case X86::VFMSUBADDPDr213r:
21489   case X86::VFMSUBADDPSr213r:
21490   case X86::VFMADDPDr213rY:
21491   case X86::VFMADDPSr213rY:
21492   case X86::VFMSUBPDr213rY:
21493   case X86::VFMSUBPSr213rY:
21494   case X86::VFNMADDPDr213rY:
21495   case X86::VFNMADDPSr213rY:
21496   case X86::VFNMSUBPDr213rY:
21497   case X86::VFNMSUBPSr213rY:
21498   case X86::VFMADDSUBPDr213rY:
21499   case X86::VFMADDSUBPSr213rY:
21500   case X86::VFMSUBADDPDr213rY:
21501   case X86::VFMSUBADDPSr213rY:
21502     return emitFMA3Instr(MI, BB);
21503   }
21504 }
21505
21506 //===----------------------------------------------------------------------===//
21507 //                           X86 Optimization Hooks
21508 //===----------------------------------------------------------------------===//
21509
21510 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21511                                                       APInt &KnownZero,
21512                                                       APInt &KnownOne,
21513                                                       const SelectionDAG &DAG,
21514                                                       unsigned Depth) const {
21515   unsigned BitWidth = KnownZero.getBitWidth();
21516   unsigned Opc = Op.getOpcode();
21517   assert((Opc >= ISD::BUILTIN_OP_END ||
21518           Opc == ISD::INTRINSIC_WO_CHAIN ||
21519           Opc == ISD::INTRINSIC_W_CHAIN ||
21520           Opc == ISD::INTRINSIC_VOID) &&
21521          "Should use MaskedValueIsZero if you don't know whether Op"
21522          " is a target node!");
21523
21524   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21525   switch (Opc) {
21526   default: break;
21527   case X86ISD::ADD:
21528   case X86ISD::SUB:
21529   case X86ISD::ADC:
21530   case X86ISD::SBB:
21531   case X86ISD::SMUL:
21532   case X86ISD::UMUL:
21533   case X86ISD::INC:
21534   case X86ISD::DEC:
21535   case X86ISD::OR:
21536   case X86ISD::XOR:
21537   case X86ISD::AND:
21538     // These nodes' second result is a boolean.
21539     if (Op.getResNo() == 0)
21540       break;
21541     // Fallthrough
21542   case X86ISD::SETCC:
21543     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21544     break;
21545   case ISD::INTRINSIC_WO_CHAIN: {
21546     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21547     unsigned NumLoBits = 0;
21548     switch (IntId) {
21549     default: break;
21550     case Intrinsic::x86_sse_movmsk_ps:
21551     case Intrinsic::x86_avx_movmsk_ps_256:
21552     case Intrinsic::x86_sse2_movmsk_pd:
21553     case Intrinsic::x86_avx_movmsk_pd_256:
21554     case Intrinsic::x86_mmx_pmovmskb:
21555     case Intrinsic::x86_sse2_pmovmskb_128:
21556     case Intrinsic::x86_avx2_pmovmskb: {
21557       // High bits of movmskp{s|d}, pmovmskb are known zero.
21558       switch (IntId) {
21559         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21560         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21561         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21562         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21563         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21564         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21565         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21566         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21567       }
21568       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21569       break;
21570     }
21571     }
21572     break;
21573   }
21574   }
21575 }
21576
21577 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21578   SDValue Op,
21579   const SelectionDAG &,
21580   unsigned Depth) const {
21581   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21582   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21583     return Op.getValueType().getScalarType().getSizeInBits();
21584
21585   // Fallback case.
21586   return 1;
21587 }
21588
21589 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21590 /// node is a GlobalAddress + offset.
21591 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21592                                        const GlobalValue* &GA,
21593                                        int64_t &Offset) const {
21594   if (N->getOpcode() == X86ISD::Wrapper) {
21595     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21596       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21597       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21598       return true;
21599     }
21600   }
21601   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21602 }
21603
21604 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21605 /// same as extracting the high 128-bit part of 256-bit vector and then
21606 /// inserting the result into the low part of a new 256-bit vector
21607 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21608   EVT VT = SVOp->getValueType(0);
21609   unsigned NumElems = VT.getVectorNumElements();
21610
21611   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21612   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21613     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21614         SVOp->getMaskElt(j) >= 0)
21615       return false;
21616
21617   return true;
21618 }
21619
21620 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21621 /// same as extracting the low 128-bit part of 256-bit vector and then
21622 /// inserting the result into the high part of a new 256-bit vector
21623 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21624   EVT VT = SVOp->getValueType(0);
21625   unsigned NumElems = VT.getVectorNumElements();
21626
21627   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21628   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21629     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21630         SVOp->getMaskElt(j) >= 0)
21631       return false;
21632
21633   return true;
21634 }
21635
21636 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21637 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21638                                         TargetLowering::DAGCombinerInfo &DCI,
21639                                         const X86Subtarget* Subtarget) {
21640   SDLoc dl(N);
21641   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21642   SDValue V1 = SVOp->getOperand(0);
21643   SDValue V2 = SVOp->getOperand(1);
21644   EVT VT = SVOp->getValueType(0);
21645   unsigned NumElems = VT.getVectorNumElements();
21646
21647   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21648       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21649     //
21650     //                   0,0,0,...
21651     //                      |
21652     //    V      UNDEF    BUILD_VECTOR    UNDEF
21653     //     \      /           \           /
21654     //  CONCAT_VECTOR         CONCAT_VECTOR
21655     //         \                  /
21656     //          \                /
21657     //          RESULT: V + zero extended
21658     //
21659     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21660         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21661         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21662       return SDValue();
21663
21664     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21665       return SDValue();
21666
21667     // To match the shuffle mask, the first half of the mask should
21668     // be exactly the first vector, and all the rest a splat with the
21669     // first element of the second one.
21670     for (unsigned i = 0; i != NumElems/2; ++i)
21671       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21672           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21673         return SDValue();
21674
21675     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21676     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21677       if (Ld->hasNUsesOfValue(1, 0)) {
21678         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21679         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21680         SDValue ResNode =
21681           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21682                                   Ld->getMemoryVT(),
21683                                   Ld->getPointerInfo(),
21684                                   Ld->getAlignment(),
21685                                   false/*isVolatile*/, true/*ReadMem*/,
21686                                   false/*WriteMem*/);
21687
21688         // Make sure the newly-created LOAD is in the same position as Ld in
21689         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21690         // and update uses of Ld's output chain to use the TokenFactor.
21691         if (Ld->hasAnyUseOfValue(1)) {
21692           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21693                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21694           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21695           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21696                                  SDValue(ResNode.getNode(), 1));
21697         }
21698
21699         return DAG.getBitcast(VT, ResNode);
21700       }
21701     }
21702
21703     // Emit a zeroed vector and insert the desired subvector on its
21704     // first half.
21705     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21706     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21707     return DCI.CombineTo(N, InsV);
21708   }
21709
21710   //===--------------------------------------------------------------------===//
21711   // Combine some shuffles into subvector extracts and inserts:
21712   //
21713
21714   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21715   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21716     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21717     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21718     return DCI.CombineTo(N, InsV);
21719   }
21720
21721   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21722   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21723     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21724     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21725     return DCI.CombineTo(N, InsV);
21726   }
21727
21728   return SDValue();
21729 }
21730
21731 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21732 /// possible.
21733 ///
21734 /// This is the leaf of the recursive combinine below. When we have found some
21735 /// chain of single-use x86 shuffle instructions and accumulated the combined
21736 /// shuffle mask represented by them, this will try to pattern match that mask
21737 /// into either a single instruction if there is a special purpose instruction
21738 /// for this operation, or into a PSHUFB instruction which is a fully general
21739 /// instruction but should only be used to replace chains over a certain depth.
21740 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21741                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21742                                    TargetLowering::DAGCombinerInfo &DCI,
21743                                    const X86Subtarget *Subtarget) {
21744   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21745
21746   // Find the operand that enters the chain. Note that multiple uses are OK
21747   // here, we're not going to remove the operand we find.
21748   SDValue Input = Op.getOperand(0);
21749   while (Input.getOpcode() == ISD::BITCAST)
21750     Input = Input.getOperand(0);
21751
21752   MVT VT = Input.getSimpleValueType();
21753   MVT RootVT = Root.getSimpleValueType();
21754   SDLoc DL(Root);
21755
21756   // Just remove no-op shuffle masks.
21757   if (Mask.size() == 1) {
21758     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21759                   /*AddTo*/ true);
21760     return true;
21761   }
21762
21763   // Use the float domain if the operand type is a floating point type.
21764   bool FloatDomain = VT.isFloatingPoint();
21765
21766   // For floating point shuffles, we don't have free copies in the shuffle
21767   // instructions or the ability to load as part of the instruction, so
21768   // canonicalize their shuffles to UNPCK or MOV variants.
21769   //
21770   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21771   // vectors because it can have a load folded into it that UNPCK cannot. This
21772   // doesn't preclude something switching to the shorter encoding post-RA.
21773   //
21774   // FIXME: Should teach these routines about AVX vector widths.
21775   if (FloatDomain && VT.getSizeInBits() == 128) {
21776     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21777       bool Lo = Mask.equals({0, 0});
21778       unsigned Shuffle;
21779       MVT ShuffleVT;
21780       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21781       // is no slower than UNPCKLPD but has the option to fold the input operand
21782       // into even an unaligned memory load.
21783       if (Lo && Subtarget->hasSSE3()) {
21784         Shuffle = X86ISD::MOVDDUP;
21785         ShuffleVT = MVT::v2f64;
21786       } else {
21787         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21788         // than the UNPCK variants.
21789         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21790         ShuffleVT = MVT::v4f32;
21791       }
21792       if (Depth == 1 && Root->getOpcode() == Shuffle)
21793         return false; // Nothing to do!
21794       Op = DAG.getBitcast(ShuffleVT, Input);
21795       DCI.AddToWorklist(Op.getNode());
21796       if (Shuffle == X86ISD::MOVDDUP)
21797         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21798       else
21799         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21800       DCI.AddToWorklist(Op.getNode());
21801       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21802                     /*AddTo*/ true);
21803       return true;
21804     }
21805     if (Subtarget->hasSSE3() &&
21806         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21807       bool Lo = Mask.equals({0, 0, 2, 2});
21808       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21809       MVT ShuffleVT = MVT::v4f32;
21810       if (Depth == 1 && Root->getOpcode() == Shuffle)
21811         return false; // Nothing to do!
21812       Op = DAG.getBitcast(ShuffleVT, Input);
21813       DCI.AddToWorklist(Op.getNode());
21814       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21815       DCI.AddToWorklist(Op.getNode());
21816       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21817                     /*AddTo*/ true);
21818       return true;
21819     }
21820     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21821       bool Lo = Mask.equals({0, 0, 1, 1});
21822       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21823       MVT ShuffleVT = MVT::v4f32;
21824       if (Depth == 1 && Root->getOpcode() == Shuffle)
21825         return false; // Nothing to do!
21826       Op = DAG.getBitcast(ShuffleVT, Input);
21827       DCI.AddToWorklist(Op.getNode());
21828       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21829       DCI.AddToWorklist(Op.getNode());
21830       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21831                     /*AddTo*/ true);
21832       return true;
21833     }
21834   }
21835
21836   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21837   // variants as none of these have single-instruction variants that are
21838   // superior to the UNPCK formulation.
21839   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21840       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21841        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21842        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21843        Mask.equals(
21844            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21845     bool Lo = Mask[0] == 0;
21846     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21847     if (Depth == 1 && Root->getOpcode() == Shuffle)
21848       return false; // Nothing to do!
21849     MVT ShuffleVT;
21850     switch (Mask.size()) {
21851     case 8:
21852       ShuffleVT = MVT::v8i16;
21853       break;
21854     case 16:
21855       ShuffleVT = MVT::v16i8;
21856       break;
21857     default:
21858       llvm_unreachable("Impossible mask size!");
21859     };
21860     Op = DAG.getBitcast(ShuffleVT, Input);
21861     DCI.AddToWorklist(Op.getNode());
21862     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21863     DCI.AddToWorklist(Op.getNode());
21864     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21865                   /*AddTo*/ true);
21866     return true;
21867   }
21868
21869   // Don't try to re-form single instruction chains under any circumstances now
21870   // that we've done encoding canonicalization for them.
21871   if (Depth < 2)
21872     return false;
21873
21874   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21875   // can replace them with a single PSHUFB instruction profitably. Intel's
21876   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21877   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21878   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21879     SmallVector<SDValue, 16> PSHUFBMask;
21880     int NumBytes = VT.getSizeInBits() / 8;
21881     int Ratio = NumBytes / Mask.size();
21882     for (int i = 0; i < NumBytes; ++i) {
21883       if (Mask[i / Ratio] == SM_SentinelUndef) {
21884         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21885         continue;
21886       }
21887       int M = Mask[i / Ratio] != SM_SentinelZero
21888                   ? Ratio * Mask[i / Ratio] + i % Ratio
21889                   : 255;
21890       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21891     }
21892     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21893     Op = DAG.getBitcast(ByteVT, Input);
21894     DCI.AddToWorklist(Op.getNode());
21895     SDValue PSHUFBMaskOp =
21896         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21897     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21898     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21899     DCI.AddToWorklist(Op.getNode());
21900     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21901                   /*AddTo*/ true);
21902     return true;
21903   }
21904
21905   // Failed to find any combines.
21906   return false;
21907 }
21908
21909 /// \brief Fully generic combining of x86 shuffle instructions.
21910 ///
21911 /// This should be the last combine run over the x86 shuffle instructions. Once
21912 /// they have been fully optimized, this will recursively consider all chains
21913 /// of single-use shuffle instructions, build a generic model of the cumulative
21914 /// shuffle operation, and check for simpler instructions which implement this
21915 /// operation. We use this primarily for two purposes:
21916 ///
21917 /// 1) Collapse generic shuffles to specialized single instructions when
21918 ///    equivalent. In most cases, this is just an encoding size win, but
21919 ///    sometimes we will collapse multiple generic shuffles into a single
21920 ///    special-purpose shuffle.
21921 /// 2) Look for sequences of shuffle instructions with 3 or more total
21922 ///    instructions, and replace them with the slightly more expensive SSSE3
21923 ///    PSHUFB instruction if available. We do this as the last combining step
21924 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21925 ///    a suitable short sequence of other instructions. The PHUFB will either
21926 ///    use a register or have to read from memory and so is slightly (but only
21927 ///    slightly) more expensive than the other shuffle instructions.
21928 ///
21929 /// Because this is inherently a quadratic operation (for each shuffle in
21930 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21931 /// This should never be an issue in practice as the shuffle lowering doesn't
21932 /// produce sequences of more than 8 instructions.
21933 ///
21934 /// FIXME: We will currently miss some cases where the redundant shuffling
21935 /// would simplify under the threshold for PSHUFB formation because of
21936 /// combine-ordering. To fix this, we should do the redundant instruction
21937 /// combining in this recursive walk.
21938 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21939                                           ArrayRef<int> RootMask,
21940                                           int Depth, bool HasPSHUFB,
21941                                           SelectionDAG &DAG,
21942                                           TargetLowering::DAGCombinerInfo &DCI,
21943                                           const X86Subtarget *Subtarget) {
21944   // Bound the depth of our recursive combine because this is ultimately
21945   // quadratic in nature.
21946   if (Depth > 8)
21947     return false;
21948
21949   // Directly rip through bitcasts to find the underlying operand.
21950   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21951     Op = Op.getOperand(0);
21952
21953   MVT VT = Op.getSimpleValueType();
21954   if (!VT.isVector())
21955     return false; // Bail if we hit a non-vector.
21956
21957   assert(Root.getSimpleValueType().isVector() &&
21958          "Shuffles operate on vector types!");
21959   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21960          "Can only combine shuffles of the same vector register size.");
21961
21962   if (!isTargetShuffle(Op.getOpcode()))
21963     return false;
21964   SmallVector<int, 16> OpMask;
21965   bool IsUnary;
21966   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21967   // We only can combine unary shuffles which we can decode the mask for.
21968   if (!HaveMask || !IsUnary)
21969     return false;
21970
21971   assert(VT.getVectorNumElements() == OpMask.size() &&
21972          "Different mask size from vector size!");
21973   assert(((RootMask.size() > OpMask.size() &&
21974            RootMask.size() % OpMask.size() == 0) ||
21975           (OpMask.size() > RootMask.size() &&
21976            OpMask.size() % RootMask.size() == 0) ||
21977           OpMask.size() == RootMask.size()) &&
21978          "The smaller number of elements must divide the larger.");
21979   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21980   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21981   assert(((RootRatio == 1 && OpRatio == 1) ||
21982           (RootRatio == 1) != (OpRatio == 1)) &&
21983          "Must not have a ratio for both incoming and op masks!");
21984
21985   SmallVector<int, 16> Mask;
21986   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21987
21988   // Merge this shuffle operation's mask into our accumulated mask. Note that
21989   // this shuffle's mask will be the first applied to the input, followed by the
21990   // root mask to get us all the way to the root value arrangement. The reason
21991   // for this order is that we are recursing up the operation chain.
21992   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21993     int RootIdx = i / RootRatio;
21994     if (RootMask[RootIdx] < 0) {
21995       // This is a zero or undef lane, we're done.
21996       Mask.push_back(RootMask[RootIdx]);
21997       continue;
21998     }
21999
22000     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22001     int OpIdx = RootMaskedIdx / OpRatio;
22002     if (OpMask[OpIdx] < 0) {
22003       // The incoming lanes are zero or undef, it doesn't matter which ones we
22004       // are using.
22005       Mask.push_back(OpMask[OpIdx]);
22006       continue;
22007     }
22008
22009     // Ok, we have non-zero lanes, map them through.
22010     Mask.push_back(OpMask[OpIdx] * OpRatio +
22011                    RootMaskedIdx % OpRatio);
22012   }
22013
22014   // See if we can recurse into the operand to combine more things.
22015   switch (Op.getOpcode()) {
22016     case X86ISD::PSHUFB:
22017       HasPSHUFB = true;
22018     case X86ISD::PSHUFD:
22019     case X86ISD::PSHUFHW:
22020     case X86ISD::PSHUFLW:
22021       if (Op.getOperand(0).hasOneUse() &&
22022           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22023                                         HasPSHUFB, DAG, DCI, Subtarget))
22024         return true;
22025       break;
22026
22027     case X86ISD::UNPCKL:
22028     case X86ISD::UNPCKH:
22029       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
22030       // We can't check for single use, we have to check that this shuffle is the only user.
22031       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22032           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22033                                         HasPSHUFB, DAG, DCI, Subtarget))
22034           return true;
22035       break;
22036   }
22037
22038   // Minor canonicalization of the accumulated shuffle mask to make it easier
22039   // to match below. All this does is detect masks with squential pairs of
22040   // elements, and shrink them to the half-width mask. It does this in a loop
22041   // so it will reduce the size of the mask to the minimal width mask which
22042   // performs an equivalent shuffle.
22043   SmallVector<int, 16> WidenedMask;
22044   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22045     Mask = std::move(WidenedMask);
22046     WidenedMask.clear();
22047   }
22048
22049   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22050                                 Subtarget);
22051 }
22052
22053 /// \brief Get the PSHUF-style mask from PSHUF node.
22054 ///
22055 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22056 /// PSHUF-style masks that can be reused with such instructions.
22057 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22058   MVT VT = N.getSimpleValueType();
22059   SmallVector<int, 4> Mask;
22060   bool IsUnary;
22061   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22062   (void)HaveMask;
22063   assert(HaveMask);
22064
22065   // If we have more than 128-bits, only the low 128-bits of shuffle mask
22066   // matter. Check that the upper masks are repeats and remove them.
22067   if (VT.getSizeInBits() > 128) {
22068     int LaneElts = 128 / VT.getScalarSizeInBits();
22069 #ifndef NDEBUG
22070     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22071       for (int j = 0; j < LaneElts; ++j)
22072         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22073                "Mask doesn't repeat in high 128-bit lanes!");
22074 #endif
22075     Mask.resize(LaneElts);
22076   }
22077
22078   switch (N.getOpcode()) {
22079   case X86ISD::PSHUFD:
22080     return Mask;
22081   case X86ISD::PSHUFLW:
22082     Mask.resize(4);
22083     return Mask;
22084   case X86ISD::PSHUFHW:
22085     Mask.erase(Mask.begin(), Mask.begin() + 4);
22086     for (int &M : Mask)
22087       M -= 4;
22088     return Mask;
22089   default:
22090     llvm_unreachable("No valid shuffle instruction found!");
22091   }
22092 }
22093
22094 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22095 ///
22096 /// We walk up the chain and look for a combinable shuffle, skipping over
22097 /// shuffles that we could hoist this shuffle's transformation past without
22098 /// altering anything.
22099 static SDValue
22100 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22101                              SelectionDAG &DAG,
22102                              TargetLowering::DAGCombinerInfo &DCI) {
22103   assert(N.getOpcode() == X86ISD::PSHUFD &&
22104          "Called with something other than an x86 128-bit half shuffle!");
22105   SDLoc DL(N);
22106
22107   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22108   // of the shuffles in the chain so that we can form a fresh chain to replace
22109   // this one.
22110   SmallVector<SDValue, 8> Chain;
22111   SDValue V = N.getOperand(0);
22112   for (; V.hasOneUse(); V = V.getOperand(0)) {
22113     switch (V.getOpcode()) {
22114     default:
22115       return SDValue(); // Nothing combined!
22116
22117     case ISD::BITCAST:
22118       // Skip bitcasts as we always know the type for the target specific
22119       // instructions.
22120       continue;
22121
22122     case X86ISD::PSHUFD:
22123       // Found another dword shuffle.
22124       break;
22125
22126     case X86ISD::PSHUFLW:
22127       // Check that the low words (being shuffled) are the identity in the
22128       // dword shuffle, and the high words are self-contained.
22129       if (Mask[0] != 0 || Mask[1] != 1 ||
22130           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22131         return SDValue();
22132
22133       Chain.push_back(V);
22134       continue;
22135
22136     case X86ISD::PSHUFHW:
22137       // Check that the high words (being shuffled) are the identity in the
22138       // dword shuffle, and the low words are self-contained.
22139       if (Mask[2] != 2 || Mask[3] != 3 ||
22140           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22141         return SDValue();
22142
22143       Chain.push_back(V);
22144       continue;
22145
22146     case X86ISD::UNPCKL:
22147     case X86ISD::UNPCKH:
22148       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22149       // shuffle into a preceding word shuffle.
22150       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
22151           V.getSimpleValueType().getScalarType() != MVT::i16)
22152         return SDValue();
22153
22154       // Search for a half-shuffle which we can combine with.
22155       unsigned CombineOp =
22156           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22157       if (V.getOperand(0) != V.getOperand(1) ||
22158           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22159         return SDValue();
22160       Chain.push_back(V);
22161       V = V.getOperand(0);
22162       do {
22163         switch (V.getOpcode()) {
22164         default:
22165           return SDValue(); // Nothing to combine.
22166
22167         case X86ISD::PSHUFLW:
22168         case X86ISD::PSHUFHW:
22169           if (V.getOpcode() == CombineOp)
22170             break;
22171
22172           Chain.push_back(V);
22173
22174           // Fallthrough!
22175         case ISD::BITCAST:
22176           V = V.getOperand(0);
22177           continue;
22178         }
22179         break;
22180       } while (V.hasOneUse());
22181       break;
22182     }
22183     // Break out of the loop if we break out of the switch.
22184     break;
22185   }
22186
22187   if (!V.hasOneUse())
22188     // We fell out of the loop without finding a viable combining instruction.
22189     return SDValue();
22190
22191   // Merge this node's mask and our incoming mask.
22192   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22193   for (int &M : Mask)
22194     M = VMask[M];
22195   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22196                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22197
22198   // Rebuild the chain around this new shuffle.
22199   while (!Chain.empty()) {
22200     SDValue W = Chain.pop_back_val();
22201
22202     if (V.getValueType() != W.getOperand(0).getValueType())
22203       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22204
22205     switch (W.getOpcode()) {
22206     default:
22207       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22208
22209     case X86ISD::UNPCKL:
22210     case X86ISD::UNPCKH:
22211       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22212       break;
22213
22214     case X86ISD::PSHUFD:
22215     case X86ISD::PSHUFLW:
22216     case X86ISD::PSHUFHW:
22217       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22218       break;
22219     }
22220   }
22221   if (V.getValueType() != N.getValueType())
22222     V = DAG.getBitcast(N.getValueType(), V);
22223
22224   // Return the new chain to replace N.
22225   return V;
22226 }
22227
22228 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
22229 ///
22230 /// We walk up the chain, skipping shuffles of the other half and looking
22231 /// through shuffles which switch halves trying to find a shuffle of the same
22232 /// pair of dwords.
22233 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22234                                         SelectionDAG &DAG,
22235                                         TargetLowering::DAGCombinerInfo &DCI) {
22236   assert(
22237       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22238       "Called with something other than an x86 128-bit half shuffle!");
22239   SDLoc DL(N);
22240   unsigned CombineOpcode = N.getOpcode();
22241
22242   // Walk up a single-use chain looking for a combinable shuffle.
22243   SDValue V = N.getOperand(0);
22244   for (; V.hasOneUse(); V = V.getOperand(0)) {
22245     switch (V.getOpcode()) {
22246     default:
22247       return false; // Nothing combined!
22248
22249     case ISD::BITCAST:
22250       // Skip bitcasts as we always know the type for the target specific
22251       // instructions.
22252       continue;
22253
22254     case X86ISD::PSHUFLW:
22255     case X86ISD::PSHUFHW:
22256       if (V.getOpcode() == CombineOpcode)
22257         break;
22258
22259       // Other-half shuffles are no-ops.
22260       continue;
22261     }
22262     // Break out of the loop if we break out of the switch.
22263     break;
22264   }
22265
22266   if (!V.hasOneUse())
22267     // We fell out of the loop without finding a viable combining instruction.
22268     return false;
22269
22270   // Combine away the bottom node as its shuffle will be accumulated into
22271   // a preceding shuffle.
22272   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22273
22274   // Record the old value.
22275   SDValue Old = V;
22276
22277   // Merge this node's mask and our incoming mask (adjusted to account for all
22278   // the pshufd instructions encountered).
22279   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22280   for (int &M : Mask)
22281     M = VMask[M];
22282   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22283                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22284
22285   // Check that the shuffles didn't cancel each other out. If not, we need to
22286   // combine to the new one.
22287   if (Old != V)
22288     // Replace the combinable shuffle with the combined one, updating all users
22289     // so that we re-evaluate the chain here.
22290     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22291
22292   return true;
22293 }
22294
22295 /// \brief Try to combine x86 target specific shuffles.
22296 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22297                                            TargetLowering::DAGCombinerInfo &DCI,
22298                                            const X86Subtarget *Subtarget) {
22299   SDLoc DL(N);
22300   MVT VT = N.getSimpleValueType();
22301   SmallVector<int, 4> Mask;
22302
22303   switch (N.getOpcode()) {
22304   case X86ISD::PSHUFD:
22305   case X86ISD::PSHUFLW:
22306   case X86ISD::PSHUFHW:
22307     Mask = getPSHUFShuffleMask(N);
22308     assert(Mask.size() == 4);
22309     break;
22310   default:
22311     return SDValue();
22312   }
22313
22314   // Nuke no-op shuffles that show up after combining.
22315   if (isNoopShuffleMask(Mask))
22316     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22317
22318   // Look for simplifications involving one or two shuffle instructions.
22319   SDValue V = N.getOperand(0);
22320   switch (N.getOpcode()) {
22321   default:
22322     break;
22323   case X86ISD::PSHUFLW:
22324   case X86ISD::PSHUFHW:
22325     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22326
22327     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22328       return SDValue(); // We combined away this shuffle, so we're done.
22329
22330     // See if this reduces to a PSHUFD which is no more expensive and can
22331     // combine with more operations. Note that it has to at least flip the
22332     // dwords as otherwise it would have been removed as a no-op.
22333     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22334       int DMask[] = {0, 1, 2, 3};
22335       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22336       DMask[DOffset + 0] = DOffset + 1;
22337       DMask[DOffset + 1] = DOffset + 0;
22338       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22339       V = DAG.getBitcast(DVT, V);
22340       DCI.AddToWorklist(V.getNode());
22341       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22342                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22343       DCI.AddToWorklist(V.getNode());
22344       return DAG.getBitcast(VT, V);
22345     }
22346
22347     // Look for shuffle patterns which can be implemented as a single unpack.
22348     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22349     // only works when we have a PSHUFD followed by two half-shuffles.
22350     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22351         (V.getOpcode() == X86ISD::PSHUFLW ||
22352          V.getOpcode() == X86ISD::PSHUFHW) &&
22353         V.getOpcode() != N.getOpcode() &&
22354         V.hasOneUse()) {
22355       SDValue D = V.getOperand(0);
22356       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22357         D = D.getOperand(0);
22358       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22359         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22360         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22361         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22362         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22363         int WordMask[8];
22364         for (int i = 0; i < 4; ++i) {
22365           WordMask[i + NOffset] = Mask[i] + NOffset;
22366           WordMask[i + VOffset] = VMask[i] + VOffset;
22367         }
22368         // Map the word mask through the DWord mask.
22369         int MappedMask[8];
22370         for (int i = 0; i < 8; ++i)
22371           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22372         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22373             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22374           // We can replace all three shuffles with an unpack.
22375           V = DAG.getBitcast(VT, D.getOperand(0));
22376           DCI.AddToWorklist(V.getNode());
22377           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22378                                                 : X86ISD::UNPCKH,
22379                              DL, VT, V, V);
22380         }
22381       }
22382     }
22383
22384     break;
22385
22386   case X86ISD::PSHUFD:
22387     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22388       return NewN;
22389
22390     break;
22391   }
22392
22393   return SDValue();
22394 }
22395
22396 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22397 ///
22398 /// We combine this directly on the abstract vector shuffle nodes so it is
22399 /// easier to generically match. We also insert dummy vector shuffle nodes for
22400 /// the operands which explicitly discard the lanes which are unused by this
22401 /// operation to try to flow through the rest of the combiner the fact that
22402 /// they're unused.
22403 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22404   SDLoc DL(N);
22405   EVT VT = N->getValueType(0);
22406
22407   // We only handle target-independent shuffles.
22408   // FIXME: It would be easy and harmless to use the target shuffle mask
22409   // extraction tool to support more.
22410   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22411     return SDValue();
22412
22413   auto *SVN = cast<ShuffleVectorSDNode>(N);
22414   ArrayRef<int> Mask = SVN->getMask();
22415   SDValue V1 = N->getOperand(0);
22416   SDValue V2 = N->getOperand(1);
22417
22418   // We require the first shuffle operand to be the SUB node, and the second to
22419   // be the ADD node.
22420   // FIXME: We should support the commuted patterns.
22421   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22422     return SDValue();
22423
22424   // If there are other uses of these operations we can't fold them.
22425   if (!V1->hasOneUse() || !V2->hasOneUse())
22426     return SDValue();
22427
22428   // Ensure that both operations have the same operands. Note that we can
22429   // commute the FADD operands.
22430   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22431   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22432       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22433     return SDValue();
22434
22435   // We're looking for blends between FADD and FSUB nodes. We insist on these
22436   // nodes being lined up in a specific expected pattern.
22437   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22438         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22439         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22440     return SDValue();
22441
22442   // Only specific types are legal at this point, assert so we notice if and
22443   // when these change.
22444   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22445           VT == MVT::v4f64) &&
22446          "Unknown vector type encountered!");
22447
22448   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22449 }
22450
22451 /// PerformShuffleCombine - Performs several different shuffle combines.
22452 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22453                                      TargetLowering::DAGCombinerInfo &DCI,
22454                                      const X86Subtarget *Subtarget) {
22455   SDLoc dl(N);
22456   SDValue N0 = N->getOperand(0);
22457   SDValue N1 = N->getOperand(1);
22458   EVT VT = N->getValueType(0);
22459
22460   // Don't create instructions with illegal types after legalize types has run.
22461   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22462   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22463     return SDValue();
22464
22465   // If we have legalized the vector types, look for blends of FADD and FSUB
22466   // nodes that we can fuse into an ADDSUB node.
22467   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22468     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22469       return AddSub;
22470
22471   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22472   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22473       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22474     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22475
22476   // During Type Legalization, when promoting illegal vector types,
22477   // the backend might introduce new shuffle dag nodes and bitcasts.
22478   //
22479   // This code performs the following transformation:
22480   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22481   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22482   //
22483   // We do this only if both the bitcast and the BINOP dag nodes have
22484   // one use. Also, perform this transformation only if the new binary
22485   // operation is legal. This is to avoid introducing dag nodes that
22486   // potentially need to be further expanded (or custom lowered) into a
22487   // less optimal sequence of dag nodes.
22488   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22489       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22490       N0.getOpcode() == ISD::BITCAST) {
22491     SDValue BC0 = N0.getOperand(0);
22492     EVT SVT = BC0.getValueType();
22493     unsigned Opcode = BC0.getOpcode();
22494     unsigned NumElts = VT.getVectorNumElements();
22495
22496     if (BC0.hasOneUse() && SVT.isVector() &&
22497         SVT.getVectorNumElements() * 2 == NumElts &&
22498         TLI.isOperationLegal(Opcode, VT)) {
22499       bool CanFold = false;
22500       switch (Opcode) {
22501       default : break;
22502       case ISD::ADD :
22503       case ISD::FADD :
22504       case ISD::SUB :
22505       case ISD::FSUB :
22506       case ISD::MUL :
22507       case ISD::FMUL :
22508         CanFold = true;
22509       }
22510
22511       unsigned SVTNumElts = SVT.getVectorNumElements();
22512       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22513       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22514         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22515       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22516         CanFold = SVOp->getMaskElt(i) < 0;
22517
22518       if (CanFold) {
22519         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22520         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22521         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22522         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22523       }
22524     }
22525   }
22526
22527   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22528   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22529   // consecutive, non-overlapping, and in the right order.
22530   SmallVector<SDValue, 16> Elts;
22531   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22532     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22533
22534   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22535     return LD;
22536
22537   if (isTargetShuffle(N->getOpcode())) {
22538     SDValue Shuffle =
22539         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22540     if (Shuffle.getNode())
22541       return Shuffle;
22542
22543     // Try recursively combining arbitrary sequences of x86 shuffle
22544     // instructions into higher-order shuffles. We do this after combining
22545     // specific PSHUF instruction sequences into their minimal form so that we
22546     // can evaluate how many specialized shuffle instructions are involved in
22547     // a particular chain.
22548     SmallVector<int, 1> NonceMask; // Just a placeholder.
22549     NonceMask.push_back(0);
22550     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22551                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22552                                       DCI, Subtarget))
22553       return SDValue(); // This routine will use CombineTo to replace N.
22554   }
22555
22556   return SDValue();
22557 }
22558
22559 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22560 /// specific shuffle of a load can be folded into a single element load.
22561 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22562 /// shuffles have been custom lowered so we need to handle those here.
22563 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22564                                          TargetLowering::DAGCombinerInfo &DCI) {
22565   if (DCI.isBeforeLegalizeOps())
22566     return SDValue();
22567
22568   SDValue InVec = N->getOperand(0);
22569   SDValue EltNo = N->getOperand(1);
22570
22571   if (!isa<ConstantSDNode>(EltNo))
22572     return SDValue();
22573
22574   EVT OriginalVT = InVec.getValueType();
22575
22576   if (InVec.getOpcode() == ISD::BITCAST) {
22577     // Don't duplicate a load with other uses.
22578     if (!InVec.hasOneUse())
22579       return SDValue();
22580     EVT BCVT = InVec.getOperand(0).getValueType();
22581     if (!BCVT.isVector() ||
22582         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22583       return SDValue();
22584     InVec = InVec.getOperand(0);
22585   }
22586
22587   EVT CurrentVT = InVec.getValueType();
22588
22589   if (!isTargetShuffle(InVec.getOpcode()))
22590     return SDValue();
22591
22592   // Don't duplicate a load with other uses.
22593   if (!InVec.hasOneUse())
22594     return SDValue();
22595
22596   SmallVector<int, 16> ShuffleMask;
22597   bool UnaryShuffle;
22598   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22599                             ShuffleMask, UnaryShuffle))
22600     return SDValue();
22601
22602   // Select the input vector, guarding against out of range extract vector.
22603   unsigned NumElems = CurrentVT.getVectorNumElements();
22604   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22605   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22606   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22607                                          : InVec.getOperand(1);
22608
22609   // If inputs to shuffle are the same for both ops, then allow 2 uses
22610   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22611                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22612
22613   if (LdNode.getOpcode() == ISD::BITCAST) {
22614     // Don't duplicate a load with other uses.
22615     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22616       return SDValue();
22617
22618     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22619     LdNode = LdNode.getOperand(0);
22620   }
22621
22622   if (!ISD::isNormalLoad(LdNode.getNode()))
22623     return SDValue();
22624
22625   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22626
22627   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22628     return SDValue();
22629
22630   EVT EltVT = N->getValueType(0);
22631   // If there's a bitcast before the shuffle, check if the load type and
22632   // alignment is valid.
22633   unsigned Align = LN0->getAlignment();
22634   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22635   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22636       EltVT.getTypeForEVT(*DAG.getContext()));
22637
22638   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22639     return SDValue();
22640
22641   // All checks match so transform back to vector_shuffle so that DAG combiner
22642   // can finish the job
22643   SDLoc dl(N);
22644
22645   // Create shuffle node taking into account the case that its a unary shuffle
22646   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22647                                    : InVec.getOperand(1);
22648   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22649                                  InVec.getOperand(0), Shuffle,
22650                                  &ShuffleMask[0]);
22651   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22652   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22653                      EltNo);
22654 }
22655
22656 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22657 /// special and don't usually play with other vector types, it's better to
22658 /// handle them early to be sure we emit efficient code by avoiding
22659 /// store-load conversions.
22660 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22661   if (N->getValueType(0) != MVT::x86mmx ||
22662       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22663       N->getOperand(0)->getValueType(0) != MVT::v2i32)
22664     return SDValue();
22665
22666   SDValue V = N->getOperand(0);
22667   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22668   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22669     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22670                        N->getValueType(0), V.getOperand(0));
22671
22672   return SDValue();
22673 }
22674
22675 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22676 /// generation and convert it from being a bunch of shuffles and extracts
22677 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22678 /// storing the value and loading scalars back, while for x64 we should
22679 /// use 64-bit extracts and shifts.
22680 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22681                                          TargetLowering::DAGCombinerInfo &DCI) {
22682   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22683     return NewOp;
22684
22685   SDValue InputVector = N->getOperand(0);
22686   SDLoc dl(InputVector);
22687   // Detect mmx to i32 conversion through a v2i32 elt extract.
22688   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22689       N->getValueType(0) == MVT::i32 &&
22690       InputVector.getValueType() == MVT::v2i32) {
22691
22692     // The bitcast source is a direct mmx result.
22693     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22694     if (MMXSrc.getValueType() == MVT::x86mmx)
22695       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22696                          N->getValueType(0),
22697                          InputVector.getNode()->getOperand(0));
22698
22699     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22700     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22701     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22702         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22703         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22704         MMXSrcOp.getValueType() == MVT::v1i64 &&
22705         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22706       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22707                          N->getValueType(0),
22708                          MMXSrcOp.getOperand(0));
22709   }
22710
22711   EVT VT = N->getValueType(0);
22712
22713   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22714       InputVector.getOpcode() == ISD::BITCAST &&
22715       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22716     uint64_t ExtractedElt =
22717           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22718     uint64_t InputValue =
22719           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22720     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22721     return DAG.getConstant(Res, dl, MVT::i1);
22722   }
22723   // Only operate on vectors of 4 elements, where the alternative shuffling
22724   // gets to be more expensive.
22725   if (InputVector.getValueType() != MVT::v4i32)
22726     return SDValue();
22727
22728   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22729   // single use which is a sign-extend or zero-extend, and all elements are
22730   // used.
22731   SmallVector<SDNode *, 4> Uses;
22732   unsigned ExtractedElements = 0;
22733   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22734        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22735     if (UI.getUse().getResNo() != InputVector.getResNo())
22736       return SDValue();
22737
22738     SDNode *Extract = *UI;
22739     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22740       return SDValue();
22741
22742     if (Extract->getValueType(0) != MVT::i32)
22743       return SDValue();
22744     if (!Extract->hasOneUse())
22745       return SDValue();
22746     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22747         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22748       return SDValue();
22749     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22750       return SDValue();
22751
22752     // Record which element was extracted.
22753     ExtractedElements |=
22754       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22755
22756     Uses.push_back(Extract);
22757   }
22758
22759   // If not all the elements were used, this may not be worthwhile.
22760   if (ExtractedElements != 15)
22761     return SDValue();
22762
22763   // Ok, we've now decided to do the transformation.
22764   // If 64-bit shifts are legal, use the extract-shift sequence,
22765   // otherwise bounce the vector off the cache.
22766   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22767   SDValue Vals[4];
22768
22769   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22770     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22771     auto &DL = DAG.getDataLayout();
22772     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22773     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22774       DAG.getConstant(0, dl, VecIdxTy));
22775     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22776       DAG.getConstant(1, dl, VecIdxTy));
22777
22778     SDValue ShAmt = DAG.getConstant(
22779         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22780     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22781     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22782       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22783     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22784     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22785       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22786   } else {
22787     // Store the value to a temporary stack slot.
22788     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22789     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22790       MachinePointerInfo(), false, false, 0);
22791
22792     EVT ElementType = InputVector.getValueType().getVectorElementType();
22793     unsigned EltSize = ElementType.getSizeInBits() / 8;
22794
22795     // Replace each use (extract) with a load of the appropriate element.
22796     for (unsigned i = 0; i < 4; ++i) {
22797       uint64_t Offset = EltSize * i;
22798       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22799       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22800
22801       SDValue ScalarAddr =
22802           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22803
22804       // Load the scalar.
22805       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22806                             ScalarAddr, MachinePointerInfo(),
22807                             false, false, false, 0);
22808
22809     }
22810   }
22811
22812   // Replace the extracts
22813   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22814     UE = Uses.end(); UI != UE; ++UI) {
22815     SDNode *Extract = *UI;
22816
22817     SDValue Idx = Extract->getOperand(1);
22818     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22819     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22820   }
22821
22822   // The replacement was made in place; don't return anything.
22823   return SDValue();
22824 }
22825
22826 static SDValue
22827 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22828                                       const X86Subtarget *Subtarget) {
22829   SDLoc dl(N);
22830   SDValue Cond = N->getOperand(0);
22831   SDValue LHS = N->getOperand(1);
22832   SDValue RHS = N->getOperand(2);
22833
22834   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22835     SDValue CondSrc = Cond->getOperand(0);
22836     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22837       Cond = CondSrc->getOperand(0);
22838   }
22839
22840   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22841     return SDValue();
22842
22843   // A vselect where all conditions and data are constants can be optimized into
22844   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22845   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22846       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22847     return SDValue();
22848
22849   unsigned MaskValue = 0;
22850   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22851     return SDValue();
22852
22853   MVT VT = N->getSimpleValueType(0);
22854   unsigned NumElems = VT.getVectorNumElements();
22855   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22856   for (unsigned i = 0; i < NumElems; ++i) {
22857     // Be sure we emit undef where we can.
22858     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22859       ShuffleMask[i] = -1;
22860     else
22861       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22862   }
22863
22864   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22865   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22866     return SDValue();
22867   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22868 }
22869
22870 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22871 /// nodes.
22872 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22873                                     TargetLowering::DAGCombinerInfo &DCI,
22874                                     const X86Subtarget *Subtarget) {
22875   SDLoc DL(N);
22876   SDValue Cond = N->getOperand(0);
22877   // Get the LHS/RHS of the select.
22878   SDValue LHS = N->getOperand(1);
22879   SDValue RHS = N->getOperand(2);
22880   EVT VT = LHS.getValueType();
22881   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22882
22883   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22884   // instructions match the semantics of the common C idiom x<y?x:y but not
22885   // x<=y?x:y, because of how they handle negative zero (which can be
22886   // ignored in unsafe-math mode).
22887   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22888   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22889       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22890       (Subtarget->hasSSE2() ||
22891        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22892     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22893
22894     unsigned Opcode = 0;
22895     // Check for x CC y ? x : y.
22896     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22897         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22898       switch (CC) {
22899       default: break;
22900       case ISD::SETULT:
22901         // Converting this to a min would handle NaNs incorrectly, and swapping
22902         // the operands would cause it to handle comparisons between positive
22903         // and negative zero incorrectly.
22904         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22905           if (!DAG.getTarget().Options.UnsafeFPMath &&
22906               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22907             break;
22908           std::swap(LHS, RHS);
22909         }
22910         Opcode = X86ISD::FMIN;
22911         break;
22912       case ISD::SETOLE:
22913         // Converting this to a min would handle comparisons between positive
22914         // and negative zero incorrectly.
22915         if (!DAG.getTarget().Options.UnsafeFPMath &&
22916             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22917           break;
22918         Opcode = X86ISD::FMIN;
22919         break;
22920       case ISD::SETULE:
22921         // Converting this to a min would handle both negative zeros and NaNs
22922         // incorrectly, but we can swap the operands to fix both.
22923         std::swap(LHS, RHS);
22924       case ISD::SETOLT:
22925       case ISD::SETLT:
22926       case ISD::SETLE:
22927         Opcode = X86ISD::FMIN;
22928         break;
22929
22930       case ISD::SETOGE:
22931         // Converting this to a max would handle comparisons between positive
22932         // and negative zero incorrectly.
22933         if (!DAG.getTarget().Options.UnsafeFPMath &&
22934             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22935           break;
22936         Opcode = X86ISD::FMAX;
22937         break;
22938       case ISD::SETUGT:
22939         // Converting this to a max would handle NaNs incorrectly, and swapping
22940         // the operands would cause it to handle comparisons between positive
22941         // and negative zero incorrectly.
22942         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22943           if (!DAG.getTarget().Options.UnsafeFPMath &&
22944               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22945             break;
22946           std::swap(LHS, RHS);
22947         }
22948         Opcode = X86ISD::FMAX;
22949         break;
22950       case ISD::SETUGE:
22951         // Converting this to a max would handle both negative zeros and NaNs
22952         // incorrectly, but we can swap the operands to fix both.
22953         std::swap(LHS, RHS);
22954       case ISD::SETOGT:
22955       case ISD::SETGT:
22956       case ISD::SETGE:
22957         Opcode = X86ISD::FMAX;
22958         break;
22959       }
22960     // Check for x CC y ? y : x -- a min/max with reversed arms.
22961     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22962                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22963       switch (CC) {
22964       default: break;
22965       case ISD::SETOGE:
22966         // Converting this to a min would handle comparisons between positive
22967         // and negative zero incorrectly, and swapping the operands would
22968         // cause it to handle NaNs incorrectly.
22969         if (!DAG.getTarget().Options.UnsafeFPMath &&
22970             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22971           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22972             break;
22973           std::swap(LHS, RHS);
22974         }
22975         Opcode = X86ISD::FMIN;
22976         break;
22977       case ISD::SETUGT:
22978         // Converting this to a min would handle NaNs incorrectly.
22979         if (!DAG.getTarget().Options.UnsafeFPMath &&
22980             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22981           break;
22982         Opcode = X86ISD::FMIN;
22983         break;
22984       case ISD::SETUGE:
22985         // Converting this to a min would handle both negative zeros and NaNs
22986         // incorrectly, but we can swap the operands to fix both.
22987         std::swap(LHS, RHS);
22988       case ISD::SETOGT:
22989       case ISD::SETGT:
22990       case ISD::SETGE:
22991         Opcode = X86ISD::FMIN;
22992         break;
22993
22994       case ISD::SETULT:
22995         // Converting this to a max would handle NaNs incorrectly.
22996         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22997           break;
22998         Opcode = X86ISD::FMAX;
22999         break;
23000       case ISD::SETOLE:
23001         // Converting this to a max would handle comparisons between positive
23002         // and negative zero incorrectly, and swapping the operands would
23003         // cause it to handle NaNs incorrectly.
23004         if (!DAG.getTarget().Options.UnsafeFPMath &&
23005             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23006           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23007             break;
23008           std::swap(LHS, RHS);
23009         }
23010         Opcode = X86ISD::FMAX;
23011         break;
23012       case ISD::SETULE:
23013         // Converting this to a max would handle both negative zeros and NaNs
23014         // incorrectly, but we can swap the operands to fix both.
23015         std::swap(LHS, RHS);
23016       case ISD::SETOLT:
23017       case ISD::SETLT:
23018       case ISD::SETLE:
23019         Opcode = X86ISD::FMAX;
23020         break;
23021       }
23022     }
23023
23024     if (Opcode)
23025       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23026   }
23027
23028   EVT CondVT = Cond.getValueType();
23029   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23030       CondVT.getVectorElementType() == MVT::i1) {
23031     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23032     // lowering on KNL. In this case we convert it to
23033     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23034     // The same situation for all 128 and 256-bit vectors of i8 and i16.
23035     // Since SKX these selects have a proper lowering.
23036     EVT OpVT = LHS.getValueType();
23037     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23038         (OpVT.getVectorElementType() == MVT::i8 ||
23039          OpVT.getVectorElementType() == MVT::i16) &&
23040         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23041       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23042       DCI.AddToWorklist(Cond.getNode());
23043       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23044     }
23045   }
23046   // If this is a select between two integer constants, try to do some
23047   // optimizations.
23048   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23049     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23050       // Don't do this for crazy integer types.
23051       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23052         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23053         // so that TrueC (the true value) is larger than FalseC.
23054         bool NeedsCondInvert = false;
23055
23056         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23057             // Efficiently invertible.
23058             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
23059              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
23060               isa<ConstantSDNode>(Cond.getOperand(1))))) {
23061           NeedsCondInvert = true;
23062           std::swap(TrueC, FalseC);
23063         }
23064
23065         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
23066         if (FalseC->getAPIntValue() == 0 &&
23067             TrueC->getAPIntValue().isPowerOf2()) {
23068           if (NeedsCondInvert) // Invert the condition if needed.
23069             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23070                                DAG.getConstant(1, DL, Cond.getValueType()));
23071
23072           // Zero extend the condition if needed.
23073           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23074
23075           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23076           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23077                              DAG.getConstant(ShAmt, DL, MVT::i8));
23078         }
23079
23080         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23081         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23082           if (NeedsCondInvert) // Invert the condition if needed.
23083             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23084                                DAG.getConstant(1, DL, Cond.getValueType()));
23085
23086           // Zero extend the condition if needed.
23087           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23088                              FalseC->getValueType(0), Cond);
23089           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23090                              SDValue(FalseC, 0));
23091         }
23092
23093         // Optimize cases that will turn into an LEA instruction.  This requires
23094         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23095         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23096           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23097           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23098
23099           bool isFastMultiplier = false;
23100           if (Diff < 10) {
23101             switch ((unsigned char)Diff) {
23102               default: break;
23103               case 1:  // result = add base, cond
23104               case 2:  // result = lea base(    , cond*2)
23105               case 3:  // result = lea base(cond, cond*2)
23106               case 4:  // result = lea base(    , cond*4)
23107               case 5:  // result = lea base(cond, cond*4)
23108               case 8:  // result = lea base(    , cond*8)
23109               case 9:  // result = lea base(cond, cond*8)
23110                 isFastMultiplier = true;
23111                 break;
23112             }
23113           }
23114
23115           if (isFastMultiplier) {
23116             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23117             if (NeedsCondInvert) // Invert the condition if needed.
23118               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23119                                  DAG.getConstant(1, DL, Cond.getValueType()));
23120
23121             // Zero extend the condition if needed.
23122             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23123                                Cond);
23124             // Scale the condition by the difference.
23125             if (Diff != 1)
23126               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23127                                  DAG.getConstant(Diff, DL,
23128                                                  Cond.getValueType()));
23129
23130             // Add the base if non-zero.
23131             if (FalseC->getAPIntValue() != 0)
23132               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23133                                  SDValue(FalseC, 0));
23134             return Cond;
23135           }
23136         }
23137       }
23138   }
23139
23140   // Canonicalize max and min:
23141   // (x > y) ? x : y -> (x >= y) ? x : y
23142   // (x < y) ? x : y -> (x <= y) ? x : y
23143   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23144   // the need for an extra compare
23145   // against zero. e.g.
23146   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23147   // subl   %esi, %edi
23148   // testl  %edi, %edi
23149   // movl   $0, %eax
23150   // cmovgl %edi, %eax
23151   // =>
23152   // xorl   %eax, %eax
23153   // subl   %esi, $edi
23154   // cmovsl %eax, %edi
23155   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23156       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23157       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23158     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23159     switch (CC) {
23160     default: break;
23161     case ISD::SETLT:
23162     case ISD::SETGT: {
23163       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23164       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23165                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23166       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23167     }
23168     }
23169   }
23170
23171   // Early exit check
23172   if (!TLI.isTypeLegal(VT))
23173     return SDValue();
23174
23175   // Match VSELECTs into subs with unsigned saturation.
23176   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23177       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23178       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23179        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23180     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23181
23182     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23183     // left side invert the predicate to simplify logic below.
23184     SDValue Other;
23185     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23186       Other = RHS;
23187       CC = ISD::getSetCCInverse(CC, true);
23188     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23189       Other = LHS;
23190     }
23191
23192     if (Other.getNode() && Other->getNumOperands() == 2 &&
23193         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23194       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23195       SDValue CondRHS = Cond->getOperand(1);
23196
23197       // Look for a general sub with unsigned saturation first.
23198       // x >= y ? x-y : 0 --> subus x, y
23199       // x >  y ? x-y : 0 --> subus x, y
23200       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23201           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23202         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23203
23204       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23205         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23206           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23207             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23208               // If the RHS is a constant we have to reverse the const
23209               // canonicalization.
23210               // x > C-1 ? x+-C : 0 --> subus x, C
23211               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23212                   CondRHSConst->getAPIntValue() ==
23213                       (-OpRHSConst->getAPIntValue() - 1))
23214                 return DAG.getNode(
23215                     X86ISD::SUBUS, DL, VT, OpLHS,
23216                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23217
23218           // Another special case: If C was a sign bit, the sub has been
23219           // canonicalized into a xor.
23220           // FIXME: Would it be better to use computeKnownBits to determine
23221           //        whether it's safe to decanonicalize the xor?
23222           // x s< 0 ? x^C : 0 --> subus x, C
23223           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23224               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23225               OpRHSConst->getAPIntValue().isSignBit())
23226             // Note that we have to rebuild the RHS constant here to ensure we
23227             // don't rely on particular values of undef lanes.
23228             return DAG.getNode(
23229                 X86ISD::SUBUS, DL, VT, OpLHS,
23230                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23231         }
23232     }
23233   }
23234
23235   // Simplify vector selection if condition value type matches vselect
23236   // operand type
23237   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23238     assert(Cond.getValueType().isVector() &&
23239            "vector select expects a vector selector!");
23240
23241     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23242     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23243
23244     // Try invert the condition if true value is not all 1s and false value
23245     // is not all 0s.
23246     if (!TValIsAllOnes && !FValIsAllZeros &&
23247         // Check if the selector will be produced by CMPP*/PCMP*
23248         Cond.getOpcode() == ISD::SETCC &&
23249         // Check if SETCC has already been promoted
23250         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23251             CondVT) {
23252       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23253       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23254
23255       if (TValIsAllZeros || FValIsAllOnes) {
23256         SDValue CC = Cond.getOperand(2);
23257         ISD::CondCode NewCC =
23258           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23259                                Cond.getOperand(0).getValueType().isInteger());
23260         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23261         std::swap(LHS, RHS);
23262         TValIsAllOnes = FValIsAllOnes;
23263         FValIsAllZeros = TValIsAllZeros;
23264       }
23265     }
23266
23267     if (TValIsAllOnes || FValIsAllZeros) {
23268       SDValue Ret;
23269
23270       if (TValIsAllOnes && FValIsAllZeros)
23271         Ret = Cond;
23272       else if (TValIsAllOnes)
23273         Ret =
23274             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23275       else if (FValIsAllZeros)
23276         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23277                           DAG.getBitcast(CondVT, LHS));
23278
23279       return DAG.getBitcast(VT, Ret);
23280     }
23281   }
23282
23283   // We should generate an X86ISD::BLENDI from a vselect if its argument
23284   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23285   // constants. This specific pattern gets generated when we split a
23286   // selector for a 512 bit vector in a machine without AVX512 (but with
23287   // 256-bit vectors), during legalization:
23288   //
23289   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23290   //
23291   // Iff we find this pattern and the build_vectors are built from
23292   // constants, we translate the vselect into a shuffle_vector that we
23293   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23294   if ((N->getOpcode() == ISD::VSELECT ||
23295        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23296       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23297     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23298     if (Shuffle.getNode())
23299       return Shuffle;
23300   }
23301
23302   // If this is a *dynamic* select (non-constant condition) and we can match
23303   // this node with one of the variable blend instructions, restructure the
23304   // condition so that the blends can use the high bit of each element and use
23305   // SimplifyDemandedBits to simplify the condition operand.
23306   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23307       !DCI.isBeforeLegalize() &&
23308       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23309     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23310
23311     // Don't optimize vector selects that map to mask-registers.
23312     if (BitWidth == 1)
23313       return SDValue();
23314
23315     // We can only handle the cases where VSELECT is directly legal on the
23316     // subtarget. We custom lower VSELECT nodes with constant conditions and
23317     // this makes it hard to see whether a dynamic VSELECT will correctly
23318     // lower, so we both check the operation's status and explicitly handle the
23319     // cases where a *dynamic* blend will fail even though a constant-condition
23320     // blend could be custom lowered.
23321     // FIXME: We should find a better way to handle this class of problems.
23322     // Potentially, we should combine constant-condition vselect nodes
23323     // pre-legalization into shuffles and not mark as many types as custom
23324     // lowered.
23325     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23326       return SDValue();
23327     // FIXME: We don't support i16-element blends currently. We could and
23328     // should support them by making *all* the bits in the condition be set
23329     // rather than just the high bit and using an i8-element blend.
23330     if (VT.getScalarType() == MVT::i16)
23331       return SDValue();
23332     // Dynamic blending was only available from SSE4.1 onward.
23333     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23334       return SDValue();
23335     // Byte blends are only available in AVX2
23336     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23337         !Subtarget->hasAVX2())
23338       return SDValue();
23339
23340     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23341     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23342
23343     APInt KnownZero, KnownOne;
23344     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23345                                           DCI.isBeforeLegalizeOps());
23346     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23347         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23348                                  TLO)) {
23349       // If we changed the computation somewhere in the DAG, this change
23350       // will affect all users of Cond.
23351       // Make sure it is fine and update all the nodes so that we do not
23352       // use the generic VSELECT anymore. Otherwise, we may perform
23353       // wrong optimizations as we messed up with the actual expectation
23354       // for the vector boolean values.
23355       if (Cond != TLO.Old) {
23356         // Check all uses of that condition operand to check whether it will be
23357         // consumed by non-BLEND instructions, which may depend on all bits are
23358         // set properly.
23359         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23360              I != E; ++I)
23361           if (I->getOpcode() != ISD::VSELECT)
23362             // TODO: Add other opcodes eventually lowered into BLEND.
23363             return SDValue();
23364
23365         // Update all the users of the condition, before committing the change,
23366         // so that the VSELECT optimizations that expect the correct vector
23367         // boolean value will not be triggered.
23368         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23369              I != E; ++I)
23370           DAG.ReplaceAllUsesOfValueWith(
23371               SDValue(*I, 0),
23372               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23373                           Cond, I->getOperand(1), I->getOperand(2)));
23374         DCI.CommitTargetLoweringOpt(TLO);
23375         return SDValue();
23376       }
23377       // At this point, only Cond is changed. Change the condition
23378       // just for N to keep the opportunity to optimize all other
23379       // users their own way.
23380       DAG.ReplaceAllUsesOfValueWith(
23381           SDValue(N, 0),
23382           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23383                       TLO.New, N->getOperand(1), N->getOperand(2)));
23384       return SDValue();
23385     }
23386   }
23387
23388   return SDValue();
23389 }
23390
23391 // Check whether a boolean test is testing a boolean value generated by
23392 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23393 // code.
23394 //
23395 // Simplify the following patterns:
23396 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23397 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23398 // to (Op EFLAGS Cond)
23399 //
23400 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23401 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23402 // to (Op EFLAGS !Cond)
23403 //
23404 // where Op could be BRCOND or CMOV.
23405 //
23406 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23407   // Quit if not CMP and SUB with its value result used.
23408   if (Cmp.getOpcode() != X86ISD::CMP &&
23409       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23410       return SDValue();
23411
23412   // Quit if not used as a boolean value.
23413   if (CC != X86::COND_E && CC != X86::COND_NE)
23414     return SDValue();
23415
23416   // Check CMP operands. One of them should be 0 or 1 and the other should be
23417   // an SetCC or extended from it.
23418   SDValue Op1 = Cmp.getOperand(0);
23419   SDValue Op2 = Cmp.getOperand(1);
23420
23421   SDValue SetCC;
23422   const ConstantSDNode* C = nullptr;
23423   bool needOppositeCond = (CC == X86::COND_E);
23424   bool checkAgainstTrue = false; // Is it a comparison against 1?
23425
23426   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23427     SetCC = Op2;
23428   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23429     SetCC = Op1;
23430   else // Quit if all operands are not constants.
23431     return SDValue();
23432
23433   if (C->getZExtValue() == 1) {
23434     needOppositeCond = !needOppositeCond;
23435     checkAgainstTrue = true;
23436   } else if (C->getZExtValue() != 0)
23437     // Quit if the constant is neither 0 or 1.
23438     return SDValue();
23439
23440   bool truncatedToBoolWithAnd = false;
23441   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23442   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23443          SetCC.getOpcode() == ISD::TRUNCATE ||
23444          SetCC.getOpcode() == ISD::AND) {
23445     if (SetCC.getOpcode() == ISD::AND) {
23446       int OpIdx = -1;
23447       ConstantSDNode *CS;
23448       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23449           CS->getZExtValue() == 1)
23450         OpIdx = 1;
23451       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23452           CS->getZExtValue() == 1)
23453         OpIdx = 0;
23454       if (OpIdx == -1)
23455         break;
23456       SetCC = SetCC.getOperand(OpIdx);
23457       truncatedToBoolWithAnd = true;
23458     } else
23459       SetCC = SetCC.getOperand(0);
23460   }
23461
23462   switch (SetCC.getOpcode()) {
23463   case X86ISD::SETCC_CARRY:
23464     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23465     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23466     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23467     // truncated to i1 using 'and'.
23468     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23469       break;
23470     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23471            "Invalid use of SETCC_CARRY!");
23472     // FALL THROUGH
23473   case X86ISD::SETCC:
23474     // Set the condition code or opposite one if necessary.
23475     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23476     if (needOppositeCond)
23477       CC = X86::GetOppositeBranchCondition(CC);
23478     return SetCC.getOperand(1);
23479   case X86ISD::CMOV: {
23480     // Check whether false/true value has canonical one, i.e. 0 or 1.
23481     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23482     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23483     // Quit if true value is not a constant.
23484     if (!TVal)
23485       return SDValue();
23486     // Quit if false value is not a constant.
23487     if (!FVal) {
23488       SDValue Op = SetCC.getOperand(0);
23489       // Skip 'zext' or 'trunc' node.
23490       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23491           Op.getOpcode() == ISD::TRUNCATE)
23492         Op = Op.getOperand(0);
23493       // A special case for rdrand/rdseed, where 0 is set if false cond is
23494       // found.
23495       if ((Op.getOpcode() != X86ISD::RDRAND &&
23496            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23497         return SDValue();
23498     }
23499     // Quit if false value is not the constant 0 or 1.
23500     bool FValIsFalse = true;
23501     if (FVal && FVal->getZExtValue() != 0) {
23502       if (FVal->getZExtValue() != 1)
23503         return SDValue();
23504       // If FVal is 1, opposite cond is needed.
23505       needOppositeCond = !needOppositeCond;
23506       FValIsFalse = false;
23507     }
23508     // Quit if TVal is not the constant opposite of FVal.
23509     if (FValIsFalse && TVal->getZExtValue() != 1)
23510       return SDValue();
23511     if (!FValIsFalse && TVal->getZExtValue() != 0)
23512       return SDValue();
23513     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23514     if (needOppositeCond)
23515       CC = X86::GetOppositeBranchCondition(CC);
23516     return SetCC.getOperand(3);
23517   }
23518   }
23519
23520   return SDValue();
23521 }
23522
23523 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23524 /// Match:
23525 ///   (X86or (X86setcc) (X86setcc))
23526 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
23527 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23528                                            X86::CondCode &CC1, SDValue &Flags,
23529                                            bool &isAnd) {
23530   if (Cond->getOpcode() == X86ISD::CMP) {
23531     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23532     if (!CondOp1C || !CondOp1C->isNullValue())
23533       return false;
23534
23535     Cond = Cond->getOperand(0);
23536   }
23537
23538   isAnd = false;
23539
23540   SDValue SetCC0, SetCC1;
23541   switch (Cond->getOpcode()) {
23542   default: return false;
23543   case ISD::AND:
23544   case X86ISD::AND:
23545     isAnd = true;
23546     // fallthru
23547   case ISD::OR:
23548   case X86ISD::OR:
23549     SetCC0 = Cond->getOperand(0);
23550     SetCC1 = Cond->getOperand(1);
23551     break;
23552   };
23553
23554   // Make sure we have SETCC nodes, using the same flags value.
23555   if (SetCC0.getOpcode() != X86ISD::SETCC ||
23556       SetCC1.getOpcode() != X86ISD::SETCC ||
23557       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23558     return false;
23559
23560   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23561   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23562   Flags = SetCC0->getOperand(1);
23563   return true;
23564 }
23565
23566 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23567 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23568                                   TargetLowering::DAGCombinerInfo &DCI,
23569                                   const X86Subtarget *Subtarget) {
23570   SDLoc DL(N);
23571
23572   // If the flag operand isn't dead, don't touch this CMOV.
23573   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23574     return SDValue();
23575
23576   SDValue FalseOp = N->getOperand(0);
23577   SDValue TrueOp = N->getOperand(1);
23578   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23579   SDValue Cond = N->getOperand(3);
23580
23581   if (CC == X86::COND_E || CC == X86::COND_NE) {
23582     switch (Cond.getOpcode()) {
23583     default: break;
23584     case X86ISD::BSR:
23585     case X86ISD::BSF:
23586       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23587       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23588         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23589     }
23590   }
23591
23592   SDValue Flags;
23593
23594   Flags = checkBoolTestSetCCCombine(Cond, CC);
23595   if (Flags.getNode() &&
23596       // Extra check as FCMOV only supports a subset of X86 cond.
23597       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23598     SDValue Ops[] = { FalseOp, TrueOp,
23599                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23600     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23601   }
23602
23603   // If this is a select between two integer constants, try to do some
23604   // optimizations.  Note that the operands are ordered the opposite of SELECT
23605   // operands.
23606   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23607     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23608       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23609       // larger than FalseC (the false value).
23610       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23611         CC = X86::GetOppositeBranchCondition(CC);
23612         std::swap(TrueC, FalseC);
23613         std::swap(TrueOp, FalseOp);
23614       }
23615
23616       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23617       // This is efficient for any integer data type (including i8/i16) and
23618       // shift amount.
23619       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23620         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23621                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23622
23623         // Zero extend the condition if needed.
23624         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23625
23626         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23627         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23628                            DAG.getConstant(ShAmt, DL, MVT::i8));
23629         if (N->getNumValues() == 2)  // Dead flag value?
23630           return DCI.CombineTo(N, Cond, SDValue());
23631         return Cond;
23632       }
23633
23634       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23635       // for any integer data type, including i8/i16.
23636       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23637         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23638                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23639
23640         // Zero extend the condition if needed.
23641         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23642                            FalseC->getValueType(0), Cond);
23643         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23644                            SDValue(FalseC, 0));
23645
23646         if (N->getNumValues() == 2)  // Dead flag value?
23647           return DCI.CombineTo(N, Cond, SDValue());
23648         return Cond;
23649       }
23650
23651       // Optimize cases that will turn into an LEA instruction.  This requires
23652       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23653       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23654         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23655         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23656
23657         bool isFastMultiplier = false;
23658         if (Diff < 10) {
23659           switch ((unsigned char)Diff) {
23660           default: break;
23661           case 1:  // result = add base, cond
23662           case 2:  // result = lea base(    , cond*2)
23663           case 3:  // result = lea base(cond, cond*2)
23664           case 4:  // result = lea base(    , cond*4)
23665           case 5:  // result = lea base(cond, cond*4)
23666           case 8:  // result = lea base(    , cond*8)
23667           case 9:  // result = lea base(cond, cond*8)
23668             isFastMultiplier = true;
23669             break;
23670           }
23671         }
23672
23673         if (isFastMultiplier) {
23674           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23675           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23676                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23677           // Zero extend the condition if needed.
23678           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23679                              Cond);
23680           // Scale the condition by the difference.
23681           if (Diff != 1)
23682             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23683                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23684
23685           // Add the base if non-zero.
23686           if (FalseC->getAPIntValue() != 0)
23687             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23688                                SDValue(FalseC, 0));
23689           if (N->getNumValues() == 2)  // Dead flag value?
23690             return DCI.CombineTo(N, Cond, SDValue());
23691           return Cond;
23692         }
23693       }
23694     }
23695   }
23696
23697   // Handle these cases:
23698   //   (select (x != c), e, c) -> select (x != c), e, x),
23699   //   (select (x == c), c, e) -> select (x == c), x, e)
23700   // where the c is an integer constant, and the "select" is the combination
23701   // of CMOV and CMP.
23702   //
23703   // The rationale for this change is that the conditional-move from a constant
23704   // needs two instructions, however, conditional-move from a register needs
23705   // only one instruction.
23706   //
23707   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23708   //  some instruction-combining opportunities. This opt needs to be
23709   //  postponed as late as possible.
23710   //
23711   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23712     // the DCI.xxxx conditions are provided to postpone the optimization as
23713     // late as possible.
23714
23715     ConstantSDNode *CmpAgainst = nullptr;
23716     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23717         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23718         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23719
23720       if (CC == X86::COND_NE &&
23721           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23722         CC = X86::GetOppositeBranchCondition(CC);
23723         std::swap(TrueOp, FalseOp);
23724       }
23725
23726       if (CC == X86::COND_E &&
23727           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23728         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23729                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23730         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23731       }
23732     }
23733   }
23734
23735   // Fold and/or of setcc's to double CMOV:
23736   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23737   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23738   //
23739   // This combine lets us generate:
23740   //   cmovcc1 (jcc1 if we don't have CMOV)
23741   //   cmovcc2 (same)
23742   // instead of:
23743   //   setcc1
23744   //   setcc2
23745   //   and/or
23746   //   cmovne (jne if we don't have CMOV)
23747   // When we can't use the CMOV instruction, it might increase branch
23748   // mispredicts.
23749   // When we can use CMOV, or when there is no mispredict, this improves
23750   // throughput and reduces register pressure.
23751   //
23752   if (CC == X86::COND_NE) {
23753     SDValue Flags;
23754     X86::CondCode CC0, CC1;
23755     bool isAndSetCC;
23756     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23757       if (isAndSetCC) {
23758         std::swap(FalseOp, TrueOp);
23759         CC0 = X86::GetOppositeBranchCondition(CC0);
23760         CC1 = X86::GetOppositeBranchCondition(CC1);
23761       }
23762
23763       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23764         Flags};
23765       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23766       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23767       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23768       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23769       return CMOV;
23770     }
23771   }
23772
23773   return SDValue();
23774 }
23775
23776 /// PerformMulCombine - Optimize a single multiply with constant into two
23777 /// in order to implement it with two cheaper instructions, e.g.
23778 /// LEA + SHL, LEA + LEA.
23779 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23780                                  TargetLowering::DAGCombinerInfo &DCI) {
23781   // An imul is usually smaller than the alternative sequence.
23782   if (DAG.getMachineFunction().getFunction()->optForMinSize())
23783     return SDValue();
23784
23785   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23786     return SDValue();
23787
23788   EVT VT = N->getValueType(0);
23789   if (VT != MVT::i64 && VT != MVT::i32)
23790     return SDValue();
23791
23792   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23793   if (!C)
23794     return SDValue();
23795   uint64_t MulAmt = C->getZExtValue();
23796   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23797     return SDValue();
23798
23799   uint64_t MulAmt1 = 0;
23800   uint64_t MulAmt2 = 0;
23801   if ((MulAmt % 9) == 0) {
23802     MulAmt1 = 9;
23803     MulAmt2 = MulAmt / 9;
23804   } else if ((MulAmt % 5) == 0) {
23805     MulAmt1 = 5;
23806     MulAmt2 = MulAmt / 5;
23807   } else if ((MulAmt % 3) == 0) {
23808     MulAmt1 = 3;
23809     MulAmt2 = MulAmt / 3;
23810   }
23811   if (MulAmt2 &&
23812       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23813     SDLoc DL(N);
23814
23815     if (isPowerOf2_64(MulAmt2) &&
23816         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23817       // If second multiplifer is pow2, issue it first. We want the multiply by
23818       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23819       // is an add.
23820       std::swap(MulAmt1, MulAmt2);
23821
23822     SDValue NewMul;
23823     if (isPowerOf2_64(MulAmt1))
23824       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23825                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23826     else
23827       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23828                            DAG.getConstant(MulAmt1, DL, VT));
23829
23830     if (isPowerOf2_64(MulAmt2))
23831       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23832                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23833     else
23834       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23835                            DAG.getConstant(MulAmt2, DL, VT));
23836
23837     // Do not add new nodes to DAG combiner worklist.
23838     DCI.CombineTo(N, NewMul, false);
23839   }
23840   return SDValue();
23841 }
23842
23843 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23844   SDValue N0 = N->getOperand(0);
23845   SDValue N1 = N->getOperand(1);
23846   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23847   EVT VT = N0.getValueType();
23848
23849   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23850   // since the result of setcc_c is all zero's or all ones.
23851   if (VT.isInteger() && !VT.isVector() &&
23852       N1C && N0.getOpcode() == ISD::AND &&
23853       N0.getOperand(1).getOpcode() == ISD::Constant) {
23854     SDValue N00 = N0.getOperand(0);
23855     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23856     APInt ShAmt = N1C->getAPIntValue();
23857     Mask = Mask.shl(ShAmt);
23858     bool MaskOK = false;
23859     // We can handle cases concerning bit-widening nodes containing setcc_c if
23860     // we carefully interrogate the mask to make sure we are semantics
23861     // preserving.
23862     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
23863     // of the underlying setcc_c operation if the setcc_c was zero extended.
23864     // Consider the following example:
23865     //   zext(setcc_c)                 -> i32 0x0000FFFF
23866     //   c1                            -> i32 0x0000FFFF
23867     //   c2                            -> i32 0x00000001
23868     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
23869     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
23870     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23871       MaskOK = true;
23872     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
23873                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23874       MaskOK = true;
23875     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
23876                 N00.getOpcode() == ISD::ANY_EXTEND) &&
23877                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23878       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
23879     }
23880     if (MaskOK && Mask != 0) {
23881       SDLoc DL(N);
23882       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
23883     }
23884   }
23885
23886   // Hardware support for vector shifts is sparse which makes us scalarize the
23887   // vector operations in many cases. Also, on sandybridge ADD is faster than
23888   // shl.
23889   // (shl V, 1) -> add V,V
23890   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23891     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23892       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23893       // We shift all of the values by one. In many cases we do not have
23894       // hardware support for this operation. This is better expressed as an ADD
23895       // of two values.
23896       if (N1SplatC->getAPIntValue() == 1)
23897         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23898     }
23899
23900   return SDValue();
23901 }
23902
23903 /// \brief Returns a vector of 0s if the node in input is a vector logical
23904 /// shift by a constant amount which is known to be bigger than or equal
23905 /// to the vector element size in bits.
23906 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23907                                       const X86Subtarget *Subtarget) {
23908   EVT VT = N->getValueType(0);
23909
23910   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23911       (!Subtarget->hasInt256() ||
23912        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23913     return SDValue();
23914
23915   SDValue Amt = N->getOperand(1);
23916   SDLoc DL(N);
23917   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23918     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23919       APInt ShiftAmt = AmtSplat->getAPIntValue();
23920       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23921
23922       // SSE2/AVX2 logical shifts always return a vector of 0s
23923       // if the shift amount is bigger than or equal to
23924       // the element size. The constant shift amount will be
23925       // encoded as a 8-bit immediate.
23926       if (ShiftAmt.trunc(8).uge(MaxAmount))
23927         return getZeroVector(VT, Subtarget, DAG, DL);
23928     }
23929
23930   return SDValue();
23931 }
23932
23933 /// PerformShiftCombine - Combine shifts.
23934 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23935                                    TargetLowering::DAGCombinerInfo &DCI,
23936                                    const X86Subtarget *Subtarget) {
23937   if (N->getOpcode() == ISD::SHL)
23938     if (SDValue V = PerformSHLCombine(N, DAG))
23939       return V;
23940
23941   // Try to fold this logical shift into a zero vector.
23942   if (N->getOpcode() != ISD::SRA)
23943     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23944       return V;
23945
23946   return SDValue();
23947 }
23948
23949 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23950 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23951 // and friends.  Likewise for OR -> CMPNEQSS.
23952 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23953                             TargetLowering::DAGCombinerInfo &DCI,
23954                             const X86Subtarget *Subtarget) {
23955   unsigned opcode;
23956
23957   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23958   // we're requiring SSE2 for both.
23959   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23960     SDValue N0 = N->getOperand(0);
23961     SDValue N1 = N->getOperand(1);
23962     SDValue CMP0 = N0->getOperand(1);
23963     SDValue CMP1 = N1->getOperand(1);
23964     SDLoc DL(N);
23965
23966     // The SETCCs should both refer to the same CMP.
23967     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23968       return SDValue();
23969
23970     SDValue CMP00 = CMP0->getOperand(0);
23971     SDValue CMP01 = CMP0->getOperand(1);
23972     EVT     VT    = CMP00.getValueType();
23973
23974     if (VT == MVT::f32 || VT == MVT::f64) {
23975       bool ExpectingFlags = false;
23976       // Check for any users that want flags:
23977       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23978            !ExpectingFlags && UI != UE; ++UI)
23979         switch (UI->getOpcode()) {
23980         default:
23981         case ISD::BR_CC:
23982         case ISD::BRCOND:
23983         case ISD::SELECT:
23984           ExpectingFlags = true;
23985           break;
23986         case ISD::CopyToReg:
23987         case ISD::SIGN_EXTEND:
23988         case ISD::ZERO_EXTEND:
23989         case ISD::ANY_EXTEND:
23990           break;
23991         }
23992
23993       if (!ExpectingFlags) {
23994         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23995         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23996
23997         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23998           X86::CondCode tmp = cc0;
23999           cc0 = cc1;
24000           cc1 = tmp;
24001         }
24002
24003         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
24004             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24005           // FIXME: need symbolic constants for these magic numbers.
24006           // See X86ATTInstPrinter.cpp:printSSECC().
24007           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24008           if (Subtarget->hasAVX512()) {
24009             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24010                                          CMP01,
24011                                          DAG.getConstant(x86cc, DL, MVT::i8));
24012             if (N->getValueType(0) != MVT::i1)
24013               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24014                                  FSetCC);
24015             return FSetCC;
24016           }
24017           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24018                                               CMP00.getValueType(), CMP00, CMP01,
24019                                               DAG.getConstant(x86cc, DL,
24020                                                               MVT::i8));
24021
24022           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24023           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24024
24025           if (is64BitFP && !Subtarget->is64Bit()) {
24026             // On a 32-bit target, we cannot bitcast the 64-bit float to a
24027             // 64-bit integer, since that's not a legal type. Since
24028             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24029             // bits, but can do this little dance to extract the lowest 32 bits
24030             // and work with those going forward.
24031             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24032                                            OnesOrZeroesF);
24033             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
24034             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24035                                         Vector32, DAG.getIntPtrConstant(0, DL));
24036             IntVT = MVT::i32;
24037           }
24038
24039           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
24040           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24041                                       DAG.getConstant(1, DL, IntVT));
24042           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
24043                                               ANDed);
24044           return OneBitOfTruth;
24045         }
24046       }
24047     }
24048   }
24049   return SDValue();
24050 }
24051
24052 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24053 /// so it can be folded inside ANDNP.
24054 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24055   EVT VT = N->getValueType(0);
24056
24057   // Match direct AllOnes for 128 and 256-bit vectors
24058   if (ISD::isBuildVectorAllOnes(N))
24059     return true;
24060
24061   // Look through a bit convert.
24062   if (N->getOpcode() == ISD::BITCAST)
24063     N = N->getOperand(0).getNode();
24064
24065   // Sometimes the operand may come from a insert_subvector building a 256-bit
24066   // allones vector
24067   if (VT.is256BitVector() &&
24068       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24069     SDValue V1 = N->getOperand(0);
24070     SDValue V2 = N->getOperand(1);
24071
24072     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24073         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24074         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24075         ISD::isBuildVectorAllOnes(V2.getNode()))
24076       return true;
24077   }
24078
24079   return false;
24080 }
24081
24082 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24083 // register. In most cases we actually compare or select YMM-sized registers
24084 // and mixing the two types creates horrible code. This method optimizes
24085 // some of the transition sequences.
24086 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24087                                  TargetLowering::DAGCombinerInfo &DCI,
24088                                  const X86Subtarget *Subtarget) {
24089   EVT VT = N->getValueType(0);
24090   if (!VT.is256BitVector())
24091     return SDValue();
24092
24093   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24094           N->getOpcode() == ISD::ZERO_EXTEND ||
24095           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24096
24097   SDValue Narrow = N->getOperand(0);
24098   EVT NarrowVT = Narrow->getValueType(0);
24099   if (!NarrowVT.is128BitVector())
24100     return SDValue();
24101
24102   if (Narrow->getOpcode() != ISD::XOR &&
24103       Narrow->getOpcode() != ISD::AND &&
24104       Narrow->getOpcode() != ISD::OR)
24105     return SDValue();
24106
24107   SDValue N0  = Narrow->getOperand(0);
24108   SDValue N1  = Narrow->getOperand(1);
24109   SDLoc DL(Narrow);
24110
24111   // The Left side has to be a trunc.
24112   if (N0.getOpcode() != ISD::TRUNCATE)
24113     return SDValue();
24114
24115   // The type of the truncated inputs.
24116   EVT WideVT = N0->getOperand(0)->getValueType(0);
24117   if (WideVT != VT)
24118     return SDValue();
24119
24120   // The right side has to be a 'trunc' or a constant vector.
24121   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24122   ConstantSDNode *RHSConstSplat = nullptr;
24123   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24124     RHSConstSplat = RHSBV->getConstantSplatNode();
24125   if (!RHSTrunc && !RHSConstSplat)
24126     return SDValue();
24127
24128   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24129
24130   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24131     return SDValue();
24132
24133   // Set N0 and N1 to hold the inputs to the new wide operation.
24134   N0 = N0->getOperand(0);
24135   if (RHSConstSplat) {
24136     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24137                      SDValue(RHSConstSplat, 0));
24138     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24139     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24140   } else if (RHSTrunc) {
24141     N1 = N1->getOperand(0);
24142   }
24143
24144   // Generate the wide operation.
24145   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24146   unsigned Opcode = N->getOpcode();
24147   switch (Opcode) {
24148   case ISD::ANY_EXTEND:
24149     return Op;
24150   case ISD::ZERO_EXTEND: {
24151     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24152     APInt Mask = APInt::getAllOnesValue(InBits);
24153     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24154     return DAG.getNode(ISD::AND, DL, VT,
24155                        Op, DAG.getConstant(Mask, DL, VT));
24156   }
24157   case ISD::SIGN_EXTEND:
24158     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24159                        Op, DAG.getValueType(NarrowVT));
24160   default:
24161     llvm_unreachable("Unexpected opcode");
24162   }
24163 }
24164
24165 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24166                                  TargetLowering::DAGCombinerInfo &DCI,
24167                                  const X86Subtarget *Subtarget) {
24168   SDValue N0 = N->getOperand(0);
24169   SDValue N1 = N->getOperand(1);
24170   SDLoc DL(N);
24171
24172   // A vector zext_in_reg may be represented as a shuffle,
24173   // feeding into a bitcast (this represents anyext) feeding into
24174   // an and with a mask.
24175   // We'd like to try to combine that into a shuffle with zero
24176   // plus a bitcast, removing the and.
24177   if (N0.getOpcode() != ISD::BITCAST ||
24178       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24179     return SDValue();
24180
24181   // The other side of the AND should be a splat of 2^C, where C
24182   // is the number of bits in the source type.
24183   if (N1.getOpcode() == ISD::BITCAST)
24184     N1 = N1.getOperand(0);
24185   if (N1.getOpcode() != ISD::BUILD_VECTOR)
24186     return SDValue();
24187   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24188
24189   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24190   EVT SrcType = Shuffle->getValueType(0);
24191
24192   // We expect a single-source shuffle
24193   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24194     return SDValue();
24195
24196   unsigned SrcSize = SrcType.getScalarSizeInBits();
24197
24198   APInt SplatValue, SplatUndef;
24199   unsigned SplatBitSize;
24200   bool HasAnyUndefs;
24201   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24202                                 SplatBitSize, HasAnyUndefs))
24203     return SDValue();
24204
24205   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24206   // Make sure the splat matches the mask we expect
24207   if (SplatBitSize > ResSize ||
24208       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24209     return SDValue();
24210
24211   // Make sure the input and output size make sense
24212   if (SrcSize >= ResSize || ResSize % SrcSize)
24213     return SDValue();
24214
24215   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24216   // The number of u's between each two values depends on the ratio between
24217   // the source and dest type.
24218   unsigned ZextRatio = ResSize / SrcSize;
24219   bool IsZext = true;
24220   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24221     if (i % ZextRatio) {
24222       if (Shuffle->getMaskElt(i) > 0) {
24223         // Expected undef
24224         IsZext = false;
24225         break;
24226       }
24227     } else {
24228       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24229         // Expected element number
24230         IsZext = false;
24231         break;
24232       }
24233     }
24234   }
24235
24236   if (!IsZext)
24237     return SDValue();
24238
24239   // Ok, perform the transformation - replace the shuffle with
24240   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24241   // (instead of undef) where the k elements come from the zero vector.
24242   SmallVector<int, 8> Mask;
24243   unsigned NumElems = SrcType.getVectorNumElements();
24244   for (unsigned i = 0; i < NumElems; ++i)
24245     if (i % ZextRatio)
24246       Mask.push_back(NumElems);
24247     else
24248       Mask.push_back(i / ZextRatio);
24249
24250   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24251     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24252   return DAG.getBitcast(N0.getValueType(), NewShuffle);
24253 }
24254
24255 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24256                                  TargetLowering::DAGCombinerInfo &DCI,
24257                                  const X86Subtarget *Subtarget) {
24258   if (DCI.isBeforeLegalizeOps())
24259     return SDValue();
24260
24261   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24262     return Zext;
24263
24264   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24265     return R;
24266
24267   EVT VT = N->getValueType(0);
24268   SDValue N0 = N->getOperand(0);
24269   SDValue N1 = N->getOperand(1);
24270   SDLoc DL(N);
24271
24272   // Create BEXTR instructions
24273   // BEXTR is ((X >> imm) & (2**size-1))
24274   if (VT == MVT::i32 || VT == MVT::i64) {
24275     // Check for BEXTR.
24276     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24277         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24278       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24279       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24280       if (MaskNode && ShiftNode) {
24281         uint64_t Mask = MaskNode->getZExtValue();
24282         uint64_t Shift = ShiftNode->getZExtValue();
24283         if (isMask_64(Mask)) {
24284           uint64_t MaskSize = countPopulation(Mask);
24285           if (Shift + MaskSize <= VT.getSizeInBits())
24286             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24287                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24288                                                VT));
24289         }
24290       }
24291     } // BEXTR
24292
24293     return SDValue();
24294   }
24295
24296   // Want to form ANDNP nodes:
24297   // 1) In the hopes of then easily combining them with OR and AND nodes
24298   //    to form PBLEND/PSIGN.
24299   // 2) To match ANDN packed intrinsics
24300   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24301     return SDValue();
24302
24303   // Check LHS for vnot
24304   if (N0.getOpcode() == ISD::XOR &&
24305       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24306       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24307     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24308
24309   // Check RHS for vnot
24310   if (N1.getOpcode() == ISD::XOR &&
24311       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24312       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24313     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24314
24315   return SDValue();
24316 }
24317
24318 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24319                                 TargetLowering::DAGCombinerInfo &DCI,
24320                                 const X86Subtarget *Subtarget) {
24321   if (DCI.isBeforeLegalizeOps())
24322     return SDValue();
24323
24324   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24325     return R;
24326
24327   SDValue N0 = N->getOperand(0);
24328   SDValue N1 = N->getOperand(1);
24329   EVT VT = N->getValueType(0);
24330
24331   // look for psign/blend
24332   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24333     if (!Subtarget->hasSSSE3() ||
24334         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24335       return SDValue();
24336
24337     // Canonicalize pandn to RHS
24338     if (N0.getOpcode() == X86ISD::ANDNP)
24339       std::swap(N0, N1);
24340     // or (and (m, y), (pandn m, x))
24341     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24342       SDValue Mask = N1.getOperand(0);
24343       SDValue X    = N1.getOperand(1);
24344       SDValue Y;
24345       if (N0.getOperand(0) == Mask)
24346         Y = N0.getOperand(1);
24347       if (N0.getOperand(1) == Mask)
24348         Y = N0.getOperand(0);
24349
24350       // Check to see if the mask appeared in both the AND and ANDNP and
24351       if (!Y.getNode())
24352         return SDValue();
24353
24354       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24355       // Look through mask bitcast.
24356       if (Mask.getOpcode() == ISD::BITCAST)
24357         Mask = Mask.getOperand(0);
24358       if (X.getOpcode() == ISD::BITCAST)
24359         X = X.getOperand(0);
24360       if (Y.getOpcode() == ISD::BITCAST)
24361         Y = Y.getOperand(0);
24362
24363       EVT MaskVT = Mask.getValueType();
24364
24365       // Validate that the Mask operand is a vector sra node.
24366       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24367       // there is no psrai.b
24368       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24369       unsigned SraAmt = ~0;
24370       if (Mask.getOpcode() == ISD::SRA) {
24371         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24372           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24373             SraAmt = AmtConst->getZExtValue();
24374       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24375         SDValue SraC = Mask.getOperand(1);
24376         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24377       }
24378       if ((SraAmt + 1) != EltBits)
24379         return SDValue();
24380
24381       SDLoc DL(N);
24382
24383       // Now we know we at least have a plendvb with the mask val.  See if
24384       // we can form a psignb/w/d.
24385       // psign = x.type == y.type == mask.type && y = sub(0, x);
24386       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24387           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24388           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24389         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24390                "Unsupported VT for PSIGN");
24391         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24392         return DAG.getBitcast(VT, Mask);
24393       }
24394       // PBLENDVB only available on SSE 4.1
24395       if (!Subtarget->hasSSE41())
24396         return SDValue();
24397
24398       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24399
24400       X = DAG.getBitcast(BlendVT, X);
24401       Y = DAG.getBitcast(BlendVT, Y);
24402       Mask = DAG.getBitcast(BlendVT, Mask);
24403       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24404       return DAG.getBitcast(VT, Mask);
24405     }
24406   }
24407
24408   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24409     return SDValue();
24410
24411   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24412   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24413
24414   // SHLD/SHRD instructions have lower register pressure, but on some
24415   // platforms they have higher latency than the equivalent
24416   // series of shifts/or that would otherwise be generated.
24417   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24418   // have higher latencies and we are not optimizing for size.
24419   if (!OptForSize && Subtarget->isSHLDSlow())
24420     return SDValue();
24421
24422   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24423     std::swap(N0, N1);
24424   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24425     return SDValue();
24426   if (!N0.hasOneUse() || !N1.hasOneUse())
24427     return SDValue();
24428
24429   SDValue ShAmt0 = N0.getOperand(1);
24430   if (ShAmt0.getValueType() != MVT::i8)
24431     return SDValue();
24432   SDValue ShAmt1 = N1.getOperand(1);
24433   if (ShAmt1.getValueType() != MVT::i8)
24434     return SDValue();
24435   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24436     ShAmt0 = ShAmt0.getOperand(0);
24437   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24438     ShAmt1 = ShAmt1.getOperand(0);
24439
24440   SDLoc DL(N);
24441   unsigned Opc = X86ISD::SHLD;
24442   SDValue Op0 = N0.getOperand(0);
24443   SDValue Op1 = N1.getOperand(0);
24444   if (ShAmt0.getOpcode() == ISD::SUB) {
24445     Opc = X86ISD::SHRD;
24446     std::swap(Op0, Op1);
24447     std::swap(ShAmt0, ShAmt1);
24448   }
24449
24450   unsigned Bits = VT.getSizeInBits();
24451   if (ShAmt1.getOpcode() == ISD::SUB) {
24452     SDValue Sum = ShAmt1.getOperand(0);
24453     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24454       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24455       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24456         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24457       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24458         return DAG.getNode(Opc, DL, VT,
24459                            Op0, Op1,
24460                            DAG.getNode(ISD::TRUNCATE, DL,
24461                                        MVT::i8, ShAmt0));
24462     }
24463   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24464     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24465     if (ShAmt0C &&
24466         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24467       return DAG.getNode(Opc, DL, VT,
24468                          N0.getOperand(0), N1.getOperand(0),
24469                          DAG.getNode(ISD::TRUNCATE, DL,
24470                                        MVT::i8, ShAmt0));
24471   }
24472
24473   return SDValue();
24474 }
24475
24476 // Generate NEG and CMOV for integer abs.
24477 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24478   EVT VT = N->getValueType(0);
24479
24480   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24481   // 8-bit integer abs to NEG and CMOV.
24482   if (VT.isInteger() && VT.getSizeInBits() == 8)
24483     return SDValue();
24484
24485   SDValue N0 = N->getOperand(0);
24486   SDValue N1 = N->getOperand(1);
24487   SDLoc DL(N);
24488
24489   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24490   // and change it to SUB and CMOV.
24491   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24492       N0.getOpcode() == ISD::ADD &&
24493       N0.getOperand(1) == N1 &&
24494       N1.getOpcode() == ISD::SRA &&
24495       N1.getOperand(0) == N0.getOperand(0))
24496     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24497       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24498         // Generate SUB & CMOV.
24499         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24500                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24501
24502         SDValue Ops[] = { N0.getOperand(0), Neg,
24503                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24504                           SDValue(Neg.getNode(), 1) };
24505         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24506       }
24507   return SDValue();
24508 }
24509
24510 // Try to turn tests against the signbit in the form of:
24511 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24512 // into:
24513 //   SETGT(X, -1)
24514 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24515   // This is only worth doing if the output type is i8.
24516   if (N->getValueType(0) != MVT::i8)
24517     return SDValue();
24518
24519   SDValue N0 = N->getOperand(0);
24520   SDValue N1 = N->getOperand(1);
24521
24522   // We should be performing an xor against a truncated shift.
24523   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24524     return SDValue();
24525
24526   // Make sure we are performing an xor against one.
24527   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24528     return SDValue();
24529
24530   // SetCC on x86 zero extends so only act on this if it's a logical shift.
24531   SDValue Shift = N0.getOperand(0);
24532   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24533     return SDValue();
24534
24535   // Make sure we are truncating from one of i16, i32 or i64.
24536   EVT ShiftTy = Shift.getValueType();
24537   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24538     return SDValue();
24539
24540   // Make sure the shift amount extracts the sign bit.
24541   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24542       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24543     return SDValue();
24544
24545   // Create a greater-than comparison against -1.
24546   // N.B. Using SETGE against 0 works but we want a canonical looking
24547   // comparison, using SETGT matches up with what TranslateX86CC.
24548   SDLoc DL(N);
24549   SDValue ShiftOp = Shift.getOperand(0);
24550   EVT ShiftOpTy = ShiftOp.getValueType();
24551   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24552                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24553   return Cond;
24554 }
24555
24556 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24557                                  TargetLowering::DAGCombinerInfo &DCI,
24558                                  const X86Subtarget *Subtarget) {
24559   if (DCI.isBeforeLegalizeOps())
24560     return SDValue();
24561
24562   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24563     return RV;
24564
24565   if (Subtarget->hasCMov())
24566     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24567       return RV;
24568
24569   return SDValue();
24570 }
24571
24572 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24573 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24574                                   TargetLowering::DAGCombinerInfo &DCI,
24575                                   const X86Subtarget *Subtarget) {
24576   LoadSDNode *Ld = cast<LoadSDNode>(N);
24577   EVT RegVT = Ld->getValueType(0);
24578   EVT MemVT = Ld->getMemoryVT();
24579   SDLoc dl(Ld);
24580   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24581
24582   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24583   // into two 16-byte operations.
24584   ISD::LoadExtType Ext = Ld->getExtensionType();
24585   bool Fast;
24586   unsigned AddressSpace = Ld->getAddressSpace();
24587   unsigned Alignment = Ld->getAlignment();
24588   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24589       Ext == ISD::NON_EXTLOAD &&
24590       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24591                              AddressSpace, Alignment, &Fast) && !Fast) {
24592     unsigned NumElems = RegVT.getVectorNumElements();
24593     if (NumElems < 2)
24594       return SDValue();
24595
24596     SDValue Ptr = Ld->getBasePtr();
24597     SDValue Increment =
24598         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24599
24600     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24601                                   NumElems/2);
24602     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24603                                 Ld->getPointerInfo(), Ld->isVolatile(),
24604                                 Ld->isNonTemporal(), Ld->isInvariant(),
24605                                 Alignment);
24606     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24607     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24608                                 Ld->getPointerInfo(), Ld->isVolatile(),
24609                                 Ld->isNonTemporal(), Ld->isInvariant(),
24610                                 std::min(16U, Alignment));
24611     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24612                              Load1.getValue(1),
24613                              Load2.getValue(1));
24614
24615     SDValue NewVec = DAG.getUNDEF(RegVT);
24616     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24617     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24618     return DCI.CombineTo(N, NewVec, TF, true);
24619   }
24620
24621   return SDValue();
24622 }
24623
24624 /// PerformMLOADCombine - Resolve extending loads
24625 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24626                                    TargetLowering::DAGCombinerInfo &DCI,
24627                                    const X86Subtarget *Subtarget) {
24628   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24629   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24630     return SDValue();
24631
24632   EVT VT = Mld->getValueType(0);
24633   unsigned NumElems = VT.getVectorNumElements();
24634   EVT LdVT = Mld->getMemoryVT();
24635   SDLoc dl(Mld);
24636
24637   assert(LdVT != VT && "Cannot extend to the same type");
24638   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24639   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24640   // From, To sizes and ElemCount must be pow of two
24641   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24642     "Unexpected size for extending masked load");
24643
24644   unsigned SizeRatio  = ToSz / FromSz;
24645   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24646
24647   // Create a type on which we perform the shuffle
24648   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24649           LdVT.getScalarType(), NumElems*SizeRatio);
24650   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24651
24652   // Convert Src0 value
24653   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24654   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24655     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24656     for (unsigned i = 0; i != NumElems; ++i)
24657       ShuffleVec[i] = i * SizeRatio;
24658
24659     // Can't shuffle using an illegal type.
24660     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24661             && "WideVecVT should be legal");
24662     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24663                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24664   }
24665   // Prepare the new mask
24666   SDValue NewMask;
24667   SDValue Mask = Mld->getMask();
24668   if (Mask.getValueType() == VT) {
24669     // Mask and original value have the same type
24670     NewMask = DAG.getBitcast(WideVecVT, Mask);
24671     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24672     for (unsigned i = 0; i != NumElems; ++i)
24673       ShuffleVec[i] = i * SizeRatio;
24674     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24675       ShuffleVec[i] = NumElems*SizeRatio;
24676     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24677                                    DAG.getConstant(0, dl, WideVecVT),
24678                                    &ShuffleVec[0]);
24679   }
24680   else {
24681     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24682     unsigned WidenNumElts = NumElems*SizeRatio;
24683     unsigned MaskNumElts = VT.getVectorNumElements();
24684     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24685                                      WidenNumElts);
24686
24687     unsigned NumConcat = WidenNumElts / MaskNumElts;
24688     SmallVector<SDValue, 16> Ops(NumConcat);
24689     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24690     Ops[0] = Mask;
24691     for (unsigned i = 1; i != NumConcat; ++i)
24692       Ops[i] = ZeroVal;
24693
24694     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24695   }
24696
24697   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24698                                      Mld->getBasePtr(), NewMask, WideSrc0,
24699                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24700                                      ISD::NON_EXTLOAD);
24701   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24702   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24703
24704 }
24705 /// PerformMSTORECombine - Resolve truncating stores
24706 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24707                                     const X86Subtarget *Subtarget) {
24708   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24709   if (!Mst->isTruncatingStore())
24710     return SDValue();
24711
24712   EVT VT = Mst->getValue().getValueType();
24713   unsigned NumElems = VT.getVectorNumElements();
24714   EVT StVT = Mst->getMemoryVT();
24715   SDLoc dl(Mst);
24716
24717   assert(StVT != VT && "Cannot truncate to the same type");
24718   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24719   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24720
24721   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24722
24723   // The truncating store is legal in some cases. For example
24724   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24725   // are designated for truncate store.
24726   // In this case we don't need any further transformations.
24727   if (TLI.isTruncStoreLegal(VT, StVT))
24728     return SDValue();
24729
24730   // From, To sizes and ElemCount must be pow of two
24731   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24732     "Unexpected size for truncating masked store");
24733   // We are going to use the original vector elt for storing.
24734   // Accumulated smaller vector elements must be a multiple of the store size.
24735   assert (((NumElems * FromSz) % ToSz) == 0 &&
24736           "Unexpected ratio for truncating masked store");
24737
24738   unsigned SizeRatio  = FromSz / ToSz;
24739   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24740
24741   // Create a type on which we perform the shuffle
24742   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24743           StVT.getScalarType(), NumElems*SizeRatio);
24744
24745   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24746
24747   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24748   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24749   for (unsigned i = 0; i != NumElems; ++i)
24750     ShuffleVec[i] = i * SizeRatio;
24751
24752   // Can't shuffle using an illegal type.
24753   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24754           && "WideVecVT should be legal");
24755
24756   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24757                                         DAG.getUNDEF(WideVecVT),
24758                                         &ShuffleVec[0]);
24759
24760   SDValue NewMask;
24761   SDValue Mask = Mst->getMask();
24762   if (Mask.getValueType() == VT) {
24763     // Mask and original value have the same type
24764     NewMask = DAG.getBitcast(WideVecVT, Mask);
24765     for (unsigned i = 0; i != NumElems; ++i)
24766       ShuffleVec[i] = i * SizeRatio;
24767     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24768       ShuffleVec[i] = NumElems*SizeRatio;
24769     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24770                                    DAG.getConstant(0, dl, WideVecVT),
24771                                    &ShuffleVec[0]);
24772   }
24773   else {
24774     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24775     unsigned WidenNumElts = NumElems*SizeRatio;
24776     unsigned MaskNumElts = VT.getVectorNumElements();
24777     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24778                                      WidenNumElts);
24779
24780     unsigned NumConcat = WidenNumElts / MaskNumElts;
24781     SmallVector<SDValue, 16> Ops(NumConcat);
24782     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24783     Ops[0] = Mask;
24784     for (unsigned i = 1; i != NumConcat; ++i)
24785       Ops[i] = ZeroVal;
24786
24787     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24788   }
24789
24790   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24791                             NewMask, StVT, Mst->getMemOperand(), false);
24792 }
24793 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24794 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24795                                    const X86Subtarget *Subtarget) {
24796   StoreSDNode *St = cast<StoreSDNode>(N);
24797   EVT VT = St->getValue().getValueType();
24798   EVT StVT = St->getMemoryVT();
24799   SDLoc dl(St);
24800   SDValue StoredVal = St->getOperand(1);
24801   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24802
24803   // If we are saving a concatenation of two XMM registers and 32-byte stores
24804   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24805   bool Fast;
24806   unsigned AddressSpace = St->getAddressSpace();
24807   unsigned Alignment = St->getAlignment();
24808   if (VT.is256BitVector() && StVT == VT &&
24809       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24810                              AddressSpace, Alignment, &Fast) && !Fast) {
24811     unsigned NumElems = VT.getVectorNumElements();
24812     if (NumElems < 2)
24813       return SDValue();
24814
24815     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24816     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24817
24818     SDValue Stride =
24819         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24820     SDValue Ptr0 = St->getBasePtr();
24821     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24822
24823     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24824                                 St->getPointerInfo(), St->isVolatile(),
24825                                 St->isNonTemporal(), Alignment);
24826     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24827                                 St->getPointerInfo(), St->isVolatile(),
24828                                 St->isNonTemporal(),
24829                                 std::min(16U, Alignment));
24830     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24831   }
24832
24833   // Optimize trunc store (of multiple scalars) to shuffle and store.
24834   // First, pack all of the elements in one place. Next, store to memory
24835   // in fewer chunks.
24836   if (St->isTruncatingStore() && VT.isVector()) {
24837     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24838     unsigned NumElems = VT.getVectorNumElements();
24839     assert(StVT != VT && "Cannot truncate to the same type");
24840     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24841     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24842
24843     // The truncating store is legal in some cases. For example
24844     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24845     // are designated for truncate store.
24846     // In this case we don't need any further transformations.
24847     if (TLI.isTruncStoreLegal(VT, StVT))
24848       return SDValue();
24849
24850     // From, To sizes and ElemCount must be pow of two
24851     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24852     // We are going to use the original vector elt for storing.
24853     // Accumulated smaller vector elements must be a multiple of the store size.
24854     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24855
24856     unsigned SizeRatio  = FromSz / ToSz;
24857
24858     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24859
24860     // Create a type on which we perform the shuffle
24861     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24862             StVT.getScalarType(), NumElems*SizeRatio);
24863
24864     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24865
24866     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24867     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24868     for (unsigned i = 0; i != NumElems; ++i)
24869       ShuffleVec[i] = i * SizeRatio;
24870
24871     // Can't shuffle using an illegal type.
24872     if (!TLI.isTypeLegal(WideVecVT))
24873       return SDValue();
24874
24875     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24876                                          DAG.getUNDEF(WideVecVT),
24877                                          &ShuffleVec[0]);
24878     // At this point all of the data is stored at the bottom of the
24879     // register. We now need to save it to mem.
24880
24881     // Find the largest store unit
24882     MVT StoreType = MVT::i8;
24883     for (MVT Tp : MVT::integer_valuetypes()) {
24884       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24885         StoreType = Tp;
24886     }
24887
24888     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24889     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24890         (64 <= NumElems * ToSz))
24891       StoreType = MVT::f64;
24892
24893     // Bitcast the original vector into a vector of store-size units
24894     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24895             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24896     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24897     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24898     SmallVector<SDValue, 8> Chains;
24899     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24900                                         TLI.getPointerTy(DAG.getDataLayout()));
24901     SDValue Ptr = St->getBasePtr();
24902
24903     // Perform one or more big stores into memory.
24904     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24905       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24906                                    StoreType, ShuffWide,
24907                                    DAG.getIntPtrConstant(i, dl));
24908       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24909                                 St->getPointerInfo(), St->isVolatile(),
24910                                 St->isNonTemporal(), St->getAlignment());
24911       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24912       Chains.push_back(Ch);
24913     }
24914
24915     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24916   }
24917
24918   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24919   // the FP state in cases where an emms may be missing.
24920   // A preferable solution to the general problem is to figure out the right
24921   // places to insert EMMS.  This qualifies as a quick hack.
24922
24923   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24924   if (VT.getSizeInBits() != 64)
24925     return SDValue();
24926
24927   const Function *F = DAG.getMachineFunction().getFunction();
24928   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24929   bool F64IsLegal =
24930       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24931   if ((VT.isVector() ||
24932        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24933       isa<LoadSDNode>(St->getValue()) &&
24934       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24935       St->getChain().hasOneUse() && !St->isVolatile()) {
24936     SDNode* LdVal = St->getValue().getNode();
24937     LoadSDNode *Ld = nullptr;
24938     int TokenFactorIndex = -1;
24939     SmallVector<SDValue, 8> Ops;
24940     SDNode* ChainVal = St->getChain().getNode();
24941     // Must be a store of a load.  We currently handle two cases:  the load
24942     // is a direct child, and it's under an intervening TokenFactor.  It is
24943     // possible to dig deeper under nested TokenFactors.
24944     if (ChainVal == LdVal)
24945       Ld = cast<LoadSDNode>(St->getChain());
24946     else if (St->getValue().hasOneUse() &&
24947              ChainVal->getOpcode() == ISD::TokenFactor) {
24948       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24949         if (ChainVal->getOperand(i).getNode() == LdVal) {
24950           TokenFactorIndex = i;
24951           Ld = cast<LoadSDNode>(St->getValue());
24952         } else
24953           Ops.push_back(ChainVal->getOperand(i));
24954       }
24955     }
24956
24957     if (!Ld || !ISD::isNormalLoad(Ld))
24958       return SDValue();
24959
24960     // If this is not the MMX case, i.e. we are just turning i64 load/store
24961     // into f64 load/store, avoid the transformation if there are multiple
24962     // uses of the loaded value.
24963     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24964       return SDValue();
24965
24966     SDLoc LdDL(Ld);
24967     SDLoc StDL(N);
24968     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24969     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24970     // pair instead.
24971     if (Subtarget->is64Bit() || F64IsLegal) {
24972       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24973       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24974                                   Ld->getPointerInfo(), Ld->isVolatile(),
24975                                   Ld->isNonTemporal(), Ld->isInvariant(),
24976                                   Ld->getAlignment());
24977       SDValue NewChain = NewLd.getValue(1);
24978       if (TokenFactorIndex != -1) {
24979         Ops.push_back(NewChain);
24980         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24981       }
24982       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24983                           St->getPointerInfo(),
24984                           St->isVolatile(), St->isNonTemporal(),
24985                           St->getAlignment());
24986     }
24987
24988     // Otherwise, lower to two pairs of 32-bit loads / stores.
24989     SDValue LoAddr = Ld->getBasePtr();
24990     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24991                                  DAG.getConstant(4, LdDL, MVT::i32));
24992
24993     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24994                                Ld->getPointerInfo(),
24995                                Ld->isVolatile(), Ld->isNonTemporal(),
24996                                Ld->isInvariant(), Ld->getAlignment());
24997     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24998                                Ld->getPointerInfo().getWithOffset(4),
24999                                Ld->isVolatile(), Ld->isNonTemporal(),
25000                                Ld->isInvariant(),
25001                                MinAlign(Ld->getAlignment(), 4));
25002
25003     SDValue NewChain = LoLd.getValue(1);
25004     if (TokenFactorIndex != -1) {
25005       Ops.push_back(LoLd);
25006       Ops.push_back(HiLd);
25007       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25008     }
25009
25010     LoAddr = St->getBasePtr();
25011     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
25012                          DAG.getConstant(4, StDL, MVT::i32));
25013
25014     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
25015                                 St->getPointerInfo(),
25016                                 St->isVolatile(), St->isNonTemporal(),
25017                                 St->getAlignment());
25018     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
25019                                 St->getPointerInfo().getWithOffset(4),
25020                                 St->isVolatile(),
25021                                 St->isNonTemporal(),
25022                                 MinAlign(St->getAlignment(), 4));
25023     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
25024   }
25025
25026   // This is similar to the above case, but here we handle a scalar 64-bit
25027   // integer store that is extracted from a vector on a 32-bit target.
25028   // If we have SSE2, then we can treat it like a floating-point double
25029   // to get past legalization. The execution dependencies fixup pass will
25030   // choose the optimal machine instruction for the store if this really is
25031   // an integer or v2f32 rather than an f64.
25032   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
25033       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
25034     SDValue OldExtract = St->getOperand(1);
25035     SDValue ExtOp0 = OldExtract.getOperand(0);
25036     unsigned VecSize = ExtOp0.getValueSizeInBits();
25037     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
25038     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
25039     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
25040                                      BitCast, OldExtract.getOperand(1));
25041     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
25042                         St->getPointerInfo(), St->isVolatile(),
25043                         St->isNonTemporal(), St->getAlignment());
25044   }
25045
25046   return SDValue();
25047 }
25048
25049 /// Return 'true' if this vector operation is "horizontal"
25050 /// and return the operands for the horizontal operation in LHS and RHS.  A
25051 /// horizontal operation performs the binary operation on successive elements
25052 /// of its first operand, then on successive elements of its second operand,
25053 /// returning the resulting values in a vector.  For example, if
25054 ///   A = < float a0, float a1, float a2, float a3 >
25055 /// and
25056 ///   B = < float b0, float b1, float b2, float b3 >
25057 /// then the result of doing a horizontal operation on A and B is
25058 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25059 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25060 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25061 /// set to A, RHS to B, and the routine returns 'true'.
25062 /// Note that the binary operation should have the property that if one of the
25063 /// operands is UNDEF then the result is UNDEF.
25064 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25065   // Look for the following pattern: if
25066   //   A = < float a0, float a1, float a2, float a3 >
25067   //   B = < float b0, float b1, float b2, float b3 >
25068   // and
25069   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25070   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25071   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25072   // which is A horizontal-op B.
25073
25074   // At least one of the operands should be a vector shuffle.
25075   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25076       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25077     return false;
25078
25079   MVT VT = LHS.getSimpleValueType();
25080
25081   assert((VT.is128BitVector() || VT.is256BitVector()) &&
25082          "Unsupported vector type for horizontal add/sub");
25083
25084   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25085   // operate independently on 128-bit lanes.
25086   unsigned NumElts = VT.getVectorNumElements();
25087   unsigned NumLanes = VT.getSizeInBits()/128;
25088   unsigned NumLaneElts = NumElts / NumLanes;
25089   assert((NumLaneElts % 2 == 0) &&
25090          "Vector type should have an even number of elements in each lane");
25091   unsigned HalfLaneElts = NumLaneElts/2;
25092
25093   // View LHS in the form
25094   //   LHS = VECTOR_SHUFFLE A, B, LMask
25095   // If LHS is not a shuffle then pretend it is the shuffle
25096   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25097   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25098   // type VT.
25099   SDValue A, B;
25100   SmallVector<int, 16> LMask(NumElts);
25101   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25102     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25103       A = LHS.getOperand(0);
25104     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25105       B = LHS.getOperand(1);
25106     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25107     std::copy(Mask.begin(), Mask.end(), LMask.begin());
25108   } else {
25109     if (LHS.getOpcode() != ISD::UNDEF)
25110       A = LHS;
25111     for (unsigned i = 0; i != NumElts; ++i)
25112       LMask[i] = i;
25113   }
25114
25115   // Likewise, view RHS in the form
25116   //   RHS = VECTOR_SHUFFLE C, D, RMask
25117   SDValue C, D;
25118   SmallVector<int, 16> RMask(NumElts);
25119   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25120     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25121       C = RHS.getOperand(0);
25122     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25123       D = RHS.getOperand(1);
25124     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25125     std::copy(Mask.begin(), Mask.end(), RMask.begin());
25126   } else {
25127     if (RHS.getOpcode() != ISD::UNDEF)
25128       C = RHS;
25129     for (unsigned i = 0; i != NumElts; ++i)
25130       RMask[i] = i;
25131   }
25132
25133   // Check that the shuffles are both shuffling the same vectors.
25134   if (!(A == C && B == D) && !(A == D && B == C))
25135     return false;
25136
25137   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25138   if (!A.getNode() && !B.getNode())
25139     return false;
25140
25141   // If A and B occur in reverse order in RHS, then "swap" them (which means
25142   // rewriting the mask).
25143   if (A != C)
25144     ShuffleVectorSDNode::commuteMask(RMask);
25145
25146   // At this point LHS and RHS are equivalent to
25147   //   LHS = VECTOR_SHUFFLE A, B, LMask
25148   //   RHS = VECTOR_SHUFFLE A, B, RMask
25149   // Check that the masks correspond to performing a horizontal operation.
25150   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25151     for (unsigned i = 0; i != NumLaneElts; ++i) {
25152       int LIdx = LMask[i+l], RIdx = RMask[i+l];
25153
25154       // Ignore any UNDEF components.
25155       if (LIdx < 0 || RIdx < 0 ||
25156           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25157           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25158         continue;
25159
25160       // Check that successive elements are being operated on.  If not, this is
25161       // not a horizontal operation.
25162       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25163       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25164       if (!(LIdx == Index && RIdx == Index + 1) &&
25165           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25166         return false;
25167     }
25168   }
25169
25170   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25171   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25172   return true;
25173 }
25174
25175 /// Do target-specific dag combines on floating point adds.
25176 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25177                                   const X86Subtarget *Subtarget) {
25178   EVT VT = N->getValueType(0);
25179   SDValue LHS = N->getOperand(0);
25180   SDValue RHS = N->getOperand(1);
25181
25182   // Try to synthesize horizontal adds from adds of shuffles.
25183   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25184        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25185       isHorizontalBinOp(LHS, RHS, true))
25186     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25187   return SDValue();
25188 }
25189
25190 /// Do target-specific dag combines on floating point subs.
25191 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25192                                   const X86Subtarget *Subtarget) {
25193   EVT VT = N->getValueType(0);
25194   SDValue LHS = N->getOperand(0);
25195   SDValue RHS = N->getOperand(1);
25196
25197   // Try to synthesize horizontal subs from subs of shuffles.
25198   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25199        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25200       isHorizontalBinOp(LHS, RHS, false))
25201     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25202   return SDValue();
25203 }
25204
25205 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25206 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
25207                                  const X86Subtarget *Subtarget) {
25208   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25209
25210   // F[X]OR(0.0, x) -> x
25211   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25212     if (C->getValueAPF().isPosZero())
25213       return N->getOperand(1);
25214
25215   // F[X]OR(x, 0.0) -> x
25216   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25217     if (C->getValueAPF().isPosZero())
25218       return N->getOperand(0);
25219
25220   EVT VT = N->getValueType(0);
25221   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
25222     SDLoc dl(N);
25223     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
25224     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
25225
25226     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
25227     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
25228     unsigned IntOpcode = (N->getOpcode() == X86ISD::FOR) ? ISD::OR : ISD::XOR;
25229     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
25230     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
25231   }
25232   return SDValue();
25233 }
25234
25235 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25236 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25237   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25238
25239   // Only perform optimizations if UnsafeMath is used.
25240   if (!DAG.getTarget().Options.UnsafeFPMath)
25241     return SDValue();
25242
25243   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25244   // into FMINC and FMAXC, which are Commutative operations.
25245   unsigned NewOp = 0;
25246   switch (N->getOpcode()) {
25247     default: llvm_unreachable("unknown opcode");
25248     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
25249     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
25250   }
25251
25252   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25253                      N->getOperand(0), N->getOperand(1));
25254 }
25255
25256 /// Do target-specific dag combines on X86ISD::FAND nodes.
25257 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25258   // FAND(0.0, x) -> 0.0
25259   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25260     if (C->getValueAPF().isPosZero())
25261       return N->getOperand(0);
25262
25263   // FAND(x, 0.0) -> 0.0
25264   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25265     if (C->getValueAPF().isPosZero())
25266       return N->getOperand(1);
25267
25268   return SDValue();
25269 }
25270
25271 /// Do target-specific dag combines on X86ISD::FANDN nodes
25272 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25273   // FANDN(0.0, x) -> x
25274   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25275     if (C->getValueAPF().isPosZero())
25276       return N->getOperand(1);
25277
25278   // FANDN(x, 0.0) -> 0.0
25279   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25280     if (C->getValueAPF().isPosZero())
25281       return N->getOperand(1);
25282
25283   return SDValue();
25284 }
25285
25286 static SDValue PerformBTCombine(SDNode *N,
25287                                 SelectionDAG &DAG,
25288                                 TargetLowering::DAGCombinerInfo &DCI) {
25289   // BT ignores high bits in the bit index operand.
25290   SDValue Op1 = N->getOperand(1);
25291   if (Op1.hasOneUse()) {
25292     unsigned BitWidth = Op1.getValueSizeInBits();
25293     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25294     APInt KnownZero, KnownOne;
25295     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25296                                           !DCI.isBeforeLegalizeOps());
25297     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25298     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25299         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25300       DCI.CommitTargetLoweringOpt(TLO);
25301   }
25302   return SDValue();
25303 }
25304
25305 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25306   SDValue Op = N->getOperand(0);
25307   if (Op.getOpcode() == ISD::BITCAST)
25308     Op = Op.getOperand(0);
25309   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25310   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25311       VT.getVectorElementType().getSizeInBits() ==
25312       OpVT.getVectorElementType().getSizeInBits()) {
25313     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25314   }
25315   return SDValue();
25316 }
25317
25318 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25319                                                const X86Subtarget *Subtarget) {
25320   EVT VT = N->getValueType(0);
25321   if (!VT.isVector())
25322     return SDValue();
25323
25324   SDValue N0 = N->getOperand(0);
25325   SDValue N1 = N->getOperand(1);
25326   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25327   SDLoc dl(N);
25328
25329   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25330   // both SSE and AVX2 since there is no sign-extended shift right
25331   // operation on a vector with 64-bit elements.
25332   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25333   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25334   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25335       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25336     SDValue N00 = N0.getOperand(0);
25337
25338     // EXTLOAD has a better solution on AVX2,
25339     // it may be replaced with X86ISD::VSEXT node.
25340     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25341       if (!ISD::isNormalLoad(N00.getNode()))
25342         return SDValue();
25343
25344     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25345         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25346                                   N00, N1);
25347       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25348     }
25349   }
25350   return SDValue();
25351 }
25352
25353 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25354                                   TargetLowering::DAGCombinerInfo &DCI,
25355                                   const X86Subtarget *Subtarget) {
25356   SDValue N0 = N->getOperand(0);
25357   EVT VT = N->getValueType(0);
25358   EVT SVT = VT.getScalarType();
25359   EVT InVT = N0.getValueType();
25360   EVT InSVT = InVT.getScalarType();
25361   SDLoc DL(N);
25362
25363   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25364   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25365   // This exposes the sext to the sdivrem lowering, so that it directly extends
25366   // from AH (which we otherwise need to do contortions to access).
25367   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25368       InVT == MVT::i8 && VT == MVT::i32) {
25369     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25370     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25371                             N0.getOperand(0), N0.getOperand(1));
25372     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25373     return R.getValue(1);
25374   }
25375
25376   if (!DCI.isBeforeLegalizeOps()) {
25377     if (InVT == MVT::i1) {
25378       SDValue Zero = DAG.getConstant(0, DL, VT);
25379       SDValue AllOnes =
25380         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25381       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25382     }
25383     return SDValue();
25384   }
25385
25386   if (VT.isVector() && Subtarget->hasSSE2()) {
25387     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25388       EVT InVT = N.getValueType();
25389       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25390                                    Size / InVT.getScalarSizeInBits());
25391       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25392                                     DAG.getUNDEF(InVT));
25393       Opnds[0] = N;
25394       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25395     };
25396
25397     // If target-size is less than 128-bits, extend to a type that would extend
25398     // to 128 bits, extend that and extract the original target vector.
25399     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25400         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25401         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25402       unsigned Scale = 128 / VT.getSizeInBits();
25403       EVT ExVT =
25404           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25405       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25406       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25407       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25408                          DAG.getIntPtrConstant(0, DL));
25409     }
25410
25411     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25412     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25413     if (VT.getSizeInBits() == 128 &&
25414         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25415         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25416       SDValue ExOp = ExtendVecSize(DL, N0, 128);
25417       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25418     }
25419
25420     // On pre-AVX2 targets, split into 128-bit nodes of
25421     // ISD::SIGN_EXTEND_VECTOR_INREG.
25422     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25423         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25424         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25425       unsigned NumVecs = VT.getSizeInBits() / 128;
25426       unsigned NumSubElts = 128 / SVT.getSizeInBits();
25427       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25428       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25429
25430       SmallVector<SDValue, 8> Opnds;
25431       for (unsigned i = 0, Offset = 0; i != NumVecs;
25432            ++i, Offset += NumSubElts) {
25433         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25434                                      DAG.getIntPtrConstant(Offset, DL));
25435         SrcVec = ExtendVecSize(DL, SrcVec, 128);
25436         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25437         Opnds.push_back(SrcVec);
25438       }
25439       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25440     }
25441   }
25442
25443   if (!Subtarget->hasFp256())
25444     return SDValue();
25445
25446   if (VT.isVector() && VT.getSizeInBits() == 256)
25447     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25448       return R;
25449
25450   return SDValue();
25451 }
25452
25453 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25454                                  const X86Subtarget* Subtarget) {
25455   SDLoc dl(N);
25456   EVT VT = N->getValueType(0);
25457
25458   // Let legalize expand this if it isn't a legal type yet.
25459   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25460     return SDValue();
25461
25462   EVT ScalarVT = VT.getScalarType();
25463   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25464       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25465        !Subtarget->hasAVX512()))
25466     return SDValue();
25467
25468   SDValue A = N->getOperand(0);
25469   SDValue B = N->getOperand(1);
25470   SDValue C = N->getOperand(2);
25471
25472   bool NegA = (A.getOpcode() == ISD::FNEG);
25473   bool NegB = (B.getOpcode() == ISD::FNEG);
25474   bool NegC = (C.getOpcode() == ISD::FNEG);
25475
25476   // Negative multiplication when NegA xor NegB
25477   bool NegMul = (NegA != NegB);
25478   if (NegA)
25479     A = A.getOperand(0);
25480   if (NegB)
25481     B = B.getOperand(0);
25482   if (NegC)
25483     C = C.getOperand(0);
25484
25485   unsigned Opcode;
25486   if (!NegMul)
25487     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25488   else
25489     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25490
25491   return DAG.getNode(Opcode, dl, VT, A, B, C);
25492 }
25493
25494 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25495                                   TargetLowering::DAGCombinerInfo &DCI,
25496                                   const X86Subtarget *Subtarget) {
25497   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25498   //           (and (i32 x86isd::setcc_carry), 1)
25499   // This eliminates the zext. This transformation is necessary because
25500   // ISD::SETCC is always legalized to i8.
25501   SDLoc dl(N);
25502   SDValue N0 = N->getOperand(0);
25503   EVT VT = N->getValueType(0);
25504
25505   if (N0.getOpcode() == ISD::AND &&
25506       N0.hasOneUse() &&
25507       N0.getOperand(0).hasOneUse()) {
25508     SDValue N00 = N0.getOperand(0);
25509     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25510       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25511       if (!C || C->getZExtValue() != 1)
25512         return SDValue();
25513       return DAG.getNode(ISD::AND, dl, VT,
25514                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25515                                      N00.getOperand(0), N00.getOperand(1)),
25516                          DAG.getConstant(1, dl, VT));
25517     }
25518   }
25519
25520   if (N0.getOpcode() == ISD::TRUNCATE &&
25521       N0.hasOneUse() &&
25522       N0.getOperand(0).hasOneUse()) {
25523     SDValue N00 = N0.getOperand(0);
25524     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25525       return DAG.getNode(ISD::AND, dl, VT,
25526                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25527                                      N00.getOperand(0), N00.getOperand(1)),
25528                          DAG.getConstant(1, dl, VT));
25529     }
25530   }
25531
25532   if (VT.is256BitVector())
25533     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25534       return R;
25535
25536   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25537   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25538   // This exposes the zext to the udivrem lowering, so that it directly extends
25539   // from AH (which we otherwise need to do contortions to access).
25540   if (N0.getOpcode() == ISD::UDIVREM &&
25541       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25542       (VT == MVT::i32 || VT == MVT::i64)) {
25543     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25544     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25545                             N0.getOperand(0), N0.getOperand(1));
25546     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25547     return R.getValue(1);
25548   }
25549
25550   return SDValue();
25551 }
25552
25553 // Optimize x == -y --> x+y == 0
25554 //          x != -y --> x+y != 0
25555 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25556                                       const X86Subtarget* Subtarget) {
25557   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25558   SDValue LHS = N->getOperand(0);
25559   SDValue RHS = N->getOperand(1);
25560   EVT VT = N->getValueType(0);
25561   SDLoc DL(N);
25562
25563   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25564     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25565       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25566         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25567                                    LHS.getOperand(1));
25568         return DAG.getSetCC(DL, N->getValueType(0), addV,
25569                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25570       }
25571   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25572     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25573       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25574         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25575                                    RHS.getOperand(1));
25576         return DAG.getSetCC(DL, N->getValueType(0), addV,
25577                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25578       }
25579
25580   if (VT.getScalarType() == MVT::i1 &&
25581       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25582     bool IsSEXT0 =
25583         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25584         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25585     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25586
25587     if (!IsSEXT0 || !IsVZero1) {
25588       // Swap the operands and update the condition code.
25589       std::swap(LHS, RHS);
25590       CC = ISD::getSetCCSwappedOperands(CC);
25591
25592       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25593                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25594       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25595     }
25596
25597     if (IsSEXT0 && IsVZero1) {
25598       assert(VT == LHS.getOperand(0).getValueType() &&
25599              "Uexpected operand type");
25600       if (CC == ISD::SETGT)
25601         return DAG.getConstant(0, DL, VT);
25602       if (CC == ISD::SETLE)
25603         return DAG.getConstant(1, DL, VT);
25604       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25605         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25606
25607       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25608              "Unexpected condition code!");
25609       return LHS.getOperand(0);
25610     }
25611   }
25612
25613   return SDValue();
25614 }
25615
25616 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25617                                          SelectionDAG &DAG) {
25618   SDLoc dl(Load);
25619   MVT VT = Load->getSimpleValueType(0);
25620   MVT EVT = VT.getVectorElementType();
25621   SDValue Addr = Load->getOperand(1);
25622   SDValue NewAddr = DAG.getNode(
25623       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25624       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25625                       Addr.getSimpleValueType()));
25626
25627   SDValue NewLoad =
25628       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25629                   DAG.getMachineFunction().getMachineMemOperand(
25630                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25631   return NewLoad;
25632 }
25633
25634 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25635                                       const X86Subtarget *Subtarget) {
25636   SDLoc dl(N);
25637   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25638   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25639          "X86insertps is only defined for v4x32");
25640
25641   SDValue Ld = N->getOperand(1);
25642   if (MayFoldLoad(Ld)) {
25643     // Extract the countS bits from the immediate so we can get the proper
25644     // address when narrowing the vector load to a specific element.
25645     // When the second source op is a memory address, insertps doesn't use
25646     // countS and just gets an f32 from that address.
25647     unsigned DestIndex =
25648         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25649
25650     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25651
25652     // Create this as a scalar to vector to match the instruction pattern.
25653     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25654     // countS bits are ignored when loading from memory on insertps, which
25655     // means we don't need to explicitly set them to 0.
25656     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25657                        LoadScalarToVector, N->getOperand(2));
25658   }
25659   return SDValue();
25660 }
25661
25662 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25663   SDValue V0 = N->getOperand(0);
25664   SDValue V1 = N->getOperand(1);
25665   SDLoc DL(N);
25666   EVT VT = N->getValueType(0);
25667
25668   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25669   // operands and changing the mask to 1. This saves us a bunch of
25670   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25671   // x86InstrInfo knows how to commute this back after instruction selection
25672   // if it would help register allocation.
25673
25674   // TODO: If optimizing for size or a processor that doesn't suffer from
25675   // partial register update stalls, this should be transformed into a MOVSD
25676   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25677
25678   if (VT == MVT::v2f64)
25679     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25680       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25681         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25682         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25683       }
25684
25685   return SDValue();
25686 }
25687
25688 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25689 // as "sbb reg,reg", since it can be extended without zext and produces
25690 // an all-ones bit which is more useful than 0/1 in some cases.
25691 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25692                                MVT VT) {
25693   if (VT == MVT::i8)
25694     return DAG.getNode(ISD::AND, DL, VT,
25695                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25696                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25697                                    EFLAGS),
25698                        DAG.getConstant(1, DL, VT));
25699   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25700   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25701                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25702                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25703                                  EFLAGS));
25704 }
25705
25706 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25707 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25708                                    TargetLowering::DAGCombinerInfo &DCI,
25709                                    const X86Subtarget *Subtarget) {
25710   SDLoc DL(N);
25711   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25712   SDValue EFLAGS = N->getOperand(1);
25713
25714   if (CC == X86::COND_A) {
25715     // Try to convert COND_A into COND_B in an attempt to facilitate
25716     // materializing "setb reg".
25717     //
25718     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25719     // cannot take an immediate as its first operand.
25720     //
25721     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25722         EFLAGS.getValueType().isInteger() &&
25723         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25724       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25725                                    EFLAGS.getNode()->getVTList(),
25726                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25727       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25728       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25729     }
25730   }
25731
25732   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25733   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25734   // cases.
25735   if (CC == X86::COND_B)
25736     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25737
25738   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25739     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25740     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25741   }
25742
25743   return SDValue();
25744 }
25745
25746 // Optimize branch condition evaluation.
25747 //
25748 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25749                                     TargetLowering::DAGCombinerInfo &DCI,
25750                                     const X86Subtarget *Subtarget) {
25751   SDLoc DL(N);
25752   SDValue Chain = N->getOperand(0);
25753   SDValue Dest = N->getOperand(1);
25754   SDValue EFLAGS = N->getOperand(3);
25755   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25756
25757   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25758     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25759     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25760                        Flags);
25761   }
25762
25763   return SDValue();
25764 }
25765
25766 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25767                                                          SelectionDAG &DAG) {
25768   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25769   // optimize away operation when it's from a constant.
25770   //
25771   // The general transformation is:
25772   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25773   //       AND(VECTOR_CMP(x,y), constant2)
25774   //    constant2 = UNARYOP(constant)
25775
25776   // Early exit if this isn't a vector operation, the operand of the
25777   // unary operation isn't a bitwise AND, or if the sizes of the operations
25778   // aren't the same.
25779   EVT VT = N->getValueType(0);
25780   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25781       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25782       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25783     return SDValue();
25784
25785   // Now check that the other operand of the AND is a constant. We could
25786   // make the transformation for non-constant splats as well, but it's unclear
25787   // that would be a benefit as it would not eliminate any operations, just
25788   // perform one more step in scalar code before moving to the vector unit.
25789   if (BuildVectorSDNode *BV =
25790           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25791     // Bail out if the vector isn't a constant.
25792     if (!BV->isConstant())
25793       return SDValue();
25794
25795     // Everything checks out. Build up the new and improved node.
25796     SDLoc DL(N);
25797     EVT IntVT = BV->getValueType(0);
25798     // Create a new constant of the appropriate type for the transformed
25799     // DAG.
25800     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25801     // The AND node needs bitcasts to/from an integer vector type around it.
25802     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25803     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25804                                  N->getOperand(0)->getOperand(0), MaskConst);
25805     SDValue Res = DAG.getBitcast(VT, NewAnd);
25806     return Res;
25807   }
25808
25809   return SDValue();
25810 }
25811
25812 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25813                                         const X86Subtarget *Subtarget) {
25814   SDValue Op0 = N->getOperand(0);
25815   EVT VT = N->getValueType(0);
25816   EVT InVT = Op0.getValueType();
25817   EVT InSVT = InVT.getScalarType();
25818   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25819
25820   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25821   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25822   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25823     SDLoc dl(N);
25824     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25825                                  InVT.getVectorNumElements());
25826     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25827
25828     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25829       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25830
25831     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25832   }
25833
25834   return SDValue();
25835 }
25836
25837 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25838                                         const X86Subtarget *Subtarget) {
25839   // First try to optimize away the conversion entirely when it's
25840   // conditionally from a constant. Vectors only.
25841   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25842     return Res;
25843
25844   // Now move on to more general possibilities.
25845   SDValue Op0 = N->getOperand(0);
25846   EVT VT = N->getValueType(0);
25847   EVT InVT = Op0.getValueType();
25848   EVT InSVT = InVT.getScalarType();
25849
25850   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25851   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25852   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25853     SDLoc dl(N);
25854     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25855                                  InVT.getVectorNumElements());
25856     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25857     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25858   }
25859
25860   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25861   // a 32-bit target where SSE doesn't support i64->FP operations.
25862   if (Op0.getOpcode() == ISD::LOAD) {
25863     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25864     EVT LdVT = Ld->getValueType(0);
25865
25866     // This transformation is not supported if the result type is f16
25867     if (VT == MVT::f16)
25868       return SDValue();
25869
25870     if (!Ld->isVolatile() && !VT.isVector() &&
25871         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25872         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25873       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25874           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25875       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25876       return FILDChain;
25877     }
25878   }
25879   return SDValue();
25880 }
25881
25882 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25883 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25884                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25885   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25886   // the result is either zero or one (depending on the input carry bit).
25887   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25888   if (X86::isZeroNode(N->getOperand(0)) &&
25889       X86::isZeroNode(N->getOperand(1)) &&
25890       // We don't have a good way to replace an EFLAGS use, so only do this when
25891       // dead right now.
25892       SDValue(N, 1).use_empty()) {
25893     SDLoc DL(N);
25894     EVT VT = N->getValueType(0);
25895     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25896     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25897                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25898                                            DAG.getConstant(X86::COND_B, DL,
25899                                                            MVT::i8),
25900                                            N->getOperand(2)),
25901                                DAG.getConstant(1, DL, VT));
25902     return DCI.CombineTo(N, Res1, CarryOut);
25903   }
25904
25905   return SDValue();
25906 }
25907
25908 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25909 //      (add Y, (setne X, 0)) -> sbb -1, Y
25910 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25911 //      (sub (setne X, 0), Y) -> adc -1, Y
25912 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25913   SDLoc DL(N);
25914
25915   // Look through ZExts.
25916   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25917   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25918     return SDValue();
25919
25920   SDValue SetCC = Ext.getOperand(0);
25921   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25922     return SDValue();
25923
25924   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25925   if (CC != X86::COND_E && CC != X86::COND_NE)
25926     return SDValue();
25927
25928   SDValue Cmp = SetCC.getOperand(1);
25929   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25930       !X86::isZeroNode(Cmp.getOperand(1)) ||
25931       !Cmp.getOperand(0).getValueType().isInteger())
25932     return SDValue();
25933
25934   SDValue CmpOp0 = Cmp.getOperand(0);
25935   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25936                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25937
25938   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25939   if (CC == X86::COND_NE)
25940     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25941                        DL, OtherVal.getValueType(), OtherVal,
25942                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25943                        NewCmp);
25944   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25945                      DL, OtherVal.getValueType(), OtherVal,
25946                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25947 }
25948
25949 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25950 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25951                                  const X86Subtarget *Subtarget) {
25952   EVT VT = N->getValueType(0);
25953   SDValue Op0 = N->getOperand(0);
25954   SDValue Op1 = N->getOperand(1);
25955
25956   // Try to synthesize horizontal adds from adds of shuffles.
25957   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25958        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25959       isHorizontalBinOp(Op0, Op1, true))
25960     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25961
25962   return OptimizeConditionalInDecrement(N, DAG);
25963 }
25964
25965 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25966                                  const X86Subtarget *Subtarget) {
25967   SDValue Op0 = N->getOperand(0);
25968   SDValue Op1 = N->getOperand(1);
25969
25970   // X86 can't encode an immediate LHS of a sub. See if we can push the
25971   // negation into a preceding instruction.
25972   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25973     // If the RHS of the sub is a XOR with one use and a constant, invert the
25974     // immediate. Then add one to the LHS of the sub so we can turn
25975     // X-Y -> X+~Y+1, saving one register.
25976     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25977         isa<ConstantSDNode>(Op1.getOperand(1))) {
25978       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25979       EVT VT = Op0.getValueType();
25980       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25981                                    Op1.getOperand(0),
25982                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25983       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25984                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25985     }
25986   }
25987
25988   // Try to synthesize horizontal adds from adds of shuffles.
25989   EVT VT = N->getValueType(0);
25990   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25991        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25992       isHorizontalBinOp(Op0, Op1, true))
25993     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25994
25995   return OptimizeConditionalInDecrement(N, DAG);
25996 }
25997
25998 /// performVZEXTCombine - Performs build vector combines
25999 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
26000                                    TargetLowering::DAGCombinerInfo &DCI,
26001                                    const X86Subtarget *Subtarget) {
26002   SDLoc DL(N);
26003   MVT VT = N->getSimpleValueType(0);
26004   SDValue Op = N->getOperand(0);
26005   MVT OpVT = Op.getSimpleValueType();
26006   MVT OpEltVT = OpVT.getVectorElementType();
26007   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
26008
26009   // (vzext (bitcast (vzext (x)) -> (vzext x)
26010   SDValue V = Op;
26011   while (V.getOpcode() == ISD::BITCAST)
26012     V = V.getOperand(0);
26013
26014   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
26015     MVT InnerVT = V.getSimpleValueType();
26016     MVT InnerEltVT = InnerVT.getVectorElementType();
26017
26018     // If the element sizes match exactly, we can just do one larger vzext. This
26019     // is always an exact type match as vzext operates on integer types.
26020     if (OpEltVT == InnerEltVT) {
26021       assert(OpVT == InnerVT && "Types must match for vzext!");
26022       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
26023     }
26024
26025     // The only other way we can combine them is if only a single element of the
26026     // inner vzext is used in the input to the outer vzext.
26027     if (InnerEltVT.getSizeInBits() < InputBits)
26028       return SDValue();
26029
26030     // In this case, the inner vzext is completely dead because we're going to
26031     // only look at bits inside of the low element. Just do the outer vzext on
26032     // a bitcast of the input to the inner.
26033     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
26034   }
26035
26036   // Check if we can bypass extracting and re-inserting an element of an input
26037   // vector. Essentially:
26038   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
26039   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
26040       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
26041       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
26042     SDValue ExtractedV = V.getOperand(0);
26043     SDValue OrigV = ExtractedV.getOperand(0);
26044     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
26045       if (ExtractIdx->getZExtValue() == 0) {
26046         MVT OrigVT = OrigV.getSimpleValueType();
26047         // Extract a subvector if necessary...
26048         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
26049           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
26050           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
26051                                     OrigVT.getVectorNumElements() / Ratio);
26052           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
26053                               DAG.getIntPtrConstant(0, DL));
26054         }
26055         Op = DAG.getBitcast(OpVT, OrigV);
26056         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
26057       }
26058   }
26059
26060   return SDValue();
26061 }
26062
26063 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
26064                                              DAGCombinerInfo &DCI) const {
26065   SelectionDAG &DAG = DCI.DAG;
26066   switch (N->getOpcode()) {
26067   default: break;
26068   case ISD::EXTRACT_VECTOR_ELT:
26069     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26070   case ISD::VSELECT:
26071   case ISD::SELECT:
26072   case X86ISD::SHRUNKBLEND:
26073     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26074   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
26075   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26076   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
26077   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
26078   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
26079   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
26080   case ISD::SHL:
26081   case ISD::SRA:
26082   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
26083   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
26084   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
26085   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
26086   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
26087   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26088   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
26089   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
26090   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26091   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26092   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
26093   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
26094   case X86ISD::FXOR:
26095   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
26096   case X86ISD::FMIN:
26097   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
26098   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
26099   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
26100   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
26101   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
26102   case ISD::ANY_EXTEND:
26103   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
26104   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
26105   case ISD::SIGN_EXTEND_INREG:
26106     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26107   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
26108   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26109   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26110   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
26111   case X86ISD::SHUFP:       // Handle all target specific shuffles
26112   case X86ISD::PALIGNR:
26113   case X86ISD::UNPCKH:
26114   case X86ISD::UNPCKL:
26115   case X86ISD::MOVHLPS:
26116   case X86ISD::MOVLHPS:
26117   case X86ISD::PSHUFB:
26118   case X86ISD::PSHUFD:
26119   case X86ISD::PSHUFHW:
26120   case X86ISD::PSHUFLW:
26121   case X86ISD::MOVSS:
26122   case X86ISD::MOVSD:
26123   case X86ISD::VPERMILPI:
26124   case X86ISD::VPERM2X128:
26125   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26126   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
26127   case X86ISD::INSERTPS: {
26128     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
26129       return PerformINSERTPSCombine(N, DAG, Subtarget);
26130     break;
26131   }
26132   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
26133   }
26134
26135   return SDValue();
26136 }
26137
26138 /// isTypeDesirableForOp - Return true if the target has native support for
26139 /// the specified value type and it is 'desirable' to use the type for the
26140 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26141 /// instruction encodings are longer and some i16 instructions are slow.
26142 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26143   if (!isTypeLegal(VT))
26144     return false;
26145   if (VT != MVT::i16)
26146     return true;
26147
26148   switch (Opc) {
26149   default:
26150     return true;
26151   case ISD::LOAD:
26152   case ISD::SIGN_EXTEND:
26153   case ISD::ZERO_EXTEND:
26154   case ISD::ANY_EXTEND:
26155   case ISD::SHL:
26156   case ISD::SRL:
26157   case ISD::SUB:
26158   case ISD::ADD:
26159   case ISD::MUL:
26160   case ISD::AND:
26161   case ISD::OR:
26162   case ISD::XOR:
26163     return false;
26164   }
26165 }
26166
26167 /// IsDesirableToPromoteOp - This method query the target whether it is
26168 /// beneficial for dag combiner to promote the specified node. If true, it
26169 /// should return the desired promotion type by reference.
26170 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26171   EVT VT = Op.getValueType();
26172   if (VT != MVT::i16)
26173     return false;
26174
26175   bool Promote = false;
26176   bool Commute = false;
26177   switch (Op.getOpcode()) {
26178   default: break;
26179   case ISD::LOAD: {
26180     LoadSDNode *LD = cast<LoadSDNode>(Op);
26181     // If the non-extending load has a single use and it's not live out, then it
26182     // might be folded.
26183     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26184                                                      Op.hasOneUse()*/) {
26185       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26186              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26187         // The only case where we'd want to promote LOAD (rather then it being
26188         // promoted as an operand is when it's only use is liveout.
26189         if (UI->getOpcode() != ISD::CopyToReg)
26190           return false;
26191       }
26192     }
26193     Promote = true;
26194     break;
26195   }
26196   case ISD::SIGN_EXTEND:
26197   case ISD::ZERO_EXTEND:
26198   case ISD::ANY_EXTEND:
26199     Promote = true;
26200     break;
26201   case ISD::SHL:
26202   case ISD::SRL: {
26203     SDValue N0 = Op.getOperand(0);
26204     // Look out for (store (shl (load), x)).
26205     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26206       return false;
26207     Promote = true;
26208     break;
26209   }
26210   case ISD::ADD:
26211   case ISD::MUL:
26212   case ISD::AND:
26213   case ISD::OR:
26214   case ISD::XOR:
26215     Commute = true;
26216     // fallthrough
26217   case ISD::SUB: {
26218     SDValue N0 = Op.getOperand(0);
26219     SDValue N1 = Op.getOperand(1);
26220     if (!Commute && MayFoldLoad(N1))
26221       return false;
26222     // Avoid disabling potential load folding opportunities.
26223     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26224       return false;
26225     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26226       return false;
26227     Promote = true;
26228   }
26229   }
26230
26231   PVT = MVT::i32;
26232   return Promote;
26233 }
26234
26235 //===----------------------------------------------------------------------===//
26236 //                           X86 Inline Assembly Support
26237 //===----------------------------------------------------------------------===//
26238
26239 // Helper to match a string separated by whitespace.
26240 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26241   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26242
26243   for (StringRef Piece : Pieces) {
26244     if (!S.startswith(Piece)) // Check if the piece matches.
26245       return false;
26246
26247     S = S.substr(Piece.size());
26248     StringRef::size_type Pos = S.find_first_not_of(" \t");
26249     if (Pos == 0) // We matched a prefix.
26250       return false;
26251
26252     S = S.substr(Pos);
26253   }
26254
26255   return S.empty();
26256 }
26257
26258 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26259
26260   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26261     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26262         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26263         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26264
26265       if (AsmPieces.size() == 3)
26266         return true;
26267       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26268         return true;
26269     }
26270   }
26271   return false;
26272 }
26273
26274 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26275   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26276
26277   std::string AsmStr = IA->getAsmString();
26278
26279   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26280   if (!Ty || Ty->getBitWidth() % 16 != 0)
26281     return false;
26282
26283   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26284   SmallVector<StringRef, 4> AsmPieces;
26285   SplitString(AsmStr, AsmPieces, ";\n");
26286
26287   switch (AsmPieces.size()) {
26288   default: return false;
26289   case 1:
26290     // FIXME: this should verify that we are targeting a 486 or better.  If not,
26291     // we will turn this bswap into something that will be lowered to logical
26292     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26293     // lower so don't worry about this.
26294     // bswap $0
26295     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26296         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26297         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26298         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26299         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26300         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26301       // No need to check constraints, nothing other than the equivalent of
26302       // "=r,0" would be valid here.
26303       return IntrinsicLowering::LowerToByteSwap(CI);
26304     }
26305
26306     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26307     if (CI->getType()->isIntegerTy(16) &&
26308         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26309         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26310          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26311       AsmPieces.clear();
26312       StringRef ConstraintsStr = IA->getConstraintString();
26313       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26314       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26315       if (clobbersFlagRegisters(AsmPieces))
26316         return IntrinsicLowering::LowerToByteSwap(CI);
26317     }
26318     break;
26319   case 3:
26320     if (CI->getType()->isIntegerTy(32) &&
26321         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26322         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26323         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26324         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26325       AsmPieces.clear();
26326       StringRef ConstraintsStr = IA->getConstraintString();
26327       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26328       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26329       if (clobbersFlagRegisters(AsmPieces))
26330         return IntrinsicLowering::LowerToByteSwap(CI);
26331     }
26332
26333     if (CI->getType()->isIntegerTy(64)) {
26334       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26335       if (Constraints.size() >= 2 &&
26336           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26337           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26338         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
26339         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26340             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26341             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26342           return IntrinsicLowering::LowerToByteSwap(CI);
26343       }
26344     }
26345     break;
26346   }
26347   return false;
26348 }
26349
26350 /// getConstraintType - Given a constraint letter, return the type of
26351 /// constraint it is for this target.
26352 X86TargetLowering::ConstraintType
26353 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26354   if (Constraint.size() == 1) {
26355     switch (Constraint[0]) {
26356     case 'R':
26357     case 'q':
26358     case 'Q':
26359     case 'f':
26360     case 't':
26361     case 'u':
26362     case 'y':
26363     case 'x':
26364     case 'Y':
26365     case 'l':
26366       return C_RegisterClass;
26367     case 'a':
26368     case 'b':
26369     case 'c':
26370     case 'd':
26371     case 'S':
26372     case 'D':
26373     case 'A':
26374       return C_Register;
26375     case 'I':
26376     case 'J':
26377     case 'K':
26378     case 'L':
26379     case 'M':
26380     case 'N':
26381     case 'G':
26382     case 'C':
26383     case 'e':
26384     case 'Z':
26385       return C_Other;
26386     default:
26387       break;
26388     }
26389   }
26390   return TargetLowering::getConstraintType(Constraint);
26391 }
26392
26393 /// Examine constraint type and operand type and determine a weight value.
26394 /// This object must already have been set up with the operand type
26395 /// and the current alternative constraint selected.
26396 TargetLowering::ConstraintWeight
26397   X86TargetLowering::getSingleConstraintMatchWeight(
26398     AsmOperandInfo &info, const char *constraint) const {
26399   ConstraintWeight weight = CW_Invalid;
26400   Value *CallOperandVal = info.CallOperandVal;
26401     // If we don't have a value, we can't do a match,
26402     // but allow it at the lowest weight.
26403   if (!CallOperandVal)
26404     return CW_Default;
26405   Type *type = CallOperandVal->getType();
26406   // Look at the constraint type.
26407   switch (*constraint) {
26408   default:
26409     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26410   case 'R':
26411   case 'q':
26412   case 'Q':
26413   case 'a':
26414   case 'b':
26415   case 'c':
26416   case 'd':
26417   case 'S':
26418   case 'D':
26419   case 'A':
26420     if (CallOperandVal->getType()->isIntegerTy())
26421       weight = CW_SpecificReg;
26422     break;
26423   case 'f':
26424   case 't':
26425   case 'u':
26426     if (type->isFloatingPointTy())
26427       weight = CW_SpecificReg;
26428     break;
26429   case 'y':
26430     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26431       weight = CW_SpecificReg;
26432     break;
26433   case 'x':
26434   case 'Y':
26435     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26436         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26437       weight = CW_Register;
26438     break;
26439   case 'I':
26440     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26441       if (C->getZExtValue() <= 31)
26442         weight = CW_Constant;
26443     }
26444     break;
26445   case 'J':
26446     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26447       if (C->getZExtValue() <= 63)
26448         weight = CW_Constant;
26449     }
26450     break;
26451   case 'K':
26452     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26453       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26454         weight = CW_Constant;
26455     }
26456     break;
26457   case 'L':
26458     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26459       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26460         weight = CW_Constant;
26461     }
26462     break;
26463   case 'M':
26464     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26465       if (C->getZExtValue() <= 3)
26466         weight = CW_Constant;
26467     }
26468     break;
26469   case 'N':
26470     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26471       if (C->getZExtValue() <= 0xff)
26472         weight = CW_Constant;
26473     }
26474     break;
26475   case 'G':
26476   case 'C':
26477     if (isa<ConstantFP>(CallOperandVal)) {
26478       weight = CW_Constant;
26479     }
26480     break;
26481   case 'e':
26482     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26483       if ((C->getSExtValue() >= -0x80000000LL) &&
26484           (C->getSExtValue() <= 0x7fffffffLL))
26485         weight = CW_Constant;
26486     }
26487     break;
26488   case 'Z':
26489     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26490       if (C->getZExtValue() <= 0xffffffff)
26491         weight = CW_Constant;
26492     }
26493     break;
26494   }
26495   return weight;
26496 }
26497
26498 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26499 /// with another that has more specific requirements based on the type of the
26500 /// corresponding operand.
26501 const char *X86TargetLowering::
26502 LowerXConstraint(EVT ConstraintVT) const {
26503   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26504   // 'f' like normal targets.
26505   if (ConstraintVT.isFloatingPoint()) {
26506     if (Subtarget->hasSSE2())
26507       return "Y";
26508     if (Subtarget->hasSSE1())
26509       return "x";
26510   }
26511
26512   return TargetLowering::LowerXConstraint(ConstraintVT);
26513 }
26514
26515 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26516 /// vector.  If it is invalid, don't add anything to Ops.
26517 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26518                                                      std::string &Constraint,
26519                                                      std::vector<SDValue>&Ops,
26520                                                      SelectionDAG &DAG) const {
26521   SDValue Result;
26522
26523   // Only support length 1 constraints for now.
26524   if (Constraint.length() > 1) return;
26525
26526   char ConstraintLetter = Constraint[0];
26527   switch (ConstraintLetter) {
26528   default: break;
26529   case 'I':
26530     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26531       if (C->getZExtValue() <= 31) {
26532         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26533                                        Op.getValueType());
26534         break;
26535       }
26536     }
26537     return;
26538   case 'J':
26539     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26540       if (C->getZExtValue() <= 63) {
26541         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26542                                        Op.getValueType());
26543         break;
26544       }
26545     }
26546     return;
26547   case 'K':
26548     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26549       if (isInt<8>(C->getSExtValue())) {
26550         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26551                                        Op.getValueType());
26552         break;
26553       }
26554     }
26555     return;
26556   case 'L':
26557     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26558       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26559           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26560         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26561                                        Op.getValueType());
26562         break;
26563       }
26564     }
26565     return;
26566   case 'M':
26567     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26568       if (C->getZExtValue() <= 3) {
26569         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26570                                        Op.getValueType());
26571         break;
26572       }
26573     }
26574     return;
26575   case 'N':
26576     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26577       if (C->getZExtValue() <= 255) {
26578         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26579                                        Op.getValueType());
26580         break;
26581       }
26582     }
26583     return;
26584   case 'O':
26585     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26586       if (C->getZExtValue() <= 127) {
26587         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26588                                        Op.getValueType());
26589         break;
26590       }
26591     }
26592     return;
26593   case 'e': {
26594     // 32-bit signed value
26595     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26596       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26597                                            C->getSExtValue())) {
26598         // Widen to 64 bits here to get it sign extended.
26599         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26600         break;
26601       }
26602     // FIXME gcc accepts some relocatable values here too, but only in certain
26603     // memory models; it's complicated.
26604     }
26605     return;
26606   }
26607   case 'Z': {
26608     // 32-bit unsigned value
26609     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26610       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26611                                            C->getZExtValue())) {
26612         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26613                                        Op.getValueType());
26614         break;
26615       }
26616     }
26617     // FIXME gcc accepts some relocatable values here too, but only in certain
26618     // memory models; it's complicated.
26619     return;
26620   }
26621   case 'i': {
26622     // Literal immediates are always ok.
26623     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26624       // Widen to 64 bits here to get it sign extended.
26625       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26626       break;
26627     }
26628
26629     // In any sort of PIC mode addresses need to be computed at runtime by
26630     // adding in a register or some sort of table lookup.  These can't
26631     // be used as immediates.
26632     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26633       return;
26634
26635     // If we are in non-pic codegen mode, we allow the address of a global (with
26636     // an optional displacement) to be used with 'i'.
26637     GlobalAddressSDNode *GA = nullptr;
26638     int64_t Offset = 0;
26639
26640     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26641     while (1) {
26642       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26643         Offset += GA->getOffset();
26644         break;
26645       } else if (Op.getOpcode() == ISD::ADD) {
26646         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26647           Offset += C->getZExtValue();
26648           Op = Op.getOperand(0);
26649           continue;
26650         }
26651       } else if (Op.getOpcode() == ISD::SUB) {
26652         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26653           Offset += -C->getZExtValue();
26654           Op = Op.getOperand(0);
26655           continue;
26656         }
26657       }
26658
26659       // Otherwise, this isn't something we can handle, reject it.
26660       return;
26661     }
26662
26663     const GlobalValue *GV = GA->getGlobal();
26664     // If we require an extra load to get this address, as in PIC mode, we
26665     // can't accept it.
26666     if (isGlobalStubReference(
26667             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26668       return;
26669
26670     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26671                                         GA->getValueType(0), Offset);
26672     break;
26673   }
26674   }
26675
26676   if (Result.getNode()) {
26677     Ops.push_back(Result);
26678     return;
26679   }
26680   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26681 }
26682
26683 std::pair<unsigned, const TargetRegisterClass *>
26684 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26685                                                 StringRef Constraint,
26686                                                 MVT VT) const {
26687   // First, see if this is a constraint that directly corresponds to an LLVM
26688   // register class.
26689   if (Constraint.size() == 1) {
26690     // GCC Constraint Letters
26691     switch (Constraint[0]) {
26692     default: break;
26693       // TODO: Slight differences here in allocation order and leaving
26694       // RIP in the class. Do they matter any more here than they do
26695       // in the normal allocation?
26696     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26697       if (Subtarget->is64Bit()) {
26698         if (VT == MVT::i32 || VT == MVT::f32)
26699           return std::make_pair(0U, &X86::GR32RegClass);
26700         if (VT == MVT::i16)
26701           return std::make_pair(0U, &X86::GR16RegClass);
26702         if (VT == MVT::i8 || VT == MVT::i1)
26703           return std::make_pair(0U, &X86::GR8RegClass);
26704         if (VT == MVT::i64 || VT == MVT::f64)
26705           return std::make_pair(0U, &X86::GR64RegClass);
26706         break;
26707       }
26708       // 32-bit fallthrough
26709     case 'Q':   // Q_REGS
26710       if (VT == MVT::i32 || VT == MVT::f32)
26711         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26712       if (VT == MVT::i16)
26713         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26714       if (VT == MVT::i8 || VT == MVT::i1)
26715         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26716       if (VT == MVT::i64)
26717         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26718       break;
26719     case 'r':   // GENERAL_REGS
26720     case 'l':   // INDEX_REGS
26721       if (VT == MVT::i8 || VT == MVT::i1)
26722         return std::make_pair(0U, &X86::GR8RegClass);
26723       if (VT == MVT::i16)
26724         return std::make_pair(0U, &X86::GR16RegClass);
26725       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26726         return std::make_pair(0U, &X86::GR32RegClass);
26727       return std::make_pair(0U, &X86::GR64RegClass);
26728     case 'R':   // LEGACY_REGS
26729       if (VT == MVT::i8 || VT == MVT::i1)
26730         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26731       if (VT == MVT::i16)
26732         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26733       if (VT == MVT::i32 || !Subtarget->is64Bit())
26734         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26735       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26736     case 'f':  // FP Stack registers.
26737       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26738       // value to the correct fpstack register class.
26739       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26740         return std::make_pair(0U, &X86::RFP32RegClass);
26741       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26742         return std::make_pair(0U, &X86::RFP64RegClass);
26743       return std::make_pair(0U, &X86::RFP80RegClass);
26744     case 'y':   // MMX_REGS if MMX allowed.
26745       if (!Subtarget->hasMMX()) break;
26746       return std::make_pair(0U, &X86::VR64RegClass);
26747     case 'Y':   // SSE_REGS if SSE2 allowed
26748       if (!Subtarget->hasSSE2()) break;
26749       // FALL THROUGH.
26750     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26751       if (!Subtarget->hasSSE1()) break;
26752
26753       switch (VT.SimpleTy) {
26754       default: break;
26755       // Scalar SSE types.
26756       case MVT::f32:
26757       case MVT::i32:
26758         return std::make_pair(0U, &X86::FR32RegClass);
26759       case MVT::f64:
26760       case MVT::i64:
26761         return std::make_pair(0U, &X86::FR64RegClass);
26762       // Vector types.
26763       case MVT::v16i8:
26764       case MVT::v8i16:
26765       case MVT::v4i32:
26766       case MVT::v2i64:
26767       case MVT::v4f32:
26768       case MVT::v2f64:
26769         return std::make_pair(0U, &X86::VR128RegClass);
26770       // AVX types.
26771       case MVT::v32i8:
26772       case MVT::v16i16:
26773       case MVT::v8i32:
26774       case MVT::v4i64:
26775       case MVT::v8f32:
26776       case MVT::v4f64:
26777         return std::make_pair(0U, &X86::VR256RegClass);
26778       case MVT::v8f64:
26779       case MVT::v16f32:
26780       case MVT::v16i32:
26781       case MVT::v8i64:
26782         return std::make_pair(0U, &X86::VR512RegClass);
26783       }
26784       break;
26785     }
26786   }
26787
26788   // Use the default implementation in TargetLowering to convert the register
26789   // constraint into a member of a register class.
26790   std::pair<unsigned, const TargetRegisterClass*> Res;
26791   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26792
26793   // Not found as a standard register?
26794   if (!Res.second) {
26795     // Map st(0) -> st(7) -> ST0
26796     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26797         tolower(Constraint[1]) == 's' &&
26798         tolower(Constraint[2]) == 't' &&
26799         Constraint[3] == '(' &&
26800         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26801         Constraint[5] == ')' &&
26802         Constraint[6] == '}') {
26803
26804       Res.first = X86::FP0+Constraint[4]-'0';
26805       Res.second = &X86::RFP80RegClass;
26806       return Res;
26807     }
26808
26809     // GCC allows "st(0)" to be called just plain "st".
26810     if (StringRef("{st}").equals_lower(Constraint)) {
26811       Res.first = X86::FP0;
26812       Res.second = &X86::RFP80RegClass;
26813       return Res;
26814     }
26815
26816     // flags -> EFLAGS
26817     if (StringRef("{flags}").equals_lower(Constraint)) {
26818       Res.first = X86::EFLAGS;
26819       Res.second = &X86::CCRRegClass;
26820       return Res;
26821     }
26822
26823     // 'A' means EAX + EDX.
26824     if (Constraint == "A") {
26825       Res.first = X86::EAX;
26826       Res.second = &X86::GR32_ADRegClass;
26827       return Res;
26828     }
26829     return Res;
26830   }
26831
26832   // Otherwise, check to see if this is a register class of the wrong value
26833   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26834   // turn into {ax},{dx}.
26835   // MVT::Other is used to specify clobber names.
26836   if (Res.second->hasType(VT) || VT == MVT::Other)
26837     return Res;   // Correct type already, nothing to do.
26838
26839   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26840   // return "eax". This should even work for things like getting 64bit integer
26841   // registers when given an f64 type.
26842   const TargetRegisterClass *Class = Res.second;
26843   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26844       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26845     unsigned Size = VT.getSizeInBits();
26846     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26847                                   : Size == 16 ? MVT::i16
26848                                   : Size == 32 ? MVT::i32
26849                                   : Size == 64 ? MVT::i64
26850                                   : MVT::Other;
26851     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26852     if (DestReg > 0) {
26853       Res.first = DestReg;
26854       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26855                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26856                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26857                  : &X86::GR64RegClass;
26858       assert(Res.second->contains(Res.first) && "Register in register class");
26859     } else {
26860       // No register found/type mismatch.
26861       Res.first = 0;
26862       Res.second = nullptr;
26863     }
26864   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26865              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26866              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26867              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26868              Class == &X86::VR512RegClass) {
26869     // Handle references to XMM physical registers that got mapped into the
26870     // wrong class.  This can happen with constraints like {xmm0} where the
26871     // target independent register mapper will just pick the first match it can
26872     // find, ignoring the required type.
26873
26874     if (VT == MVT::f32 || VT == MVT::i32)
26875       Res.second = &X86::FR32RegClass;
26876     else if (VT == MVT::f64 || VT == MVT::i64)
26877       Res.second = &X86::FR64RegClass;
26878     else if (X86::VR128RegClass.hasType(VT))
26879       Res.second = &X86::VR128RegClass;
26880     else if (X86::VR256RegClass.hasType(VT))
26881       Res.second = &X86::VR256RegClass;
26882     else if (X86::VR512RegClass.hasType(VT))
26883       Res.second = &X86::VR512RegClass;
26884     else {
26885       // Type mismatch and not a clobber: Return an error;
26886       Res.first = 0;
26887       Res.second = nullptr;
26888     }
26889   }
26890
26891   return Res;
26892 }
26893
26894 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26895                                             const AddrMode &AM, Type *Ty,
26896                                             unsigned AS) const {
26897   // Scaling factors are not free at all.
26898   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26899   // will take 2 allocations in the out of order engine instead of 1
26900   // for plain addressing mode, i.e. inst (reg1).
26901   // E.g.,
26902   // vaddps (%rsi,%drx), %ymm0, %ymm1
26903   // Requires two allocations (one for the load, one for the computation)
26904   // whereas:
26905   // vaddps (%rsi), %ymm0, %ymm1
26906   // Requires just 1 allocation, i.e., freeing allocations for other operations
26907   // and having less micro operations to execute.
26908   //
26909   // For some X86 architectures, this is even worse because for instance for
26910   // stores, the complex addressing mode forces the instruction to use the
26911   // "load" ports instead of the dedicated "store" port.
26912   // E.g., on Haswell:
26913   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26914   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26915   if (isLegalAddressingMode(DL, AM, Ty, AS))
26916     // Scale represents reg2 * scale, thus account for 1
26917     // as soon as we use a second register.
26918     return AM.Scale != 0;
26919   return -1;
26920 }
26921
26922 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
26923   // Integer division on x86 is expensive. However, when aggressively optimizing
26924   // for code size, we prefer to use a div instruction, as it is usually smaller
26925   // than the alternative sequence.
26926   // The exception to this is vector division. Since x86 doesn't have vector
26927   // integer division, leaving the division as-is is a loss even in terms of
26928   // size, because it will have to be scalarized, while the alternative code
26929   // sequence can be performed in vector form.
26930   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
26931                                    Attribute::MinSize);
26932   return OptSize && !VT.isVector();
26933 }