de8d3e93b497b812b56546b82fdb222880d9b8a1
[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   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
422   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
423   // support continuation, user-level threading, and etc.. As a result, no
424   // other SjLj exception interfaces are implemented and please don't build
425   // your own exception handling based on them.
426   // LLVM/Clang supports zero-cost DWARF exception handling.
427   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
428   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
429
430   // Darwin ABI issue.
431   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
432   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
433   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
434   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
435   if (Subtarget->is64Bit())
436     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
437   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
438   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
439   if (Subtarget->is64Bit()) {
440     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
441     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
442     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
443     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
444     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
445   }
446   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
447   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
448   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
449   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
450   if (Subtarget->is64Bit()) {
451     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
452     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
453     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
454   }
455
456   if (Subtarget->hasSSE1())
457     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
458
459   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
460
461   // Expand certain atomics
462   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
463     MVT VT = IntVTs[i];
464     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
465     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
466     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
467   }
468
469   if (Subtarget->hasCmpxchg16b()) {
470     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
471   }
472
473   // FIXME - use subtarget debug flags
474   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
475       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
476     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
477   }
478
479   if (Subtarget->isTarget64BitLP64()) {
480     setExceptionPointerRegister(X86::RAX);
481     setExceptionSelectorRegister(X86::RDX);
482   } else {
483     setExceptionPointerRegister(X86::EAX);
484     setExceptionSelectorRegister(X86::EDX);
485   }
486   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
487   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
488
489   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
490   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
491
492   setOperationAction(ISD::TRAP, MVT::Other, Legal);
493   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
494
495   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
496   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
497   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
498   if (Subtarget->is64Bit()) {
499     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
500     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
501   } else {
502     // TargetInfo::CharPtrBuiltinVaList
503     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
504     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
505   }
506
507   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
508   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
509
510   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
511
512   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
513   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
514   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
515
516   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
517     // f32 and f64 use SSE.
518     // Set up the FP register classes.
519     addRegisterClass(MVT::f32, &X86::FR32RegClass);
520     addRegisterClass(MVT::f64, &X86::FR64RegClass);
521
522     // Use ANDPD to simulate FABS.
523     setOperationAction(ISD::FABS , MVT::f64, Custom);
524     setOperationAction(ISD::FABS , MVT::f32, Custom);
525
526     // Use XORP to simulate FNEG.
527     setOperationAction(ISD::FNEG , MVT::f64, Custom);
528     setOperationAction(ISD::FNEG , MVT::f32, Custom);
529
530     // Use ANDPD and ORPD to simulate FCOPYSIGN.
531     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
532     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
533
534     // Lower this to FGETSIGNx86 plus an AND.
535     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
536     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
537
538     // We don't support sin/cos/fmod
539     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
540     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
541     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
542     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
543     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
544     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
545
546     // Expand FP immediates into loads from the stack, except for the special
547     // cases we handle.
548     addLegalFPImmediate(APFloat(+0.0)); // xorpd
549     addLegalFPImmediate(APFloat(+0.0f)); // xorps
550   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
551     // Use SSE for f32, x87 for f64.
552     // Set up the FP register classes.
553     addRegisterClass(MVT::f32, &X86::FR32RegClass);
554     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
555
556     // Use ANDPS to simulate FABS.
557     setOperationAction(ISD::FABS , MVT::f32, Custom);
558
559     // Use XORP to simulate FNEG.
560     setOperationAction(ISD::FNEG , MVT::f32, Custom);
561
562     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
563
564     // Use ANDPS and ORPS to simulate FCOPYSIGN.
565     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
566     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
567
568     // We don't support sin/cos/fmod
569     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
570     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
571     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
572
573     // Special cases we handle for FP constants.
574     addLegalFPImmediate(APFloat(+0.0f)); // xorps
575     addLegalFPImmediate(APFloat(+0.0)); // FLD0
576     addLegalFPImmediate(APFloat(+1.0)); // FLD1
577     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
578     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
579
580     if (!TM.Options.UnsafeFPMath) {
581       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
582       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
583       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
584     }
585   } else if (!Subtarget->useSoftFloat()) {
586     // f32 and f64 in x87.
587     // Set up the FP register classes.
588     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
589     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
590
591     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
592     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
593     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
594     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
595
596     if (!TM.Options.UnsafeFPMath) {
597       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
598       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
599       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
600       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
601       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
602       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
603     }
604     addLegalFPImmediate(APFloat(+0.0)); // FLD0
605     addLegalFPImmediate(APFloat(+1.0)); // FLD1
606     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
607     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
608     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
609     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
610     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
611     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
612   }
613
614   // We don't support FMA.
615   setOperationAction(ISD::FMA, MVT::f64, Expand);
616   setOperationAction(ISD::FMA, MVT::f32, Expand);
617
618   // Long double always uses X87.
619   if (!Subtarget->useSoftFloat()) {
620     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
621     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
622     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
623     {
624       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
625       addLegalFPImmediate(TmpFlt);  // FLD0
626       TmpFlt.changeSign();
627       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
628
629       bool ignored;
630       APFloat TmpFlt2(+1.0);
631       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
632                       &ignored);
633       addLegalFPImmediate(TmpFlt2);  // FLD1
634       TmpFlt2.changeSign();
635       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
636     }
637
638     if (!TM.Options.UnsafeFPMath) {
639       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
640       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
641       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
642     }
643
644     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
645     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
646     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
647     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
648     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
649     setOperationAction(ISD::FMA, MVT::f80, Expand);
650   }
651
652   // Always use a library call for pow.
653   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
654   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
655   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
656
657   setOperationAction(ISD::FLOG, MVT::f80, Expand);
658   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
659   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
660   setOperationAction(ISD::FEXP, MVT::f80, Expand);
661   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
662   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
663   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
664
665   // First set operation action for all vector types to either promote
666   // (for widening) or expand (for scalarization). Then we will selectively
667   // turn on ones that can be effectively codegen'd.
668   for (MVT VT : MVT::vector_valuetypes()) {
669     setOperationAction(ISD::ADD , VT, Expand);
670     setOperationAction(ISD::SUB , VT, Expand);
671     setOperationAction(ISD::FADD, VT, Expand);
672     setOperationAction(ISD::FNEG, VT, Expand);
673     setOperationAction(ISD::FSUB, VT, Expand);
674     setOperationAction(ISD::MUL , VT, Expand);
675     setOperationAction(ISD::FMUL, VT, Expand);
676     setOperationAction(ISD::SDIV, VT, Expand);
677     setOperationAction(ISD::UDIV, VT, Expand);
678     setOperationAction(ISD::FDIV, VT, Expand);
679     setOperationAction(ISD::SREM, VT, Expand);
680     setOperationAction(ISD::UREM, VT, Expand);
681     setOperationAction(ISD::LOAD, VT, Expand);
682     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
683     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
684     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
685     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
686     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
687     setOperationAction(ISD::FABS, VT, Expand);
688     setOperationAction(ISD::FSIN, VT, Expand);
689     setOperationAction(ISD::FSINCOS, VT, Expand);
690     setOperationAction(ISD::FCOS, VT, Expand);
691     setOperationAction(ISD::FSINCOS, VT, Expand);
692     setOperationAction(ISD::FREM, VT, Expand);
693     setOperationAction(ISD::FMA,  VT, Expand);
694     setOperationAction(ISD::FPOWI, VT, Expand);
695     setOperationAction(ISD::FSQRT, VT, Expand);
696     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
697     setOperationAction(ISD::FFLOOR, VT, Expand);
698     setOperationAction(ISD::FCEIL, VT, Expand);
699     setOperationAction(ISD::FTRUNC, VT, Expand);
700     setOperationAction(ISD::FRINT, VT, Expand);
701     setOperationAction(ISD::FNEARBYINT, VT, Expand);
702     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
703     setOperationAction(ISD::MULHS, VT, Expand);
704     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
705     setOperationAction(ISD::MULHU, VT, Expand);
706     setOperationAction(ISD::SDIVREM, VT, Expand);
707     setOperationAction(ISD::UDIVREM, VT, Expand);
708     setOperationAction(ISD::FPOW, VT, Expand);
709     setOperationAction(ISD::CTPOP, VT, Expand);
710     setOperationAction(ISD::CTTZ, VT, Expand);
711     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
712     setOperationAction(ISD::CTLZ, VT, Expand);
713     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
714     setOperationAction(ISD::SHL, VT, Expand);
715     setOperationAction(ISD::SRA, VT, Expand);
716     setOperationAction(ISD::SRL, VT, Expand);
717     setOperationAction(ISD::ROTL, VT, Expand);
718     setOperationAction(ISD::ROTR, VT, Expand);
719     setOperationAction(ISD::BSWAP, VT, Expand);
720     setOperationAction(ISD::SETCC, VT, Expand);
721     setOperationAction(ISD::FLOG, VT, Expand);
722     setOperationAction(ISD::FLOG2, VT, Expand);
723     setOperationAction(ISD::FLOG10, VT, Expand);
724     setOperationAction(ISD::FEXP, VT, Expand);
725     setOperationAction(ISD::FEXP2, VT, Expand);
726     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
727     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
728     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
729     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
730     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
731     setOperationAction(ISD::TRUNCATE, VT, Expand);
732     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
733     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
734     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
735     setOperationAction(ISD::VSELECT, VT, Expand);
736     setOperationAction(ISD::SELECT_CC, VT, Expand);
737     for (MVT InnerVT : MVT::vector_valuetypes()) {
738       setTruncStoreAction(InnerVT, VT, Expand);
739
740       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
741       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
742
743       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
744       // types, we have to deal with them whether we ask for Expansion or not.
745       // Setting Expand causes its own optimisation problems though, so leave
746       // them legal.
747       if (VT.getVectorElementType() == MVT::i1)
748         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
749
750       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
751       // split/scalarized right now.
752       if (VT.getVectorElementType() == MVT::f16)
753         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
754     }
755   }
756
757   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
758   // with -msoft-float, disable use of MMX as well.
759   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
760     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
761     // No operations on x86mmx supported, everything uses intrinsics.
762   }
763
764   // MMX-sized vectors (other than x86mmx) are expected to be expanded
765   // into smaller operations.
766   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
767     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
768     setOperationAction(ISD::AND,                MMXTy,      Expand);
769     setOperationAction(ISD::OR,                 MMXTy,      Expand);
770     setOperationAction(ISD::XOR,                MMXTy,      Expand);
771     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
772     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
773     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
774   }
775   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
776
777   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
778     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
779
780     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
781     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
783     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
784     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
785     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
786     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
787     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
788     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
789     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
790     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
791     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
792     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
793     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
794   }
795
796   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
797     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
798
799     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
800     // registers cannot be used even for integer operations.
801     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
802     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
803     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
804     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
805
806     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
807     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
808     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
809     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
810     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
811     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
812     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
813     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
814     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
815     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
816     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
817     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
818     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
819     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
820     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
821     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
822     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
825     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
826     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
827     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
828     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
829
830     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
831     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
832     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
833     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
834
835     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
837     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
838     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
839
840     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
841     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
843     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
844     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
845
846     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
847     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
848     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
849     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
850
851     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
852     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
853       MVT VT = (MVT::SimpleValueType)i;
854       // Do not attempt to custom lower non-power-of-2 vectors
855       if (!isPowerOf2_32(VT.getVectorNumElements()))
856         continue;
857       // Do not attempt to custom lower non-128-bit vectors
858       if (!VT.is128BitVector())
859         continue;
860       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
861       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
862       setOperationAction(ISD::VSELECT,            VT, Custom);
863       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
864     }
865
866     // We support custom legalizing of sext and anyext loads for specific
867     // memory vector types which we can load as a scalar (or sequence of
868     // scalars) and extend in-register to a legal 128-bit vector type. For sext
869     // loads these must work with a single scalar load.
870     for (MVT VT : MVT::integer_vector_valuetypes()) {
871       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
872       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
873       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
874       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
875       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
878       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
879       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
880     }
881
882     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
883     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
884     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
885     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
886     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
887     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
888     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
889     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
890
891     if (Subtarget->is64Bit()) {
892       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
893       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
894     }
895
896     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
897     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
898       MVT VT = (MVT::SimpleValueType)i;
899
900       // Do not attempt to promote non-128-bit vectors
901       if (!VT.is128BitVector())
902         continue;
903
904       setOperationAction(ISD::AND,    VT, Promote);
905       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
906       setOperationAction(ISD::OR,     VT, Promote);
907       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
908       setOperationAction(ISD::XOR,    VT, Promote);
909       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
910       setOperationAction(ISD::LOAD,   VT, Promote);
911       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
912       setOperationAction(ISD::SELECT, VT, Promote);
913       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
914     }
915
916     // Custom lower v2i64 and v2f64 selects.
917     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
918     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
919     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
920     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
921
922     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
923     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
924
925     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
926
927     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
928     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
929     // As there is no 64-bit GPR available, we need build a special custom
930     // sequence to convert from v2i32 to v2f32.
931     if (!Subtarget->is64Bit())
932       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
933
934     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
935     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
936
937     for (MVT VT : MVT::fp_vector_valuetypes())
938       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
939
940     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
941     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
942     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
943   }
944
945   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
946     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
947       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
948       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
949       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
950       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
951       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
952     }
953
954     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
955     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
956     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
957     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
958     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
959     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
960     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
961     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
962
963     // FIXME: Do we need to handle scalar-to-vector here?
964     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
965
966     // We directly match byte blends in the backend as they match the VSELECT
967     // condition form.
968     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
969
970     // SSE41 brings specific instructions for doing vector sign extend even in
971     // cases where we don't have SRA.
972     for (MVT VT : MVT::integer_vector_valuetypes()) {
973       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
974       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
975       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
976     }
977
978     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
979     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
980     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
981     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
982     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
983     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
984     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
985
986     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
987     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
988     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
989     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
990     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
991     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
992
993     // i8 and i16 vectors are custom because the source register and source
994     // source memory operand types are not the same width.  f32 vectors are
995     // custom since the immediate controlling the insert encodes additional
996     // information.
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
999     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1000     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1001
1002     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1003     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1004     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1005     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1006
1007     // FIXME: these should be Legal, but that's only for the case where
1008     // the index is constant.  For now custom expand to deal with that.
1009     if (Subtarget->is64Bit()) {
1010       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1011       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1012     }
1013   }
1014
1015   if (Subtarget->hasSSE2()) {
1016     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1017     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1018     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1019
1020     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1021     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1022
1023     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1024     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1025
1026     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1027     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1028
1029     // In the customized shift lowering, the legal cases in AVX2 will be
1030     // recognized.
1031     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1032     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1033
1034     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1035     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1036
1037     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1038     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1039   }
1040
1041   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1042     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1043     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1044     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1045     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1046     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1047     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1048
1049     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1050     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1051     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1052
1053     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1054     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1055     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1056     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1057     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1058     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1059     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1060     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1061     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1062     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1063     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1064     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1065
1066     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1067     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1068     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1069     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1070     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1071     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1072     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1073     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1074     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1075     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1076     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1077     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1078
1079     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1080     // even though v8i16 is a legal type.
1081     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1082     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1083     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1084
1085     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1086     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1087     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1088
1089     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1090     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1091
1092     for (MVT VT : MVT::fp_vector_valuetypes())
1093       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1094
1095     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1096     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1097
1098     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1099     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1100
1101     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1102     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1103
1104     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1105     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1106     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1107     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1108
1109     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1110     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1111     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1112
1113     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1114     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1115     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1116     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1117     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1118     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1119     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1120     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1121     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1122     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1123     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1124     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1125
1126     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1127     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1128     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1129     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1130
1131     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1132       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1133       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1134       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1135       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1136       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1137       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1138     }
1139
1140     if (Subtarget->hasInt256()) {
1141       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1142       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1143       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1144       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1145
1146       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1147       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1148       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1149       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1150
1151       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1152       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1153       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1154       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1155
1156       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1157       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1158       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1159       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1160
1161       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1162       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1163       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1164       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1165       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1166       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1167       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1168       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1169       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1170       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1171       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1172       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1173
1174       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1175       // when we have a 256bit-wide blend with immediate.
1176       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1177
1178       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1179       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1180       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1181       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1182       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1183       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1184       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1185
1186       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1187       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1188       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1189       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1190       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1191       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1192     } else {
1193       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1194       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1195       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1196       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1197
1198       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1199       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1200       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1201       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1202
1203       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1204       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1205       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1206       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1207
1208       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1209       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1210       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1211       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1212       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1213       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1214       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1215       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1216       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1217       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1218       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1219       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1220     }
1221
1222     // In the customized shift lowering, the legal cases in AVX2 will be
1223     // recognized.
1224     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1225     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1226
1227     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1228     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1229
1230     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1231     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1232
1233     // Custom lower several nodes for 256-bit types.
1234     for (MVT VT : MVT::vector_valuetypes()) {
1235       if (VT.getScalarSizeInBits() >= 32) {
1236         setOperationAction(ISD::MLOAD,  VT, Legal);
1237         setOperationAction(ISD::MSTORE, VT, Legal);
1238       }
1239       // Extract subvector is special because the value type
1240       // (result) is 128-bit but the source is 256-bit wide.
1241       if (VT.is128BitVector()) {
1242         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1243       }
1244       // Do not attempt to custom lower other non-256-bit vectors
1245       if (!VT.is256BitVector())
1246         continue;
1247
1248       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1249       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1250       setOperationAction(ISD::VSELECT,            VT, Custom);
1251       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1252       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1253       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1254       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1255       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1256     }
1257
1258     if (Subtarget->hasInt256())
1259       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1260
1261
1262     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1263     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1264       MVT VT = (MVT::SimpleValueType)i;
1265
1266       // Do not attempt to promote non-256-bit vectors
1267       if (!VT.is256BitVector())
1268         continue;
1269
1270       setOperationAction(ISD::AND,    VT, Promote);
1271       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1272       setOperationAction(ISD::OR,     VT, Promote);
1273       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1274       setOperationAction(ISD::XOR,    VT, Promote);
1275       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1276       setOperationAction(ISD::LOAD,   VT, Promote);
1277       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1278       setOperationAction(ISD::SELECT, VT, Promote);
1279       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1280     }
1281   }
1282
1283   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1284     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1285     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1286     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1287     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1288
1289     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1290     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1291     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1292
1293     for (MVT VT : MVT::fp_vector_valuetypes())
1294       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1295
1296     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1297     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1298     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1299     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1300     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1301     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1302     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1303     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1304     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1305     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1306     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1307     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1308
1309     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1310     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1311     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1312     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1313     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1314     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1315     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1316     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1317     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1318     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1319     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1320     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1321     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1322
1323     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1324     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1325     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1326     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1327     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1328     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1329
1330     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1331     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1332     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1333     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1334     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1335     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1336     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1337     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1338
1339     // FIXME:  [US]INT_TO_FP are not legal for f80.
1340     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1341     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1342     if (Subtarget->is64Bit()) {
1343       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1344       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1345     }
1346     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1347     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1348     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1349     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1350     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1351     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1352     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1353     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1354     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1355     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1356     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1357     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1358     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1359     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1360     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1361     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1362
1363     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1364     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1365     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1366     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1367     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1368     if (Subtarget->hasVLX()){
1369       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1370       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1371       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1372       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1373       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1374
1375       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1376       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1377       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1378       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1379       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1380     }
1381     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1382     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1383     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1384     if (Subtarget->hasDQI()) {
1385       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1386       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1387
1388       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1389       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1390       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1391       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1392       if (Subtarget->hasVLX()) {
1393         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1394         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1395         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1396         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1397         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1398         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1399         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1400         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1401       }
1402     }
1403     if (Subtarget->hasVLX()) {
1404       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1405       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1406       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1407       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1408       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1409       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1410       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1411       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1412     }
1413     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1414     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1415     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1416     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1417     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1418     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1419     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1420     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1421     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1422     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1423     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1424     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1425     if (Subtarget->hasDQI()) {
1426       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1427       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1428     }
1429     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1430     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1431     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1432     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1433     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1434     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1435     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1436     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1437     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1438     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1439
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1444     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1445
1446     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1447     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1448
1449     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1450
1451     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1452     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1453     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1454     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1455     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1456     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1459     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1460     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1461     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1462
1463     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1464     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1465     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1466     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1467     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1468     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1469     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1470     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1471
1472     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1473     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1474
1475     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1476     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1477
1478     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1479
1480     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1481     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1482
1483     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1484     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1485
1486     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1487     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1488
1489     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1490     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1491     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1492     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1493     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1494     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1495
1496     if (Subtarget->hasCDI()) {
1497       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1498       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1499     }
1500     if (Subtarget->hasDQI()) {
1501       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1502       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1503       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1504     }
1505     // Custom lower several nodes.
1506     for (MVT VT : MVT::vector_valuetypes()) {
1507       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1508       if (EltSize == 1) {
1509         setOperationAction(ISD::AND, VT, Legal);
1510         setOperationAction(ISD::OR,  VT, Legal);
1511         setOperationAction(ISD::XOR,  VT, Legal);
1512       }
1513       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1514         setOperationAction(ISD::MGATHER,  VT, Custom);
1515         setOperationAction(ISD::MSCATTER, VT, Custom);
1516       }
1517       // Extract subvector is special because the value type
1518       // (result) is 256/128-bit but the source is 512-bit wide.
1519       if (VT.is128BitVector() || VT.is256BitVector()) {
1520         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1521       }
1522       if (VT.getVectorElementType() == MVT::i1)
1523         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1524
1525       // Do not attempt to custom lower other non-512-bit vectors
1526       if (!VT.is512BitVector())
1527         continue;
1528
1529       if (EltSize >= 32) {
1530         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1531         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1532         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1533         setOperationAction(ISD::VSELECT,             VT, Legal);
1534         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1535         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1536         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1537         setOperationAction(ISD::MLOAD,               VT, Legal);
1538         setOperationAction(ISD::MSTORE,              VT, Legal);
1539       }
1540     }
1541     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1542       MVT VT = (MVT::SimpleValueType)i;
1543
1544       // Do not attempt to promote non-512-bit vectors.
1545       if (!VT.is512BitVector())
1546         continue;
1547
1548       setOperationAction(ISD::SELECT, VT, Promote);
1549       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1550     }
1551   }// has  AVX-512
1552
1553   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1554     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1555     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1556
1557     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1558     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1559
1560     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1561     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1562     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1563     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1564     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1565     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1566     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1567     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1568     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1569     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1570     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1571     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1572     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1573     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1574     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1575     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1576     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1577     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1578     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1579     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1580     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1581     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1582     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1583     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1584     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1585     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1586     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1587     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1588     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1589     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1590
1591     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1592     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1593     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1594     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1595     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1596     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1597     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1598     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1599
1600     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1601     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1602     if (Subtarget->hasVLX())
1603       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1604
1605     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1606       const MVT VT = (MVT::SimpleValueType)i;
1607
1608       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1609
1610       // Do not attempt to promote non-512-bit vectors.
1611       if (!VT.is512BitVector())
1612         continue;
1613
1614       if (EltSize < 32) {
1615         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1616         setOperationAction(ISD::VSELECT,             VT, Legal);
1617       }
1618     }
1619   }
1620
1621   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1622     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1623     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1624
1625     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1626     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1627     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1628     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1629     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1630     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1631     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1632     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1633     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1634     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1635
1636     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1637     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1638     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1639     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1640     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1641     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1642     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1643     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1644
1645     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1646     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1647     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1648     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1649     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1650     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1651     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1652     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1653   }
1654
1655   // We want to custom lower some of our intrinsics.
1656   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1657   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1658   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1659   if (!Subtarget->is64Bit())
1660     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1661
1662   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1663   // handle type legalization for these operations here.
1664   //
1665   // FIXME: We really should do custom legalization for addition and
1666   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1667   // than generic legalization for 64-bit multiplication-with-overflow, though.
1668   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1669     // Add/Sub/Mul with overflow operations are custom lowered.
1670     MVT VT = IntVTs[i];
1671     setOperationAction(ISD::SADDO, VT, Custom);
1672     setOperationAction(ISD::UADDO, VT, Custom);
1673     setOperationAction(ISD::SSUBO, VT, Custom);
1674     setOperationAction(ISD::USUBO, VT, Custom);
1675     setOperationAction(ISD::SMULO, VT, Custom);
1676     setOperationAction(ISD::UMULO, VT, Custom);
1677   }
1678
1679
1680   if (!Subtarget->is64Bit()) {
1681     // These libcalls are not available in 32-bit.
1682     setLibcallName(RTLIB::SHL_I128, nullptr);
1683     setLibcallName(RTLIB::SRL_I128, nullptr);
1684     setLibcallName(RTLIB::SRA_I128, nullptr);
1685   }
1686
1687   // Combine sin / cos into one node or libcall if possible.
1688   if (Subtarget->hasSinCos()) {
1689     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1690     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1691     if (Subtarget->isTargetDarwin()) {
1692       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1693       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1694       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1695       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1696     }
1697   }
1698
1699   if (Subtarget->isTargetWin64()) {
1700     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1701     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1702     setOperationAction(ISD::SREM, MVT::i128, Custom);
1703     setOperationAction(ISD::UREM, MVT::i128, Custom);
1704     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1705     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1706   }
1707
1708   // We have target-specific dag combine patterns for the following nodes:
1709   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1710   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1711   setTargetDAGCombine(ISD::BITCAST);
1712   setTargetDAGCombine(ISD::VSELECT);
1713   setTargetDAGCombine(ISD::SELECT);
1714   setTargetDAGCombine(ISD::SHL);
1715   setTargetDAGCombine(ISD::SRA);
1716   setTargetDAGCombine(ISD::SRL);
1717   setTargetDAGCombine(ISD::OR);
1718   setTargetDAGCombine(ISD::AND);
1719   setTargetDAGCombine(ISD::ADD);
1720   setTargetDAGCombine(ISD::FADD);
1721   setTargetDAGCombine(ISD::FSUB);
1722   setTargetDAGCombine(ISD::FMA);
1723   setTargetDAGCombine(ISD::SUB);
1724   setTargetDAGCombine(ISD::LOAD);
1725   setTargetDAGCombine(ISD::MLOAD);
1726   setTargetDAGCombine(ISD::STORE);
1727   setTargetDAGCombine(ISD::MSTORE);
1728   setTargetDAGCombine(ISD::ZERO_EXTEND);
1729   setTargetDAGCombine(ISD::ANY_EXTEND);
1730   setTargetDAGCombine(ISD::SIGN_EXTEND);
1731   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1732   setTargetDAGCombine(ISD::SINT_TO_FP);
1733   setTargetDAGCombine(ISD::UINT_TO_FP);
1734   setTargetDAGCombine(ISD::SETCC);
1735   setTargetDAGCombine(ISD::BUILD_VECTOR);
1736   setTargetDAGCombine(ISD::MUL);
1737   setTargetDAGCombine(ISD::XOR);
1738
1739   computeRegisterProperties(Subtarget->getRegisterInfo());
1740
1741   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1742   MaxStoresPerMemsetOptSize = 8;
1743   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1744   MaxStoresPerMemcpyOptSize = 4;
1745   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1746   MaxStoresPerMemmoveOptSize = 4;
1747   setPrefLoopAlignment(4); // 2^4 bytes.
1748
1749   // Predictable cmov don't hurt on atom because it's in-order.
1750   PredictableSelectIsExpensive = !Subtarget->isAtom();
1751   EnableExtLdPromotion = true;
1752   setPrefFunctionAlignment(4); // 2^4 bytes.
1753
1754   verifyIntrinsicTables();
1755 }
1756
1757 // This has so far only been implemented for 64-bit MachO.
1758 bool X86TargetLowering::useLoadStackGuardNode() const {
1759   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1760 }
1761
1762 TargetLoweringBase::LegalizeTypeAction
1763 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1764   if (ExperimentalVectorWideningLegalization &&
1765       VT.getVectorNumElements() != 1 &&
1766       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1767     return TypeWidenVector;
1768
1769   return TargetLoweringBase::getPreferredVectorAction(VT);
1770 }
1771
1772 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1773                                           EVT VT) const {
1774   if (!VT.isVector())
1775     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1776
1777   const unsigned NumElts = VT.getVectorNumElements();
1778   const EVT EltVT = VT.getVectorElementType();
1779   if (VT.is512BitVector()) {
1780     if (Subtarget->hasAVX512())
1781       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1782           EltVT == MVT::f32 || EltVT == MVT::f64)
1783         switch(NumElts) {
1784         case  8: return MVT::v8i1;
1785         case 16: return MVT::v16i1;
1786       }
1787     if (Subtarget->hasBWI())
1788       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1789         switch(NumElts) {
1790         case 32: return MVT::v32i1;
1791         case 64: return MVT::v64i1;
1792       }
1793   }
1794
1795   if (VT.is256BitVector() || VT.is128BitVector()) {
1796     if (Subtarget->hasVLX())
1797       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1798           EltVT == MVT::f32 || EltVT == MVT::f64)
1799         switch(NumElts) {
1800         case 2: return MVT::v2i1;
1801         case 4: return MVT::v4i1;
1802         case 8: return MVT::v8i1;
1803       }
1804     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1805       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1806         switch(NumElts) {
1807         case  8: return MVT::v8i1;
1808         case 16: return MVT::v16i1;
1809         case 32: return MVT::v32i1;
1810       }
1811   }
1812
1813   return VT.changeVectorElementTypeToInteger();
1814 }
1815
1816 /// Helper for getByValTypeAlignment to determine
1817 /// the desired ByVal argument alignment.
1818 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1819   if (MaxAlign == 16)
1820     return;
1821   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1822     if (VTy->getBitWidth() == 128)
1823       MaxAlign = 16;
1824   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1825     unsigned EltAlign = 0;
1826     getMaxByValAlign(ATy->getElementType(), EltAlign);
1827     if (EltAlign > MaxAlign)
1828       MaxAlign = EltAlign;
1829   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1830     for (auto *EltTy : STy->elements()) {
1831       unsigned EltAlign = 0;
1832       getMaxByValAlign(EltTy, EltAlign);
1833       if (EltAlign > MaxAlign)
1834         MaxAlign = EltAlign;
1835       if (MaxAlign == 16)
1836         break;
1837     }
1838   }
1839 }
1840
1841 /// Return the desired alignment for ByVal aggregate
1842 /// function arguments in the caller parameter area. For X86, aggregates
1843 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1844 /// are at 4-byte boundaries.
1845 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1846                                                   const DataLayout &DL) const {
1847   if (Subtarget->is64Bit()) {
1848     // Max of 8 and alignment of type.
1849     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1850     if (TyAlign > 8)
1851       return TyAlign;
1852     return 8;
1853   }
1854
1855   unsigned Align = 4;
1856   if (Subtarget->hasSSE1())
1857     getMaxByValAlign(Ty, Align);
1858   return Align;
1859 }
1860
1861 /// Returns the target specific optimal type for load
1862 /// and store operations as a result of memset, memcpy, and memmove
1863 /// lowering. If DstAlign is zero that means it's safe to destination
1864 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1865 /// means there isn't a need to check it against alignment requirement,
1866 /// probably because the source does not need to be loaded. If 'IsMemset' is
1867 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1868 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1869 /// source is constant so it does not need to be loaded.
1870 /// It returns EVT::Other if the type should be determined using generic
1871 /// target-independent logic.
1872 EVT
1873 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1874                                        unsigned DstAlign, unsigned SrcAlign,
1875                                        bool IsMemset, bool ZeroMemset,
1876                                        bool MemcpyStrSrc,
1877                                        MachineFunction &MF) const {
1878   const Function *F = MF.getFunction();
1879   if ((!IsMemset || ZeroMemset) &&
1880       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1881     if (Size >= 16 &&
1882         (!Subtarget->isUnalignedMem16Slow() ||
1883          ((DstAlign == 0 || DstAlign >= 16) &&
1884           (SrcAlign == 0 || SrcAlign >= 16)))) {
1885       if (Size >= 32) {
1886         // FIXME: Check if unaligned 32-byte accesses are slow.
1887         if (Subtarget->hasInt256())
1888           return MVT::v8i32;
1889         if (Subtarget->hasFp256())
1890           return MVT::v8f32;
1891       }
1892       if (Subtarget->hasSSE2())
1893         return MVT::v4i32;
1894       if (Subtarget->hasSSE1())
1895         return MVT::v4f32;
1896     } else if (!MemcpyStrSrc && Size >= 8 &&
1897                !Subtarget->is64Bit() &&
1898                Subtarget->hasSSE2()) {
1899       // Do not use f64 to lower memcpy if source is string constant. It's
1900       // better to use i32 to avoid the loads.
1901       return MVT::f64;
1902     }
1903   }
1904   // This is a compromise. If we reach here, unaligned accesses may be slow on
1905   // this target. However, creating smaller, aligned accesses could be even
1906   // slower and would certainly be a lot more code.
1907   if (Subtarget->is64Bit() && Size >= 8)
1908     return MVT::i64;
1909   return MVT::i32;
1910 }
1911
1912 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1913   if (VT == MVT::f32)
1914     return X86ScalarSSEf32;
1915   else if (VT == MVT::f64)
1916     return X86ScalarSSEf64;
1917   return true;
1918 }
1919
1920 bool
1921 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1922                                                   unsigned,
1923                                                   unsigned,
1924                                                   bool *Fast) const {
1925   if (Fast) {
1926     if (VT.getSizeInBits() == 256)
1927       *Fast = !Subtarget->isUnalignedMem32Slow();
1928     else
1929       // FIXME: We should always return that 8-byte and under accesses are fast.
1930       // That is what other x86 lowering code assumes.
1931       *Fast = !Subtarget->isUnalignedMem16Slow();
1932   }
1933   return true;
1934 }
1935
1936 /// Return the entry encoding for a jump table in the
1937 /// current function.  The returned value is a member of the
1938 /// MachineJumpTableInfo::JTEntryKind enum.
1939 unsigned X86TargetLowering::getJumpTableEncoding() const {
1940   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1941   // symbol.
1942   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1943       Subtarget->isPICStyleGOT())
1944     return MachineJumpTableInfo::EK_Custom32;
1945
1946   // Otherwise, use the normal jump table encoding heuristics.
1947   return TargetLowering::getJumpTableEncoding();
1948 }
1949
1950 bool X86TargetLowering::useSoftFloat() const {
1951   return Subtarget->useSoftFloat();
1952 }
1953
1954 const MCExpr *
1955 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1956                                              const MachineBasicBlock *MBB,
1957                                              unsigned uid,MCContext &Ctx) const{
1958   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1959          Subtarget->isPICStyleGOT());
1960   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1961   // entries.
1962   return MCSymbolRefExpr::create(MBB->getSymbol(),
1963                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1964 }
1965
1966 /// Returns relocation base for the given PIC jumptable.
1967 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1968                                                     SelectionDAG &DAG) const {
1969   if (!Subtarget->is64Bit())
1970     // This doesn't have SDLoc associated with it, but is not really the
1971     // same as a Register.
1972     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1973                        getPointerTy(DAG.getDataLayout()));
1974   return Table;
1975 }
1976
1977 /// This returns the relocation base for the given PIC jumptable,
1978 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1979 const MCExpr *X86TargetLowering::
1980 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1981                              MCContext &Ctx) const {
1982   // X86-64 uses RIP relative addressing based on the jump table label.
1983   if (Subtarget->isPICStyleRIPRel())
1984     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1985
1986   // Otherwise, the reference is relative to the PIC base.
1987   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1988 }
1989
1990 std::pair<const TargetRegisterClass *, uint8_t>
1991 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1992                                            MVT VT) const {
1993   const TargetRegisterClass *RRC = nullptr;
1994   uint8_t Cost = 1;
1995   switch (VT.SimpleTy) {
1996   default:
1997     return TargetLowering::findRepresentativeClass(TRI, VT);
1998   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1999     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2000     break;
2001   case MVT::x86mmx:
2002     RRC = &X86::VR64RegClass;
2003     break;
2004   case MVT::f32: case MVT::f64:
2005   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2006   case MVT::v4f32: case MVT::v2f64:
2007   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2008   case MVT::v4f64:
2009     RRC = &X86::VR128RegClass;
2010     break;
2011   }
2012   return std::make_pair(RRC, Cost);
2013 }
2014
2015 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2016                                                unsigned &Offset) const {
2017   if (!Subtarget->isTargetLinux())
2018     return false;
2019
2020   if (Subtarget->is64Bit()) {
2021     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2022     Offset = 0x28;
2023     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2024       AddressSpace = 256;
2025     else
2026       AddressSpace = 257;
2027   } else {
2028     // %gs:0x14 on i386
2029     Offset = 0x14;
2030     AddressSpace = 256;
2031   }
2032   return true;
2033 }
2034
2035 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2036                                             unsigned DestAS) const {
2037   assert(SrcAS != DestAS && "Expected different address spaces!");
2038
2039   return SrcAS < 256 && DestAS < 256;
2040 }
2041
2042 //===----------------------------------------------------------------------===//
2043 //               Return Value Calling Convention Implementation
2044 //===----------------------------------------------------------------------===//
2045
2046 #include "X86GenCallingConv.inc"
2047
2048 bool
2049 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2050                                   MachineFunction &MF, bool isVarArg,
2051                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2052                         LLVMContext &Context) const {
2053   SmallVector<CCValAssign, 16> RVLocs;
2054   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2055   return CCInfo.CheckReturn(Outs, RetCC_X86);
2056 }
2057
2058 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2059   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2060   return ScratchRegs;
2061 }
2062
2063 SDValue
2064 X86TargetLowering::LowerReturn(SDValue Chain,
2065                                CallingConv::ID CallConv, bool isVarArg,
2066                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2067                                const SmallVectorImpl<SDValue> &OutVals,
2068                                SDLoc dl, SelectionDAG &DAG) const {
2069   MachineFunction &MF = DAG.getMachineFunction();
2070   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2071
2072   SmallVector<CCValAssign, 16> RVLocs;
2073   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2074   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2075
2076   SDValue Flag;
2077   SmallVector<SDValue, 6> RetOps;
2078   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2079   // Operand #1 = Bytes To Pop
2080   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2081                    MVT::i16));
2082
2083   // Copy the result values into the output registers.
2084   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2085     CCValAssign &VA = RVLocs[i];
2086     assert(VA.isRegLoc() && "Can only return in registers!");
2087     SDValue ValToCopy = OutVals[i];
2088     EVT ValVT = ValToCopy.getValueType();
2089
2090     // Promote values to the appropriate types.
2091     if (VA.getLocInfo() == CCValAssign::SExt)
2092       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2093     else if (VA.getLocInfo() == CCValAssign::ZExt)
2094       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2095     else if (VA.getLocInfo() == CCValAssign::AExt) {
2096       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2097         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2098       else
2099         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2100     }
2101     else if (VA.getLocInfo() == CCValAssign::BCvt)
2102       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2103
2104     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2105            "Unexpected FP-extend for return value.");
2106
2107     // If this is x86-64, and we disabled SSE, we can't return FP values,
2108     // or SSE or MMX vectors.
2109     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2110          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2111           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2112       report_fatal_error("SSE register return with SSE disabled");
2113     }
2114     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2115     // llvm-gcc has never done it right and no one has noticed, so this
2116     // should be OK for now.
2117     if (ValVT == MVT::f64 &&
2118         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2119       report_fatal_error("SSE2 register return with SSE2 disabled");
2120
2121     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2122     // the RET instruction and handled by the FP Stackifier.
2123     if (VA.getLocReg() == X86::FP0 ||
2124         VA.getLocReg() == X86::FP1) {
2125       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2126       // change the value to the FP stack register class.
2127       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2128         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2129       RetOps.push_back(ValToCopy);
2130       // Don't emit a copytoreg.
2131       continue;
2132     }
2133
2134     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2135     // which is returned in RAX / RDX.
2136     if (Subtarget->is64Bit()) {
2137       if (ValVT == MVT::x86mmx) {
2138         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2139           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2140           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2141                                   ValToCopy);
2142           // If we don't have SSE2 available, convert to v4f32 so the generated
2143           // register is legal.
2144           if (!Subtarget->hasSSE2())
2145             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2146         }
2147       }
2148     }
2149
2150     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2151     Flag = Chain.getValue(1);
2152     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2153   }
2154
2155   // All x86 ABIs require that for returning structs by value we copy
2156   // the sret argument into %rax/%eax (depending on ABI) for the return.
2157   // We saved the argument into a virtual register in the entry block,
2158   // so now we copy the value out and into %rax/%eax.
2159   //
2160   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2161   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2162   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2163   // either case FuncInfo->setSRetReturnReg() will have been called.
2164   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2165     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2166                                      getPointerTy(MF.getDataLayout()));
2167
2168     unsigned RetValReg
2169         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2170           X86::RAX : X86::EAX;
2171     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2172     Flag = Chain.getValue(1);
2173
2174     // RAX/EAX now acts like a return value.
2175     RetOps.push_back(
2176         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2177   }
2178
2179   RetOps[0] = Chain;  // Update chain.
2180
2181   // Add the flag if we have it.
2182   if (Flag.getNode())
2183     RetOps.push_back(Flag);
2184
2185   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2186 }
2187
2188 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2189   if (N->getNumValues() != 1)
2190     return false;
2191   if (!N->hasNUsesOfValue(1, 0))
2192     return false;
2193
2194   SDValue TCChain = Chain;
2195   SDNode *Copy = *N->use_begin();
2196   if (Copy->getOpcode() == ISD::CopyToReg) {
2197     // If the copy has a glue operand, we conservatively assume it isn't safe to
2198     // perform a tail call.
2199     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2200       return false;
2201     TCChain = Copy->getOperand(0);
2202   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2203     return false;
2204
2205   bool HasRet = false;
2206   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2207        UI != UE; ++UI) {
2208     if (UI->getOpcode() != X86ISD::RET_FLAG)
2209       return false;
2210     // If we are returning more than one value, we can definitely
2211     // not make a tail call see PR19530
2212     if (UI->getNumOperands() > 4)
2213       return false;
2214     if (UI->getNumOperands() == 4 &&
2215         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2216       return false;
2217     HasRet = true;
2218   }
2219
2220   if (!HasRet)
2221     return false;
2222
2223   Chain = TCChain;
2224   return true;
2225 }
2226
2227 EVT
2228 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2229                                             ISD::NodeType ExtendKind) const {
2230   MVT ReturnMVT;
2231   // TODO: Is this also valid on 32-bit?
2232   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2233     ReturnMVT = MVT::i8;
2234   else
2235     ReturnMVT = MVT::i32;
2236
2237   EVT MinVT = getRegisterType(Context, ReturnMVT);
2238   return VT.bitsLT(MinVT) ? MinVT : VT;
2239 }
2240
2241 /// Lower the result values of a call into the
2242 /// appropriate copies out of appropriate physical registers.
2243 ///
2244 SDValue
2245 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2246                                    CallingConv::ID CallConv, bool isVarArg,
2247                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2248                                    SDLoc dl, SelectionDAG &DAG,
2249                                    SmallVectorImpl<SDValue> &InVals) const {
2250
2251   // Assign locations to each value returned by this call.
2252   SmallVector<CCValAssign, 16> RVLocs;
2253   bool Is64Bit = Subtarget->is64Bit();
2254   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2255                  *DAG.getContext());
2256   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2257
2258   // Copy all of the result registers out of their specified physreg.
2259   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2260     CCValAssign &VA = RVLocs[i];
2261     EVT CopyVT = VA.getLocVT();
2262
2263     // If this is x86-64, and we disabled SSE, we can't return FP values
2264     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2265         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2266       report_fatal_error("SSE register return with SSE disabled");
2267     }
2268
2269     // If we prefer to use the value in xmm registers, copy it out as f80 and
2270     // use a truncate to move it from fp stack reg to xmm reg.
2271     bool RoundAfterCopy = false;
2272     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2273         isScalarFPTypeInSSEReg(VA.getValVT())) {
2274       CopyVT = MVT::f80;
2275       RoundAfterCopy = (CopyVT != VA.getLocVT());
2276     }
2277
2278     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2279                                CopyVT, InFlag).getValue(1);
2280     SDValue Val = Chain.getValue(0);
2281
2282     if (RoundAfterCopy)
2283       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2284                         // This truncation won't change the value.
2285                         DAG.getIntPtrConstant(1, dl));
2286
2287     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2288       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2289
2290     InFlag = Chain.getValue(2);
2291     InVals.push_back(Val);
2292   }
2293
2294   return Chain;
2295 }
2296
2297 //===----------------------------------------------------------------------===//
2298 //                C & StdCall & Fast Calling Convention implementation
2299 //===----------------------------------------------------------------------===//
2300 //  StdCall calling convention seems to be standard for many Windows' API
2301 //  routines and around. It differs from C calling convention just a little:
2302 //  callee should clean up the stack, not caller. Symbols should be also
2303 //  decorated in some fancy way :) It doesn't support any vector arguments.
2304 //  For info on fast calling convention see Fast Calling Convention (tail call)
2305 //  implementation LowerX86_32FastCCCallTo.
2306
2307 /// CallIsStructReturn - Determines whether a call uses struct return
2308 /// semantics.
2309 enum StructReturnType {
2310   NotStructReturn,
2311   RegStructReturn,
2312   StackStructReturn
2313 };
2314 static StructReturnType
2315 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2316   if (Outs.empty())
2317     return NotStructReturn;
2318
2319   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2320   if (!Flags.isSRet())
2321     return NotStructReturn;
2322   if (Flags.isInReg())
2323     return RegStructReturn;
2324   return StackStructReturn;
2325 }
2326
2327 /// Determines whether a function uses struct return semantics.
2328 static StructReturnType
2329 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2330   if (Ins.empty())
2331     return NotStructReturn;
2332
2333   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2334   if (!Flags.isSRet())
2335     return NotStructReturn;
2336   if (Flags.isInReg())
2337     return RegStructReturn;
2338   return StackStructReturn;
2339 }
2340
2341 /// Make a copy of an aggregate at address specified by "Src" to address
2342 /// "Dst" with size and alignment information specified by the specific
2343 /// parameter attribute. The copy will be passed as a byval function parameter.
2344 static SDValue
2345 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2346                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2347                           SDLoc dl) {
2348   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2349
2350   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2351                        /*isVolatile*/false, /*AlwaysInline=*/true,
2352                        /*isTailCall*/false,
2353                        MachinePointerInfo(), MachinePointerInfo());
2354 }
2355
2356 /// Return true if the calling convention is one that
2357 /// supports tail call optimization.
2358 static bool IsTailCallConvention(CallingConv::ID CC) {
2359   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2360           CC == CallingConv::HiPE);
2361 }
2362
2363 /// \brief Return true if the calling convention is a C calling convention.
2364 static bool IsCCallConvention(CallingConv::ID CC) {
2365   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2366           CC == CallingConv::X86_64_SysV);
2367 }
2368
2369 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2370   auto Attr =
2371       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2372   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2373     return false;
2374
2375   CallSite CS(CI);
2376   CallingConv::ID CalleeCC = CS.getCallingConv();
2377   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2378     return false;
2379
2380   return true;
2381 }
2382
2383 /// Return true if the function is being made into
2384 /// a tailcall target by changing its ABI.
2385 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2386                                    bool GuaranteedTailCallOpt) {
2387   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2388 }
2389
2390 SDValue
2391 X86TargetLowering::LowerMemArgument(SDValue Chain,
2392                                     CallingConv::ID CallConv,
2393                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2394                                     SDLoc dl, SelectionDAG &DAG,
2395                                     const CCValAssign &VA,
2396                                     MachineFrameInfo *MFI,
2397                                     unsigned i) const {
2398   // Create the nodes corresponding to a load from this parameter slot.
2399   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2400   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2401       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2402   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2403   EVT ValVT;
2404
2405   // If value is passed by pointer we have address passed instead of the value
2406   // itself.
2407   bool ExtendedInMem = VA.isExtInLoc() &&
2408     VA.getValVT().getScalarType() == MVT::i1;
2409
2410   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2411     ValVT = VA.getLocVT();
2412   else
2413     ValVT = VA.getValVT();
2414
2415   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2416   // changed with more analysis.
2417   // In case of tail call optimization mark all arguments mutable. Since they
2418   // could be overwritten by lowering of arguments in case of a tail call.
2419   if (Flags.isByVal()) {
2420     unsigned Bytes = Flags.getByValSize();
2421     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2422     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2423     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2424   } else {
2425     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2426                                     VA.getLocMemOffset(), isImmutable);
2427     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2428     SDValue Val = DAG.getLoad(
2429         ValVT, dl, Chain, FIN,
2430         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2431         false, false, 0);
2432     return ExtendedInMem ?
2433       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2434   }
2435 }
2436
2437 // FIXME: Get this from tablegen.
2438 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2439                                                 const X86Subtarget *Subtarget) {
2440   assert(Subtarget->is64Bit());
2441
2442   if (Subtarget->isCallingConvWin64(CallConv)) {
2443     static const MCPhysReg GPR64ArgRegsWin64[] = {
2444       X86::RCX, X86::RDX, X86::R8,  X86::R9
2445     };
2446     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2447   }
2448
2449   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2450     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2451   };
2452   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2453 }
2454
2455 // FIXME: Get this from tablegen.
2456 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2457                                                 CallingConv::ID CallConv,
2458                                                 const X86Subtarget *Subtarget) {
2459   assert(Subtarget->is64Bit());
2460   if (Subtarget->isCallingConvWin64(CallConv)) {
2461     // The XMM registers which might contain var arg parameters are shadowed
2462     // in their paired GPR.  So we only need to save the GPR to their home
2463     // slots.
2464     // TODO: __vectorcall will change this.
2465     return None;
2466   }
2467
2468   const Function *Fn = MF.getFunction();
2469   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2470   bool isSoftFloat = Subtarget->useSoftFloat();
2471   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2472          "SSE register cannot be used when SSE is disabled!");
2473   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2474     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2475     // registers.
2476     return None;
2477
2478   static const MCPhysReg XMMArgRegs64Bit[] = {
2479     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2480     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2481   };
2482   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2483 }
2484
2485 SDValue
2486 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2487                                         CallingConv::ID CallConv,
2488                                         bool isVarArg,
2489                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2490                                         SDLoc dl,
2491                                         SelectionDAG &DAG,
2492                                         SmallVectorImpl<SDValue> &InVals)
2493                                           const {
2494   MachineFunction &MF = DAG.getMachineFunction();
2495   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2496   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2497
2498   const Function* Fn = MF.getFunction();
2499   if (Fn->hasExternalLinkage() &&
2500       Subtarget->isTargetCygMing() &&
2501       Fn->getName() == "main")
2502     FuncInfo->setForceFramePointer(true);
2503
2504   MachineFrameInfo *MFI = MF.getFrameInfo();
2505   bool Is64Bit = Subtarget->is64Bit();
2506   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2507
2508   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2509          "Var args not supported with calling convention fastcc, ghc or hipe");
2510
2511   // Assign locations to all of the incoming arguments.
2512   SmallVector<CCValAssign, 16> ArgLocs;
2513   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2514
2515   // Allocate shadow area for Win64
2516   if (IsWin64)
2517     CCInfo.AllocateStack(32, 8);
2518
2519   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2520
2521   unsigned LastVal = ~0U;
2522   SDValue ArgValue;
2523   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2524     CCValAssign &VA = ArgLocs[i];
2525     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2526     // places.
2527     assert(VA.getValNo() != LastVal &&
2528            "Don't support value assigned to multiple locs yet");
2529     (void)LastVal;
2530     LastVal = VA.getValNo();
2531
2532     if (VA.isRegLoc()) {
2533       EVT RegVT = VA.getLocVT();
2534       const TargetRegisterClass *RC;
2535       if (RegVT == MVT::i32)
2536         RC = &X86::GR32RegClass;
2537       else if (Is64Bit && RegVT == MVT::i64)
2538         RC = &X86::GR64RegClass;
2539       else if (RegVT == MVT::f32)
2540         RC = &X86::FR32RegClass;
2541       else if (RegVT == MVT::f64)
2542         RC = &X86::FR64RegClass;
2543       else if (RegVT.is512BitVector())
2544         RC = &X86::VR512RegClass;
2545       else if (RegVT.is256BitVector())
2546         RC = &X86::VR256RegClass;
2547       else if (RegVT.is128BitVector())
2548         RC = &X86::VR128RegClass;
2549       else if (RegVT == MVT::x86mmx)
2550         RC = &X86::VR64RegClass;
2551       else if (RegVT == MVT::i1)
2552         RC = &X86::VK1RegClass;
2553       else if (RegVT == MVT::v8i1)
2554         RC = &X86::VK8RegClass;
2555       else if (RegVT == MVT::v16i1)
2556         RC = &X86::VK16RegClass;
2557       else if (RegVT == MVT::v32i1)
2558         RC = &X86::VK32RegClass;
2559       else if (RegVT == MVT::v64i1)
2560         RC = &X86::VK64RegClass;
2561       else
2562         llvm_unreachable("Unknown argument type!");
2563
2564       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2565       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2566
2567       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2568       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2569       // right size.
2570       if (VA.getLocInfo() == CCValAssign::SExt)
2571         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2572                                DAG.getValueType(VA.getValVT()));
2573       else if (VA.getLocInfo() == CCValAssign::ZExt)
2574         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2575                                DAG.getValueType(VA.getValVT()));
2576       else if (VA.getLocInfo() == CCValAssign::BCvt)
2577         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2578
2579       if (VA.isExtInLoc()) {
2580         // Handle MMX values passed in XMM regs.
2581         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2582           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2583         else
2584           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2585       }
2586     } else {
2587       assert(VA.isMemLoc());
2588       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2589     }
2590
2591     // If value is passed via pointer - do a load.
2592     if (VA.getLocInfo() == CCValAssign::Indirect)
2593       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2594                              MachinePointerInfo(), false, false, false, 0);
2595
2596     InVals.push_back(ArgValue);
2597   }
2598
2599   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2600     // All x86 ABIs require that for returning structs by value we copy the
2601     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2602     // the argument into a virtual register so that we can access it from the
2603     // return points.
2604     if (Ins[i].Flags.isSRet()) {
2605       unsigned Reg = FuncInfo->getSRetReturnReg();
2606       if (!Reg) {
2607         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2608         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2609         FuncInfo->setSRetReturnReg(Reg);
2610       }
2611       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2612       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2613       break;
2614     }
2615   }
2616
2617   unsigned StackSize = CCInfo.getNextStackOffset();
2618   // Align stack specially for tail calls.
2619   if (FuncIsMadeTailCallSafe(CallConv,
2620                              MF.getTarget().Options.GuaranteedTailCallOpt))
2621     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2622
2623   // If the function takes variable number of arguments, make a frame index for
2624   // the start of the first vararg value... for expansion of llvm.va_start. We
2625   // can skip this if there are no va_start calls.
2626   if (MFI->hasVAStart() &&
2627       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2628                    CallConv != CallingConv::X86_ThisCall))) {
2629     FuncInfo->setVarArgsFrameIndex(
2630         MFI->CreateFixedObject(1, StackSize, true));
2631   }
2632
2633   MachineModuleInfo &MMI = MF.getMMI();
2634   const Function *WinEHParent = nullptr;
2635   if (MMI.hasWinEHFuncInfo(Fn))
2636     WinEHParent = MMI.getWinEHParent(Fn);
2637   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2638   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2639
2640   // Figure out if XMM registers are in use.
2641   assert(!(Subtarget->useSoftFloat() &&
2642            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2643          "SSE register cannot be used when SSE is disabled!");
2644
2645   // 64-bit calling conventions support varargs and register parameters, so we
2646   // have to do extra work to spill them in the prologue.
2647   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2648     // Find the first unallocated argument registers.
2649     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2650     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2651     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2652     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2653     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2654            "SSE register cannot be used when SSE is disabled!");
2655
2656     // Gather all the live in physical registers.
2657     SmallVector<SDValue, 6> LiveGPRs;
2658     SmallVector<SDValue, 8> LiveXMMRegs;
2659     SDValue ALVal;
2660     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2661       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2662       LiveGPRs.push_back(
2663           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2664     }
2665     if (!ArgXMMs.empty()) {
2666       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2667       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2668       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2669         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2670         LiveXMMRegs.push_back(
2671             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2672       }
2673     }
2674
2675     if (IsWin64) {
2676       // Get to the caller-allocated home save location.  Add 8 to account
2677       // for the return address.
2678       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2679       FuncInfo->setRegSaveFrameIndex(
2680           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2681       // Fixup to set vararg frame on shadow area (4 x i64).
2682       if (NumIntRegs < 4)
2683         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2684     } else {
2685       // For X86-64, if there are vararg parameters that are passed via
2686       // registers, then we must store them to their spots on the stack so
2687       // they may be loaded by deferencing the result of va_next.
2688       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2689       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2690       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2691           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2692     }
2693
2694     // Store the integer parameter registers.
2695     SmallVector<SDValue, 8> MemOps;
2696     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2697                                       getPointerTy(DAG.getDataLayout()));
2698     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2699     for (SDValue Val : LiveGPRs) {
2700       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2701                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2702       SDValue Store =
2703           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2704                        MachinePointerInfo::getFixedStack(
2705                            DAG.getMachineFunction(),
2706                            FuncInfo->getRegSaveFrameIndex(), Offset),
2707                        false, false, 0);
2708       MemOps.push_back(Store);
2709       Offset += 8;
2710     }
2711
2712     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2713       // Now store the XMM (fp + vector) parameter registers.
2714       SmallVector<SDValue, 12> SaveXMMOps;
2715       SaveXMMOps.push_back(Chain);
2716       SaveXMMOps.push_back(ALVal);
2717       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2718                              FuncInfo->getRegSaveFrameIndex(), dl));
2719       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2720                              FuncInfo->getVarArgsFPOffset(), dl));
2721       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2722                         LiveXMMRegs.end());
2723       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2724                                    MVT::Other, SaveXMMOps));
2725     }
2726
2727     if (!MemOps.empty())
2728       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2729   } else if (IsWin64 && IsWinEHOutlined) {
2730     // Get to the caller-allocated home save location.  Add 8 to account
2731     // for the return address.
2732     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2733     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2734         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2735
2736     MMI.getWinEHFuncInfo(Fn)
2737         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2738         FuncInfo->getRegSaveFrameIndex();
2739
2740     // Store the second integer parameter (rdx) into rsp+16 relative to the
2741     // stack pointer at the entry of the function.
2742     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2743                                       getPointerTy(DAG.getDataLayout()));
2744     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2745     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2746     Chain = DAG.getStore(
2747         Val.getValue(1), dl, Val, RSFIN,
2748         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2749                                           FuncInfo->getRegSaveFrameIndex()),
2750         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2751   }
2752
2753   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2754     // Find the largest legal vector type.
2755     MVT VecVT = MVT::Other;
2756     // FIXME: Only some x86_32 calling conventions support AVX512.
2757     if (Subtarget->hasAVX512() &&
2758         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2759                      CallConv == CallingConv::Intel_OCL_BI)))
2760       VecVT = MVT::v16f32;
2761     else if (Subtarget->hasAVX())
2762       VecVT = MVT::v8f32;
2763     else if (Subtarget->hasSSE2())
2764       VecVT = MVT::v4f32;
2765
2766     // We forward some GPRs and some vector types.
2767     SmallVector<MVT, 2> RegParmTypes;
2768     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2769     RegParmTypes.push_back(IntVT);
2770     if (VecVT != MVT::Other)
2771       RegParmTypes.push_back(VecVT);
2772
2773     // Compute the set of forwarded registers. The rest are scratch.
2774     SmallVectorImpl<ForwardedRegister> &Forwards =
2775         FuncInfo->getForwardedMustTailRegParms();
2776     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2777
2778     // Conservatively forward AL on x86_64, since it might be used for varargs.
2779     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2780       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2781       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2782     }
2783
2784     // Copy all forwards from physical to virtual registers.
2785     for (ForwardedRegister &F : Forwards) {
2786       // FIXME: Can we use a less constrained schedule?
2787       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2788       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2789       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2790     }
2791   }
2792
2793   // Some CCs need callee pop.
2794   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2795                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2796     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2797   } else {
2798     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2799     // If this is an sret function, the return should pop the hidden pointer.
2800     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2801         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2802         argsAreStructReturn(Ins) == StackStructReturn)
2803       FuncInfo->setBytesToPopOnReturn(4);
2804   }
2805
2806   if (!Is64Bit) {
2807     // RegSaveFrameIndex is X86-64 only.
2808     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2809     if (CallConv == CallingConv::X86_FastCall ||
2810         CallConv == CallingConv::X86_ThisCall)
2811       // fastcc functions can't have varargs.
2812       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2813   }
2814
2815   FuncInfo->setArgumentStackSize(StackSize);
2816
2817   if (IsWinEHParent) {
2818     if (Is64Bit) {
2819       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2820       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2821       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2822       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2823       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2824                            MachinePointerInfo::getFixedStack(
2825                                DAG.getMachineFunction(), UnwindHelpFI),
2826                            /*isVolatile=*/true,
2827                            /*isNonTemporal=*/false, /*Alignment=*/0);
2828     } else {
2829       // Functions using Win32 EH are considered to have opaque SP adjustments
2830       // to force local variables to be addressed from the frame or base
2831       // pointers.
2832       MFI->setHasOpaqueSPAdjustment(true);
2833     }
2834   }
2835
2836   return Chain;
2837 }
2838
2839 SDValue
2840 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2841                                     SDValue StackPtr, SDValue Arg,
2842                                     SDLoc dl, SelectionDAG &DAG,
2843                                     const CCValAssign &VA,
2844                                     ISD::ArgFlagsTy Flags) const {
2845   unsigned LocMemOffset = VA.getLocMemOffset();
2846   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2847   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2848                        StackPtr, PtrOff);
2849   if (Flags.isByVal())
2850     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2851
2852   return DAG.getStore(
2853       Chain, dl, Arg, PtrOff,
2854       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2855       false, false, 0);
2856 }
2857
2858 /// Emit a load of return address if tail call
2859 /// optimization is performed and it is required.
2860 SDValue
2861 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2862                                            SDValue &OutRetAddr, SDValue Chain,
2863                                            bool IsTailCall, bool Is64Bit,
2864                                            int FPDiff, SDLoc dl) const {
2865   // Adjust the Return address stack slot.
2866   EVT VT = getPointerTy(DAG.getDataLayout());
2867   OutRetAddr = getReturnAddressFrameIndex(DAG);
2868
2869   // Load the "old" Return address.
2870   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2871                            false, false, false, 0);
2872   return SDValue(OutRetAddr.getNode(), 1);
2873 }
2874
2875 /// Emit a store of the return address if tail call
2876 /// optimization is performed and it is required (FPDiff!=0).
2877 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2878                                         SDValue Chain, SDValue RetAddrFrIdx,
2879                                         EVT PtrVT, unsigned SlotSize,
2880                                         int FPDiff, SDLoc dl) {
2881   // Store the return address to the appropriate stack slot.
2882   if (!FPDiff) return Chain;
2883   // Calculate the new stack slot for the return address.
2884   int NewReturnAddrFI =
2885     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2886                                          false);
2887   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2888   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2889                        MachinePointerInfo::getFixedStack(
2890                            DAG.getMachineFunction(), NewReturnAddrFI),
2891                        false, false, 0);
2892   return Chain;
2893 }
2894
2895 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2896 /// operation of specified width.
2897 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2898                        SDValue V2) {
2899   unsigned NumElems = VT.getVectorNumElements();
2900   SmallVector<int, 8> Mask;
2901   Mask.push_back(NumElems);
2902   for (unsigned i = 1; i != NumElems; ++i)
2903     Mask.push_back(i);
2904   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2905 }
2906
2907 SDValue
2908 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2909                              SmallVectorImpl<SDValue> &InVals) const {
2910   SelectionDAG &DAG                     = CLI.DAG;
2911   SDLoc &dl                             = CLI.DL;
2912   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2913   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2914   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2915   SDValue Chain                         = CLI.Chain;
2916   SDValue Callee                        = CLI.Callee;
2917   CallingConv::ID CallConv              = CLI.CallConv;
2918   bool &isTailCall                      = CLI.IsTailCall;
2919   bool isVarArg                         = CLI.IsVarArg;
2920
2921   MachineFunction &MF = DAG.getMachineFunction();
2922   bool Is64Bit        = Subtarget->is64Bit();
2923   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2924   StructReturnType SR = callIsStructReturn(Outs);
2925   bool IsSibcall      = false;
2926   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2927   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2928
2929   if (Attr.getValueAsString() == "true")
2930     isTailCall = false;
2931
2932   if (Subtarget->isPICStyleGOT() &&
2933       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2934     // If we are using a GOT, disable tail calls to external symbols with
2935     // default visibility. Tail calling such a symbol requires using a GOT
2936     // relocation, which forces early binding of the symbol. This breaks code
2937     // that require lazy function symbol resolution. Using musttail or
2938     // GuaranteedTailCallOpt will override this.
2939     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2940     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2941                G->getGlobal()->hasDefaultVisibility()))
2942       isTailCall = false;
2943   }
2944
2945   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2946   if (IsMustTail) {
2947     // Force this to be a tail call.  The verifier rules are enough to ensure
2948     // that we can lower this successfully without moving the return address
2949     // around.
2950     isTailCall = true;
2951   } else if (isTailCall) {
2952     // Check if it's really possible to do a tail call.
2953     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2954                     isVarArg, SR != NotStructReturn,
2955                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2956                     Outs, OutVals, Ins, DAG);
2957
2958     // Sibcalls are automatically detected tailcalls which do not require
2959     // ABI changes.
2960     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2961       IsSibcall = true;
2962
2963     if (isTailCall)
2964       ++NumTailCalls;
2965   }
2966
2967   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2968          "Var args not supported with calling convention fastcc, ghc or hipe");
2969
2970   // Analyze operands of the call, assigning locations to each operand.
2971   SmallVector<CCValAssign, 16> ArgLocs;
2972   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2973
2974   // Allocate shadow area for Win64
2975   if (IsWin64)
2976     CCInfo.AllocateStack(32, 8);
2977
2978   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2979
2980   // Get a count of how many bytes are to be pushed on the stack.
2981   unsigned NumBytes = CCInfo.getNextStackOffset();
2982   if (IsSibcall)
2983     // This is a sibcall. The memory operands are available in caller's
2984     // own caller's stack.
2985     NumBytes = 0;
2986   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2987            IsTailCallConvention(CallConv))
2988     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2989
2990   int FPDiff = 0;
2991   if (isTailCall && !IsSibcall && !IsMustTail) {
2992     // Lower arguments at fp - stackoffset + fpdiff.
2993     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2994
2995     FPDiff = NumBytesCallerPushed - NumBytes;
2996
2997     // Set the delta of movement of the returnaddr stackslot.
2998     // But only set if delta is greater than previous delta.
2999     if (FPDiff < X86Info->getTCReturnAddrDelta())
3000       X86Info->setTCReturnAddrDelta(FPDiff);
3001   }
3002
3003   unsigned NumBytesToPush = NumBytes;
3004   unsigned NumBytesToPop = NumBytes;
3005
3006   // If we have an inalloca argument, all stack space has already been allocated
3007   // for us and be right at the top of the stack.  We don't support multiple
3008   // arguments passed in memory when using inalloca.
3009   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3010     NumBytesToPush = 0;
3011     if (!ArgLocs.back().isMemLoc())
3012       report_fatal_error("cannot use inalloca attribute on a register "
3013                          "parameter");
3014     if (ArgLocs.back().getLocMemOffset() != 0)
3015       report_fatal_error("any parameter with the inalloca attribute must be "
3016                          "the only memory argument");
3017   }
3018
3019   if (!IsSibcall)
3020     Chain = DAG.getCALLSEQ_START(
3021         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3022
3023   SDValue RetAddrFrIdx;
3024   // Load return address for tail calls.
3025   if (isTailCall && FPDiff)
3026     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3027                                     Is64Bit, FPDiff, dl);
3028
3029   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3030   SmallVector<SDValue, 8> MemOpChains;
3031   SDValue StackPtr;
3032
3033   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3034   // of tail call optimization arguments are handle later.
3035   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3036   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3037     // Skip inalloca arguments, they have already been written.
3038     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3039     if (Flags.isInAlloca())
3040       continue;
3041
3042     CCValAssign &VA = ArgLocs[i];
3043     EVT RegVT = VA.getLocVT();
3044     SDValue Arg = OutVals[i];
3045     bool isByVal = Flags.isByVal();
3046
3047     // Promote the value if needed.
3048     switch (VA.getLocInfo()) {
3049     default: llvm_unreachable("Unknown loc info!");
3050     case CCValAssign::Full: break;
3051     case CCValAssign::SExt:
3052       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3053       break;
3054     case CCValAssign::ZExt:
3055       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3056       break;
3057     case CCValAssign::AExt:
3058       if (Arg.getValueType().isVector() &&
3059           Arg.getValueType().getScalarType() == MVT::i1)
3060         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3061       else if (RegVT.is128BitVector()) {
3062         // Special case: passing MMX values in XMM registers.
3063         Arg = DAG.getBitcast(MVT::i64, Arg);
3064         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3065         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3066       } else
3067         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3068       break;
3069     case CCValAssign::BCvt:
3070       Arg = DAG.getBitcast(RegVT, Arg);
3071       break;
3072     case CCValAssign::Indirect: {
3073       // Store the argument.
3074       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3075       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3076       Chain = DAG.getStore(
3077           Chain, dl, Arg, SpillSlot,
3078           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3079           false, false, 0);
3080       Arg = SpillSlot;
3081       break;
3082     }
3083     }
3084
3085     if (VA.isRegLoc()) {
3086       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3087       if (isVarArg && IsWin64) {
3088         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3089         // shadow reg if callee is a varargs function.
3090         unsigned ShadowReg = 0;
3091         switch (VA.getLocReg()) {
3092         case X86::XMM0: ShadowReg = X86::RCX; break;
3093         case X86::XMM1: ShadowReg = X86::RDX; break;
3094         case X86::XMM2: ShadowReg = X86::R8; break;
3095         case X86::XMM3: ShadowReg = X86::R9; break;
3096         }
3097         if (ShadowReg)
3098           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3099       }
3100     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3101       assert(VA.isMemLoc());
3102       if (!StackPtr.getNode())
3103         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3104                                       getPointerTy(DAG.getDataLayout()));
3105       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3106                                              dl, DAG, VA, Flags));
3107     }
3108   }
3109
3110   if (!MemOpChains.empty())
3111     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3112
3113   if (Subtarget->isPICStyleGOT()) {
3114     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3115     // GOT pointer.
3116     if (!isTailCall) {
3117       RegsToPass.push_back(std::make_pair(
3118           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3119                                           getPointerTy(DAG.getDataLayout()))));
3120     } else {
3121       // If we are tail calling and generating PIC/GOT style code load the
3122       // address of the callee into ECX. The value in ecx is used as target of
3123       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3124       // for tail calls on PIC/GOT architectures. Normally we would just put the
3125       // address of GOT into ebx and then call target@PLT. But for tail calls
3126       // ebx would be restored (since ebx is callee saved) before jumping to the
3127       // target@PLT.
3128
3129       // Note: The actual moving to ECX is done further down.
3130       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3131       if (G && !G->getGlobal()->hasLocalLinkage() &&
3132           G->getGlobal()->hasDefaultVisibility())
3133         Callee = LowerGlobalAddress(Callee, DAG);
3134       else if (isa<ExternalSymbolSDNode>(Callee))
3135         Callee = LowerExternalSymbol(Callee, DAG);
3136     }
3137   }
3138
3139   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3140     // From AMD64 ABI document:
3141     // For calls that may call functions that use varargs or stdargs
3142     // (prototype-less calls or calls to functions containing ellipsis (...) in
3143     // the declaration) %al is used as hidden argument to specify the number
3144     // of SSE registers used. The contents of %al do not need to match exactly
3145     // the number of registers, but must be an ubound on the number of SSE
3146     // registers used and is in the range 0 - 8 inclusive.
3147
3148     // Count the number of XMM registers allocated.
3149     static const MCPhysReg XMMArgRegs[] = {
3150       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3151       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3152     };
3153     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3154     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3155            && "SSE registers cannot be used when SSE is disabled");
3156
3157     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3158                                         DAG.getConstant(NumXMMRegs, dl,
3159                                                         MVT::i8)));
3160   }
3161
3162   if (isVarArg && IsMustTail) {
3163     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3164     for (const auto &F : Forwards) {
3165       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3166       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3167     }
3168   }
3169
3170   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3171   // don't need this because the eligibility check rejects calls that require
3172   // shuffling arguments passed in memory.
3173   if (!IsSibcall && isTailCall) {
3174     // Force all the incoming stack arguments to be loaded from the stack
3175     // before any new outgoing arguments are stored to the stack, because the
3176     // outgoing stack slots may alias the incoming argument stack slots, and
3177     // the alias isn't otherwise explicit. This is slightly more conservative
3178     // than necessary, because it means that each store effectively depends
3179     // on every argument instead of just those arguments it would clobber.
3180     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3181
3182     SmallVector<SDValue, 8> MemOpChains2;
3183     SDValue FIN;
3184     int FI = 0;
3185     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3186       CCValAssign &VA = ArgLocs[i];
3187       if (VA.isRegLoc())
3188         continue;
3189       assert(VA.isMemLoc());
3190       SDValue Arg = OutVals[i];
3191       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3192       // Skip inalloca arguments.  They don't require any work.
3193       if (Flags.isInAlloca())
3194         continue;
3195       // Create frame index.
3196       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3197       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3198       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3199       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3200
3201       if (Flags.isByVal()) {
3202         // Copy relative to framepointer.
3203         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3204         if (!StackPtr.getNode())
3205           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3206                                         getPointerTy(DAG.getDataLayout()));
3207         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3208                              StackPtr, Source);
3209
3210         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3211                                                          ArgChain,
3212                                                          Flags, DAG, dl));
3213       } else {
3214         // Store relative to framepointer.
3215         MemOpChains2.push_back(DAG.getStore(
3216             ArgChain, dl, Arg, FIN,
3217             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3218             false, false, 0));
3219       }
3220     }
3221
3222     if (!MemOpChains2.empty())
3223       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3224
3225     // Store the return address to the appropriate stack slot.
3226     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3227                                      getPointerTy(DAG.getDataLayout()),
3228                                      RegInfo->getSlotSize(), FPDiff, dl);
3229   }
3230
3231   // Build a sequence of copy-to-reg nodes chained together with token chain
3232   // and flag operands which copy the outgoing args into registers.
3233   SDValue InFlag;
3234   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3235     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3236                              RegsToPass[i].second, InFlag);
3237     InFlag = Chain.getValue(1);
3238   }
3239
3240   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3241     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3242     // In the 64-bit large code model, we have to make all calls
3243     // through a register, since the call instruction's 32-bit
3244     // pc-relative offset may not be large enough to hold the whole
3245     // address.
3246   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3247     // If the callee is a GlobalAddress node (quite common, every direct call
3248     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3249     // it.
3250     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3251
3252     // We should use extra load for direct calls to dllimported functions in
3253     // non-JIT mode.
3254     const GlobalValue *GV = G->getGlobal();
3255     if (!GV->hasDLLImportStorageClass()) {
3256       unsigned char OpFlags = 0;
3257       bool ExtraLoad = false;
3258       unsigned WrapperKind = ISD::DELETED_NODE;
3259
3260       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3261       // external symbols most go through the PLT in PIC mode.  If the symbol
3262       // has hidden or protected visibility, or if it is static or local, then
3263       // we don't need to use the PLT - we can directly call it.
3264       if (Subtarget->isTargetELF() &&
3265           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3266           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3267         OpFlags = X86II::MO_PLT;
3268       } else if (Subtarget->isPICStyleStubAny() &&
3269                  !GV->isStrongDefinitionForLinker() &&
3270                  (!Subtarget->getTargetTriple().isMacOSX() ||
3271                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3272         // PC-relative references to external symbols should go through $stub,
3273         // unless we're building with the leopard linker or later, which
3274         // automatically synthesizes these stubs.
3275         OpFlags = X86II::MO_DARWIN_STUB;
3276       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3277                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3278         // If the function is marked as non-lazy, generate an indirect call
3279         // which loads from the GOT directly. This avoids runtime overhead
3280         // at the cost of eager binding (and one extra byte of encoding).
3281         OpFlags = X86II::MO_GOTPCREL;
3282         WrapperKind = X86ISD::WrapperRIP;
3283         ExtraLoad = true;
3284       }
3285
3286       Callee = DAG.getTargetGlobalAddress(
3287           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3288
3289       // Add a wrapper if needed.
3290       if (WrapperKind != ISD::DELETED_NODE)
3291         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3292                              getPointerTy(DAG.getDataLayout()), Callee);
3293       // Add extra indirection if needed.
3294       if (ExtraLoad)
3295         Callee = DAG.getLoad(
3296             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3297             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3298             false, 0);
3299     }
3300   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3301     unsigned char OpFlags = 0;
3302
3303     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3304     // external symbols should go through the PLT.
3305     if (Subtarget->isTargetELF() &&
3306         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3307       OpFlags = X86II::MO_PLT;
3308     } else if (Subtarget->isPICStyleStubAny() &&
3309                (!Subtarget->getTargetTriple().isMacOSX() ||
3310                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3311       // PC-relative references to external symbols should go through $stub,
3312       // unless we're building with the leopard linker or later, which
3313       // automatically synthesizes these stubs.
3314       OpFlags = X86II::MO_DARWIN_STUB;
3315     }
3316
3317     Callee = DAG.getTargetExternalSymbol(
3318         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3319   } else if (Subtarget->isTarget64BitILP32() &&
3320              Callee->getValueType(0) == MVT::i32) {
3321     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3322     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3323   }
3324
3325   // Returns a chain & a flag for retval copy to use.
3326   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3327   SmallVector<SDValue, 8> Ops;
3328
3329   if (!IsSibcall && isTailCall) {
3330     Chain = DAG.getCALLSEQ_END(Chain,
3331                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3332                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3333     InFlag = Chain.getValue(1);
3334   }
3335
3336   Ops.push_back(Chain);
3337   Ops.push_back(Callee);
3338
3339   if (isTailCall)
3340     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3341
3342   // Add argument registers to the end of the list so that they are known live
3343   // into the call.
3344   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3345     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3346                                   RegsToPass[i].second.getValueType()));
3347
3348   // Add a register mask operand representing the call-preserved registers.
3349   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3350   assert(Mask && "Missing call preserved mask for calling convention");
3351
3352   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3353   // the function clobbers all registers. If an exception is thrown, the runtime
3354   // will not restore CSRs.
3355   // FIXME: Model this more precisely so that we can register allocate across
3356   // the normal edge and spill and fill across the exceptional edge.
3357   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3358     const Function *CallerFn = MF.getFunction();
3359     EHPersonality Pers =
3360         CallerFn->hasPersonalityFn()
3361             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3362             : EHPersonality::Unknown;
3363     if (isMSVCEHPersonality(Pers))
3364       Mask = RegInfo->getNoPreservedMask();
3365   }
3366
3367   Ops.push_back(DAG.getRegisterMask(Mask));
3368
3369   if (InFlag.getNode())
3370     Ops.push_back(InFlag);
3371
3372   if (isTailCall) {
3373     // We used to do:
3374     //// If this is the first return lowered for this function, add the regs
3375     //// to the liveout set for the function.
3376     // This isn't right, although it's probably harmless on x86; liveouts
3377     // should be computed from returns not tail calls.  Consider a void
3378     // function making a tail call to a function returning int.
3379     MF.getFrameInfo()->setHasTailCall();
3380     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3381   }
3382
3383   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3384   InFlag = Chain.getValue(1);
3385
3386   // Create the CALLSEQ_END node.
3387   unsigned NumBytesForCalleeToPop;
3388   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3389                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3390     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3391   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3392            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3393            SR == StackStructReturn)
3394     // If this is a call to a struct-return function, the callee
3395     // pops the hidden struct pointer, so we have to push it back.
3396     // This is common for Darwin/X86, Linux & Mingw32 targets.
3397     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3398     NumBytesForCalleeToPop = 4;
3399   else
3400     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3401
3402   // Returns a flag for retval copy to use.
3403   if (!IsSibcall) {
3404     Chain = DAG.getCALLSEQ_END(Chain,
3405                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3406                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3407                                                      true),
3408                                InFlag, dl);
3409     InFlag = Chain.getValue(1);
3410   }
3411
3412   // Handle result values, copying them out of physregs into vregs that we
3413   // return.
3414   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3415                          Ins, dl, DAG, InVals);
3416 }
3417
3418 //===----------------------------------------------------------------------===//
3419 //                Fast Calling Convention (tail call) implementation
3420 //===----------------------------------------------------------------------===//
3421
3422 //  Like std call, callee cleans arguments, convention except that ECX is
3423 //  reserved for storing the tail called function address. Only 2 registers are
3424 //  free for argument passing (inreg). Tail call optimization is performed
3425 //  provided:
3426 //                * tailcallopt is enabled
3427 //                * caller/callee are fastcc
3428 //  On X86_64 architecture with GOT-style position independent code only local
3429 //  (within module) calls are supported at the moment.
3430 //  To keep the stack aligned according to platform abi the function
3431 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3432 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3433 //  If a tail called function callee has more arguments than the caller the
3434 //  caller needs to make sure that there is room to move the RETADDR to. This is
3435 //  achieved by reserving an area the size of the argument delta right after the
3436 //  original RETADDR, but before the saved framepointer or the spilled registers
3437 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3438 //  stack layout:
3439 //    arg1
3440 //    arg2
3441 //    RETADDR
3442 //    [ new RETADDR
3443 //      move area ]
3444 //    (possible EBP)
3445 //    ESI
3446 //    EDI
3447 //    local1 ..
3448
3449 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3450 /// requirement.
3451 unsigned
3452 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3453                                                SelectionDAG& DAG) const {
3454   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3455   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3456   unsigned StackAlignment = TFI.getStackAlignment();
3457   uint64_t AlignMask = StackAlignment - 1;
3458   int64_t Offset = StackSize;
3459   unsigned SlotSize = RegInfo->getSlotSize();
3460   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3461     // Number smaller than 12 so just add the difference.
3462     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3463   } else {
3464     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3465     Offset = ((~AlignMask) & Offset) + StackAlignment +
3466       (StackAlignment-SlotSize);
3467   }
3468   return Offset;
3469 }
3470
3471 /// Return true if the given stack call argument is already available in the
3472 /// same position (relatively) of the caller's incoming argument stack.
3473 static
3474 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3475                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3476                          const X86InstrInfo *TII) {
3477   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3478   int FI = INT_MAX;
3479   if (Arg.getOpcode() == ISD::CopyFromReg) {
3480     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3481     if (!TargetRegisterInfo::isVirtualRegister(VR))
3482       return false;
3483     MachineInstr *Def = MRI->getVRegDef(VR);
3484     if (!Def)
3485       return false;
3486     if (!Flags.isByVal()) {
3487       if (!TII->isLoadFromStackSlot(Def, FI))
3488         return false;
3489     } else {
3490       unsigned Opcode = Def->getOpcode();
3491       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3492            Opcode == X86::LEA64_32r) &&
3493           Def->getOperand(1).isFI()) {
3494         FI = Def->getOperand(1).getIndex();
3495         Bytes = Flags.getByValSize();
3496       } else
3497         return false;
3498     }
3499   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3500     if (Flags.isByVal())
3501       // ByVal argument is passed in as a pointer but it's now being
3502       // dereferenced. e.g.
3503       // define @foo(%struct.X* %A) {
3504       //   tail call @bar(%struct.X* byval %A)
3505       // }
3506       return false;
3507     SDValue Ptr = Ld->getBasePtr();
3508     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3509     if (!FINode)
3510       return false;
3511     FI = FINode->getIndex();
3512   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3513     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3514     FI = FINode->getIndex();
3515     Bytes = Flags.getByValSize();
3516   } else
3517     return false;
3518
3519   assert(FI != INT_MAX);
3520   if (!MFI->isFixedObjectIndex(FI))
3521     return false;
3522   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3523 }
3524
3525 /// Check whether the call is eligible for tail call optimization. Targets
3526 /// that want to do tail call optimization should implement this function.
3527 bool
3528 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3529                                                      CallingConv::ID CalleeCC,
3530                                                      bool isVarArg,
3531                                                      bool isCalleeStructRet,
3532                                                      bool isCallerStructRet,
3533                                                      Type *RetTy,
3534                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3535                                     const SmallVectorImpl<SDValue> &OutVals,
3536                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3537                                                      SelectionDAG &DAG) const {
3538   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3539     return false;
3540
3541   // If -tailcallopt is specified, make fastcc functions tail-callable.
3542   const MachineFunction &MF = DAG.getMachineFunction();
3543   const Function *CallerF = MF.getFunction();
3544
3545   // If the function return type is x86_fp80 and the callee return type is not,
3546   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3547   // perform a tailcall optimization here.
3548   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3549     return false;
3550
3551   CallingConv::ID CallerCC = CallerF->getCallingConv();
3552   bool CCMatch = CallerCC == CalleeCC;
3553   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3554   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3555
3556   // Win64 functions have extra shadow space for argument homing. Don't do the
3557   // sibcall if the caller and callee have mismatched expectations for this
3558   // space.
3559   if (IsCalleeWin64 != IsCallerWin64)
3560     return false;
3561
3562   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3563     if (IsTailCallConvention(CalleeCC) && CCMatch)
3564       return true;
3565     return false;
3566   }
3567
3568   // Look for obvious safe cases to perform tail call optimization that do not
3569   // require ABI changes. This is what gcc calls sibcall.
3570
3571   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3572   // emit a special epilogue.
3573   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3574   if (RegInfo->needsStackRealignment(MF))
3575     return false;
3576
3577   // Also avoid sibcall optimization if either caller or callee uses struct
3578   // return semantics.
3579   if (isCalleeStructRet || isCallerStructRet)
3580     return false;
3581
3582   // An stdcall/thiscall caller is expected to clean up its arguments; the
3583   // callee isn't going to do that.
3584   // FIXME: this is more restrictive than needed. We could produce a tailcall
3585   // when the stack adjustment matches. For example, with a thiscall that takes
3586   // only one argument.
3587   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3588                    CallerCC == CallingConv::X86_ThisCall))
3589     return false;
3590
3591   // Do not sibcall optimize vararg calls unless all arguments are passed via
3592   // registers.
3593   if (isVarArg && !Outs.empty()) {
3594
3595     // Optimizing for varargs on Win64 is unlikely to be safe without
3596     // additional testing.
3597     if (IsCalleeWin64 || IsCallerWin64)
3598       return false;
3599
3600     SmallVector<CCValAssign, 16> ArgLocs;
3601     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3602                    *DAG.getContext());
3603
3604     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3605     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3606       if (!ArgLocs[i].isRegLoc())
3607         return false;
3608   }
3609
3610   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3611   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3612   // this into a sibcall.
3613   bool Unused = false;
3614   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3615     if (!Ins[i].Used) {
3616       Unused = true;
3617       break;
3618     }
3619   }
3620   if (Unused) {
3621     SmallVector<CCValAssign, 16> RVLocs;
3622     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3623                    *DAG.getContext());
3624     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3625     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3626       CCValAssign &VA = RVLocs[i];
3627       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3628         return false;
3629     }
3630   }
3631
3632   // If the calling conventions do not match, then we'd better make sure the
3633   // results are returned in the same way as what the caller expects.
3634   if (!CCMatch) {
3635     SmallVector<CCValAssign, 16> RVLocs1;
3636     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3637                     *DAG.getContext());
3638     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3639
3640     SmallVector<CCValAssign, 16> RVLocs2;
3641     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3642                     *DAG.getContext());
3643     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3644
3645     if (RVLocs1.size() != RVLocs2.size())
3646       return false;
3647     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3648       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3649         return false;
3650       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3651         return false;
3652       if (RVLocs1[i].isRegLoc()) {
3653         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3654           return false;
3655       } else {
3656         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3657           return false;
3658       }
3659     }
3660   }
3661
3662   // If the callee takes no arguments then go on to check the results of the
3663   // call.
3664   if (!Outs.empty()) {
3665     // Check if stack adjustment is needed. For now, do not do this if any
3666     // argument is passed on the stack.
3667     SmallVector<CCValAssign, 16> ArgLocs;
3668     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3669                    *DAG.getContext());
3670
3671     // Allocate shadow area for Win64
3672     if (IsCalleeWin64)
3673       CCInfo.AllocateStack(32, 8);
3674
3675     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3676     if (CCInfo.getNextStackOffset()) {
3677       MachineFunction &MF = DAG.getMachineFunction();
3678       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3679         return false;
3680
3681       // Check if the arguments are already laid out in the right way as
3682       // the caller's fixed stack objects.
3683       MachineFrameInfo *MFI = MF.getFrameInfo();
3684       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3685       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3686       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3687         CCValAssign &VA = ArgLocs[i];
3688         SDValue Arg = OutVals[i];
3689         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3690         if (VA.getLocInfo() == CCValAssign::Indirect)
3691           return false;
3692         if (!VA.isRegLoc()) {
3693           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3694                                    MFI, MRI, TII))
3695             return false;
3696         }
3697       }
3698     }
3699
3700     // If the tailcall address may be in a register, then make sure it's
3701     // possible to register allocate for it. In 32-bit, the call address can
3702     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3703     // callee-saved registers are restored. These happen to be the same
3704     // registers used to pass 'inreg' arguments so watch out for those.
3705     if (!Subtarget->is64Bit() &&
3706         ((!isa<GlobalAddressSDNode>(Callee) &&
3707           !isa<ExternalSymbolSDNode>(Callee)) ||
3708          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3709       unsigned NumInRegs = 0;
3710       // In PIC we need an extra register to formulate the address computation
3711       // for the callee.
3712       unsigned MaxInRegs =
3713         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3714
3715       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3716         CCValAssign &VA = ArgLocs[i];
3717         if (!VA.isRegLoc())
3718           continue;
3719         unsigned Reg = VA.getLocReg();
3720         switch (Reg) {
3721         default: break;
3722         case X86::EAX: case X86::EDX: case X86::ECX:
3723           if (++NumInRegs == MaxInRegs)
3724             return false;
3725           break;
3726         }
3727       }
3728     }
3729   }
3730
3731   return true;
3732 }
3733
3734 FastISel *
3735 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3736                                   const TargetLibraryInfo *libInfo) const {
3737   return X86::createFastISel(funcInfo, libInfo);
3738 }
3739
3740 //===----------------------------------------------------------------------===//
3741 //                           Other Lowering Hooks
3742 //===----------------------------------------------------------------------===//
3743
3744 static bool MayFoldLoad(SDValue Op) {
3745   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3746 }
3747
3748 static bool MayFoldIntoStore(SDValue Op) {
3749   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3750 }
3751
3752 static bool isTargetShuffle(unsigned Opcode) {
3753   switch(Opcode) {
3754   default: return false;
3755   case X86ISD::BLENDI:
3756   case X86ISD::PSHUFB:
3757   case X86ISD::PSHUFD:
3758   case X86ISD::PSHUFHW:
3759   case X86ISD::PSHUFLW:
3760   case X86ISD::SHUFP:
3761   case X86ISD::PALIGNR:
3762   case X86ISD::MOVLHPS:
3763   case X86ISD::MOVLHPD:
3764   case X86ISD::MOVHLPS:
3765   case X86ISD::MOVLPS:
3766   case X86ISD::MOVLPD:
3767   case X86ISD::MOVSHDUP:
3768   case X86ISD::MOVSLDUP:
3769   case X86ISD::MOVDDUP:
3770   case X86ISD::MOVSS:
3771   case X86ISD::MOVSD:
3772   case X86ISD::UNPCKL:
3773   case X86ISD::UNPCKH:
3774   case X86ISD::VPERMILPI:
3775   case X86ISD::VPERM2X128:
3776   case X86ISD::VPERMI:
3777     return true;
3778   }
3779 }
3780
3781 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3782                                     SDValue V1, unsigned TargetMask,
3783                                     SelectionDAG &DAG) {
3784   switch(Opc) {
3785   default: llvm_unreachable("Unknown x86 shuffle node");
3786   case X86ISD::PSHUFD:
3787   case X86ISD::PSHUFHW:
3788   case X86ISD::PSHUFLW:
3789   case X86ISD::VPERMILPI:
3790   case X86ISD::VPERMI:
3791     return DAG.getNode(Opc, dl, VT, V1,
3792                        DAG.getConstant(TargetMask, dl, MVT::i8));
3793   }
3794 }
3795
3796 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3797                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3798   switch(Opc) {
3799   default: llvm_unreachable("Unknown x86 shuffle node");
3800   case X86ISD::MOVLHPS:
3801   case X86ISD::MOVLHPD:
3802   case X86ISD::MOVHLPS:
3803   case X86ISD::MOVLPS:
3804   case X86ISD::MOVLPD:
3805   case X86ISD::MOVSS:
3806   case X86ISD::MOVSD:
3807   case X86ISD::UNPCKL:
3808   case X86ISD::UNPCKH:
3809     return DAG.getNode(Opc, dl, VT, V1, V2);
3810   }
3811 }
3812
3813 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3814   MachineFunction &MF = DAG.getMachineFunction();
3815   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3816   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3817   int ReturnAddrIndex = FuncInfo->getRAIndex();
3818
3819   if (ReturnAddrIndex == 0) {
3820     // Set up a frame object for the return address.
3821     unsigned SlotSize = RegInfo->getSlotSize();
3822     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3823                                                            -(int64_t)SlotSize,
3824                                                            false);
3825     FuncInfo->setRAIndex(ReturnAddrIndex);
3826   }
3827
3828   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3829 }
3830
3831 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3832                                        bool hasSymbolicDisplacement) {
3833   // Offset should fit into 32 bit immediate field.
3834   if (!isInt<32>(Offset))
3835     return false;
3836
3837   // If we don't have a symbolic displacement - we don't have any extra
3838   // restrictions.
3839   if (!hasSymbolicDisplacement)
3840     return true;
3841
3842   // FIXME: Some tweaks might be needed for medium code model.
3843   if (M != CodeModel::Small && M != CodeModel::Kernel)
3844     return false;
3845
3846   // For small code model we assume that latest object is 16MB before end of 31
3847   // bits boundary. We may also accept pretty large negative constants knowing
3848   // that all objects are in the positive half of address space.
3849   if (M == CodeModel::Small && Offset < 16*1024*1024)
3850     return true;
3851
3852   // For kernel code model we know that all object resist in the negative half
3853   // of 32bits address space. We may not accept negative offsets, since they may
3854   // be just off and we may accept pretty large positive ones.
3855   if (M == CodeModel::Kernel && Offset >= 0)
3856     return true;
3857
3858   return false;
3859 }
3860
3861 /// Determines whether the callee is required to pop its own arguments.
3862 /// Callee pop is necessary to support tail calls.
3863 bool X86::isCalleePop(CallingConv::ID CallingConv,
3864                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3865   switch (CallingConv) {
3866   default:
3867     return false;
3868   case CallingConv::X86_StdCall:
3869   case CallingConv::X86_FastCall:
3870   case CallingConv::X86_ThisCall:
3871     return !is64Bit;
3872   case CallingConv::Fast:
3873   case CallingConv::GHC:
3874   case CallingConv::HiPE:
3875     if (IsVarArg)
3876       return false;
3877     return TailCallOpt;
3878   }
3879 }
3880
3881 /// \brief Return true if the condition is an unsigned comparison operation.
3882 static bool isX86CCUnsigned(unsigned X86CC) {
3883   switch (X86CC) {
3884   default: llvm_unreachable("Invalid integer condition!");
3885   case X86::COND_E:     return true;
3886   case X86::COND_G:     return false;
3887   case X86::COND_GE:    return false;
3888   case X86::COND_L:     return false;
3889   case X86::COND_LE:    return false;
3890   case X86::COND_NE:    return true;
3891   case X86::COND_B:     return true;
3892   case X86::COND_A:     return true;
3893   case X86::COND_BE:    return true;
3894   case X86::COND_AE:    return true;
3895   }
3896   llvm_unreachable("covered switch fell through?!");
3897 }
3898
3899 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3900 /// condition code, returning the condition code and the LHS/RHS of the
3901 /// comparison to make.
3902 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3903                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3904   if (!isFP) {
3905     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3906       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3907         // X > -1   -> X == 0, jump !sign.
3908         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3909         return X86::COND_NS;
3910       }
3911       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3912         // X < 0   -> X == 0, jump on sign.
3913         return X86::COND_S;
3914       }
3915       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3916         // X < 1   -> X <= 0
3917         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3918         return X86::COND_LE;
3919       }
3920     }
3921
3922     switch (SetCCOpcode) {
3923     default: llvm_unreachable("Invalid integer condition!");
3924     case ISD::SETEQ:  return X86::COND_E;
3925     case ISD::SETGT:  return X86::COND_G;
3926     case ISD::SETGE:  return X86::COND_GE;
3927     case ISD::SETLT:  return X86::COND_L;
3928     case ISD::SETLE:  return X86::COND_LE;
3929     case ISD::SETNE:  return X86::COND_NE;
3930     case ISD::SETULT: return X86::COND_B;
3931     case ISD::SETUGT: return X86::COND_A;
3932     case ISD::SETULE: return X86::COND_BE;
3933     case ISD::SETUGE: return X86::COND_AE;
3934     }
3935   }
3936
3937   // First determine if it is required or is profitable to flip the operands.
3938
3939   // If LHS is a foldable load, but RHS is not, flip the condition.
3940   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3941       !ISD::isNON_EXTLoad(RHS.getNode())) {
3942     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3943     std::swap(LHS, RHS);
3944   }
3945
3946   switch (SetCCOpcode) {
3947   default: break;
3948   case ISD::SETOLT:
3949   case ISD::SETOLE:
3950   case ISD::SETUGT:
3951   case ISD::SETUGE:
3952     std::swap(LHS, RHS);
3953     break;
3954   }
3955
3956   // On a floating point condition, the flags are set as follows:
3957   // ZF  PF  CF   op
3958   //  0 | 0 | 0 | X > Y
3959   //  0 | 0 | 1 | X < Y
3960   //  1 | 0 | 0 | X == Y
3961   //  1 | 1 | 1 | unordered
3962   switch (SetCCOpcode) {
3963   default: llvm_unreachable("Condcode should be pre-legalized away");
3964   case ISD::SETUEQ:
3965   case ISD::SETEQ:   return X86::COND_E;
3966   case ISD::SETOLT:              // flipped
3967   case ISD::SETOGT:
3968   case ISD::SETGT:   return X86::COND_A;
3969   case ISD::SETOLE:              // flipped
3970   case ISD::SETOGE:
3971   case ISD::SETGE:   return X86::COND_AE;
3972   case ISD::SETUGT:              // flipped
3973   case ISD::SETULT:
3974   case ISD::SETLT:   return X86::COND_B;
3975   case ISD::SETUGE:              // flipped
3976   case ISD::SETULE:
3977   case ISD::SETLE:   return X86::COND_BE;
3978   case ISD::SETONE:
3979   case ISD::SETNE:   return X86::COND_NE;
3980   case ISD::SETUO:   return X86::COND_P;
3981   case ISD::SETO:    return X86::COND_NP;
3982   case ISD::SETOEQ:
3983   case ISD::SETUNE:  return X86::COND_INVALID;
3984   }
3985 }
3986
3987 /// Is there a floating point cmov for the specific X86 condition code?
3988 /// Current x86 isa includes the following FP cmov instructions:
3989 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3990 static bool hasFPCMov(unsigned X86CC) {
3991   switch (X86CC) {
3992   default:
3993     return false;
3994   case X86::COND_B:
3995   case X86::COND_BE:
3996   case X86::COND_E:
3997   case X86::COND_P:
3998   case X86::COND_A:
3999   case X86::COND_AE:
4000   case X86::COND_NE:
4001   case X86::COND_NP:
4002     return true;
4003   }
4004 }
4005
4006 /// Returns true if the target can instruction select the
4007 /// specified FP immediate natively. If false, the legalizer will
4008 /// materialize the FP immediate as a load from a constant pool.
4009 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4010   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4011     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4012       return true;
4013   }
4014   return false;
4015 }
4016
4017 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4018                                               ISD::LoadExtType ExtTy,
4019                                               EVT NewVT) const {
4020   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4021   // relocation target a movq or addq instruction: don't let the load shrink.
4022   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4023   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4024     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4025       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4026   return true;
4027 }
4028
4029 /// \brief Returns true if it is beneficial to convert a load of a constant
4030 /// to just the constant itself.
4031 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4032                                                           Type *Ty) const {
4033   assert(Ty->isIntegerTy());
4034
4035   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4036   if (BitSize == 0 || BitSize > 64)
4037     return false;
4038   return true;
4039 }
4040
4041 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4042                                                 unsigned Index) const {
4043   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4044     return false;
4045
4046   return (Index == 0 || Index == ResVT.getVectorNumElements());
4047 }
4048
4049 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4050   // Speculate cttz only if we can directly use TZCNT.
4051   return Subtarget->hasBMI();
4052 }
4053
4054 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4055   // Speculate ctlz only if we can directly use LZCNT.
4056   return Subtarget->hasLZCNT();
4057 }
4058
4059 /// Return true if every element in Mask, beginning
4060 /// from position Pos and ending in Pos+Size is undef.
4061 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4062   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4063     if (0 <= Mask[i])
4064       return false;
4065   return true;
4066 }
4067
4068 /// Return true if Val is undef or if its value falls within the
4069 /// specified range (L, H].
4070 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4071   return (Val < 0) || (Val >= Low && Val < Hi);
4072 }
4073
4074 /// Val is either less than zero (undef) or equal to the specified value.
4075 static bool isUndefOrEqual(int Val, int CmpVal) {
4076   return (Val < 0 || Val == CmpVal);
4077 }
4078
4079 /// Return true if every element in Mask, beginning
4080 /// from position Pos and ending in Pos+Size, falls within the specified
4081 /// sequential range (Low, Low+Size]. or is undef.
4082 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4083                                        unsigned Pos, unsigned Size, int Low) {
4084   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4085     if (!isUndefOrEqual(Mask[i], Low))
4086       return false;
4087   return true;
4088 }
4089
4090 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4091 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4092 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4093   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4094   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4095     return false;
4096
4097   // The index should be aligned on a vecWidth-bit boundary.
4098   uint64_t Index =
4099     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4100
4101   MVT VT = N->getSimpleValueType(0);
4102   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4103   bool Result = (Index * ElSize) % vecWidth == 0;
4104
4105   return Result;
4106 }
4107
4108 /// Return true if the specified INSERT_SUBVECTOR
4109 /// operand specifies a subvector insert that is suitable for input to
4110 /// insertion of 128 or 256-bit subvectors
4111 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4112   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4113   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4114     return false;
4115   // The index should be aligned on a vecWidth-bit boundary.
4116   uint64_t Index =
4117     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4118
4119   MVT VT = N->getSimpleValueType(0);
4120   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4121   bool Result = (Index * ElSize) % vecWidth == 0;
4122
4123   return Result;
4124 }
4125
4126 bool X86::isVINSERT128Index(SDNode *N) {
4127   return isVINSERTIndex(N, 128);
4128 }
4129
4130 bool X86::isVINSERT256Index(SDNode *N) {
4131   return isVINSERTIndex(N, 256);
4132 }
4133
4134 bool X86::isVEXTRACT128Index(SDNode *N) {
4135   return isVEXTRACTIndex(N, 128);
4136 }
4137
4138 bool X86::isVEXTRACT256Index(SDNode *N) {
4139   return isVEXTRACTIndex(N, 256);
4140 }
4141
4142 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4143   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4144   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4145     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4146
4147   uint64_t Index =
4148     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4149
4150   MVT VecVT = N->getOperand(0).getSimpleValueType();
4151   MVT ElVT = VecVT.getVectorElementType();
4152
4153   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4154   return Index / NumElemsPerChunk;
4155 }
4156
4157 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4158   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4159   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4160     llvm_unreachable("Illegal insert subvector for VINSERT");
4161
4162   uint64_t Index =
4163     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4164
4165   MVT VecVT = N->getSimpleValueType(0);
4166   MVT ElVT = VecVT.getVectorElementType();
4167
4168   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4169   return Index / NumElemsPerChunk;
4170 }
4171
4172 /// Return the appropriate immediate to extract the specified
4173 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4174 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4175   return getExtractVEXTRACTImmediate(N, 128);
4176 }
4177
4178 /// Return the appropriate immediate to extract the specified
4179 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4180 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4181   return getExtractVEXTRACTImmediate(N, 256);
4182 }
4183
4184 /// Return the appropriate immediate to insert at the specified
4185 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4186 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4187   return getInsertVINSERTImmediate(N, 128);
4188 }
4189
4190 /// Return the appropriate immediate to insert at the specified
4191 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4192 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4193   return getInsertVINSERTImmediate(N, 256);
4194 }
4195
4196 /// Returns true if Elt is a constant integer zero
4197 static bool isZero(SDValue V) {
4198   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4199   return C && C->isNullValue();
4200 }
4201
4202 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4203 bool X86::isZeroNode(SDValue Elt) {
4204   if (isZero(Elt))
4205     return true;
4206   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4207     return CFP->getValueAPF().isPosZero();
4208   return false;
4209 }
4210
4211 /// Returns a vector of specified type with all zero elements.
4212 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4213                              SelectionDAG &DAG, SDLoc dl) {
4214   assert(VT.isVector() && "Expected a vector type");
4215
4216   // Always build SSE zero vectors as <4 x i32> bitcasted
4217   // to their dest type. This ensures they get CSE'd.
4218   SDValue Vec;
4219   if (VT.is128BitVector()) {  // SSE
4220     if (Subtarget->hasSSE2()) {  // SSE2
4221       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4222       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4223     } else { // SSE1
4224       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4225       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4226     }
4227   } else if (VT.is256BitVector()) { // AVX
4228     if (Subtarget->hasInt256()) { // AVX2
4229       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4230       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4231       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4232     } else {
4233       // 256-bit logic and arithmetic instructions in AVX are all
4234       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4235       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4236       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4237       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4238     }
4239   } else if (VT.is512BitVector()) { // AVX-512
4240       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4241       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4242                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4243       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4244   } else if (VT.getScalarType() == MVT::i1) {
4245
4246     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4247             && "Unexpected vector type");
4248     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4249             && "Unexpected vector type");
4250     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4251     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4252     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4253   } else
4254     llvm_unreachable("Unexpected vector type");
4255
4256   return DAG.getBitcast(VT, Vec);
4257 }
4258
4259 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4260                                 SelectionDAG &DAG, SDLoc dl,
4261                                 unsigned vectorWidth) {
4262   assert((vectorWidth == 128 || vectorWidth == 256) &&
4263          "Unsupported vector width");
4264   EVT VT = Vec.getValueType();
4265   EVT ElVT = VT.getVectorElementType();
4266   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4267   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4268                                   VT.getVectorNumElements()/Factor);
4269
4270   // Extract from UNDEF is UNDEF.
4271   if (Vec.getOpcode() == ISD::UNDEF)
4272     return DAG.getUNDEF(ResultVT);
4273
4274   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4275   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4276
4277   // This is the index of the first element of the vectorWidth-bit chunk
4278   // we want.
4279   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4280                                * ElemsPerChunk);
4281
4282   // If the input is a buildvector just emit a smaller one.
4283   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4284     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4285                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4286                                     ElemsPerChunk));
4287
4288   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4289   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4290 }
4291
4292 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4293 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4294 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4295 /// instructions or a simple subregister reference. Idx is an index in the
4296 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4297 /// lowering EXTRACT_VECTOR_ELT operations easier.
4298 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4299                                    SelectionDAG &DAG, SDLoc dl) {
4300   assert((Vec.getValueType().is256BitVector() ||
4301           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4302   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4303 }
4304
4305 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4306 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4307                                    SelectionDAG &DAG, SDLoc dl) {
4308   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4309   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4310 }
4311
4312 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4313                                unsigned IdxVal, SelectionDAG &DAG,
4314                                SDLoc dl, unsigned vectorWidth) {
4315   assert((vectorWidth == 128 || vectorWidth == 256) &&
4316          "Unsupported vector width");
4317   // Inserting UNDEF is Result
4318   if (Vec.getOpcode() == ISD::UNDEF)
4319     return Result;
4320   EVT VT = Vec.getValueType();
4321   EVT ElVT = VT.getVectorElementType();
4322   EVT ResultVT = Result.getValueType();
4323
4324   // Insert the relevant vectorWidth bits.
4325   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4326
4327   // This is the index of the first element of the vectorWidth-bit chunk
4328   // we want.
4329   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4330                                * ElemsPerChunk);
4331
4332   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4333   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4334 }
4335
4336 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4337 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4338 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4339 /// simple superregister reference.  Idx is an index in the 128 bits
4340 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4341 /// lowering INSERT_VECTOR_ELT operations easier.
4342 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4343                                   SelectionDAG &DAG, SDLoc dl) {
4344   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4345
4346   // For insertion into the zero index (low half) of a 256-bit vector, it is
4347   // more efficient to generate a blend with immediate instead of an insert*128.
4348   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4349   // extend the subvector to the size of the result vector. Make sure that
4350   // we are not recursing on that node by checking for undef here.
4351   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4352       Result.getOpcode() != ISD::UNDEF) {
4353     EVT ResultVT = Result.getValueType();
4354     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4355     SDValue Undef = DAG.getUNDEF(ResultVT);
4356     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4357                                  Vec, ZeroIndex);
4358
4359     // The blend instruction, and therefore its mask, depend on the data type.
4360     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4361     if (ScalarType.isFloatingPoint()) {
4362       // Choose either vblendps (float) or vblendpd (double).
4363       unsigned ScalarSize = ScalarType.getSizeInBits();
4364       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4365       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4366       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4367       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4368     }
4369
4370     const X86Subtarget &Subtarget =
4371     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4372
4373     // AVX2 is needed for 256-bit integer blend support.
4374     // Integers must be cast to 32-bit because there is only vpblendd;
4375     // vpblendw can't be used for this because it has a handicapped mask.
4376
4377     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4378     // is still more efficient than using the wrong domain vinsertf128 that
4379     // will be created by InsertSubVector().
4380     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4381
4382     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4383     Vec256 = DAG.getBitcast(CastVT, Vec256);
4384     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4385     return DAG.getBitcast(ResultVT, Vec256);
4386   }
4387
4388   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4389 }
4390
4391 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4392                                   SelectionDAG &DAG, SDLoc dl) {
4393   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4394   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4395 }
4396
4397 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4398 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4399 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4400 /// large BUILD_VECTORS.
4401 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4402                                    unsigned NumElems, SelectionDAG &DAG,
4403                                    SDLoc dl) {
4404   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4405   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4406 }
4407
4408 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4409                                    unsigned NumElems, SelectionDAG &DAG,
4410                                    SDLoc dl) {
4411   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4412   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4413 }
4414
4415 /// Returns a vector of specified type with all bits set.
4416 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4417 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4418 /// Then bitcast to their original type, ensuring they get CSE'd.
4419 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4420                              SDLoc dl) {
4421   assert(VT.isVector() && "Expected a vector type");
4422
4423   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4424   SDValue Vec;
4425   if (VT.is256BitVector()) {
4426     if (HasInt256) { // AVX2
4427       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4428       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4429     } else { // AVX
4430       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4431       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4432     }
4433   } else if (VT.is128BitVector()) {
4434     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4435   } else
4436     llvm_unreachable("Unexpected vector type");
4437
4438   return DAG.getBitcast(VT, Vec);
4439 }
4440
4441 /// Returns a vector_shuffle node for an unpackl operation.
4442 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4443                           SDValue V2) {
4444   unsigned NumElems = VT.getVectorNumElements();
4445   SmallVector<int, 8> Mask;
4446   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4447     Mask.push_back(i);
4448     Mask.push_back(i + NumElems);
4449   }
4450   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4451 }
4452
4453 /// Returns a vector_shuffle node for an unpackh operation.
4454 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4455                           SDValue V2) {
4456   unsigned NumElems = VT.getVectorNumElements();
4457   SmallVector<int, 8> Mask;
4458   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4459     Mask.push_back(i + Half);
4460     Mask.push_back(i + NumElems + Half);
4461   }
4462   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4463 }
4464
4465 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4466 /// This produces a shuffle where the low element of V2 is swizzled into the
4467 /// zero/undef vector, landing at element Idx.
4468 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4469 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4470                                            bool IsZero,
4471                                            const X86Subtarget *Subtarget,
4472                                            SelectionDAG &DAG) {
4473   MVT VT = V2.getSimpleValueType();
4474   SDValue V1 = IsZero
4475     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4476   unsigned NumElems = VT.getVectorNumElements();
4477   SmallVector<int, 16> MaskVec;
4478   for (unsigned i = 0; i != NumElems; ++i)
4479     // If this is the insertion idx, put the low elt of V2 here.
4480     MaskVec.push_back(i == Idx ? NumElems : i);
4481   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4482 }
4483
4484 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4485 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4486 /// uses one source. Note that this will set IsUnary for shuffles which use a
4487 /// single input multiple times, and in those cases it will
4488 /// adjust the mask to only have indices within that single input.
4489 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4490 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4491                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4492   unsigned NumElems = VT.getVectorNumElements();
4493   SDValue ImmN;
4494
4495   IsUnary = false;
4496   bool IsFakeUnary = false;
4497   switch(N->getOpcode()) {
4498   case X86ISD::BLENDI:
4499     ImmN = N->getOperand(N->getNumOperands()-1);
4500     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4501     break;
4502   case X86ISD::SHUFP:
4503     ImmN = N->getOperand(N->getNumOperands()-1);
4504     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4505     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4506     break;
4507   case X86ISD::UNPCKH:
4508     DecodeUNPCKHMask(VT, Mask);
4509     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4510     break;
4511   case X86ISD::UNPCKL:
4512     DecodeUNPCKLMask(VT, Mask);
4513     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4514     break;
4515   case X86ISD::MOVHLPS:
4516     DecodeMOVHLPSMask(NumElems, Mask);
4517     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4518     break;
4519   case X86ISD::MOVLHPS:
4520     DecodeMOVLHPSMask(NumElems, Mask);
4521     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4522     break;
4523   case X86ISD::PALIGNR:
4524     ImmN = N->getOperand(N->getNumOperands()-1);
4525     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4526     break;
4527   case X86ISD::PSHUFD:
4528   case X86ISD::VPERMILPI:
4529     ImmN = N->getOperand(N->getNumOperands()-1);
4530     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4531     IsUnary = true;
4532     break;
4533   case X86ISD::PSHUFHW:
4534     ImmN = N->getOperand(N->getNumOperands()-1);
4535     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4536     IsUnary = true;
4537     break;
4538   case X86ISD::PSHUFLW:
4539     ImmN = N->getOperand(N->getNumOperands()-1);
4540     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4541     IsUnary = true;
4542     break;
4543   case X86ISD::PSHUFB: {
4544     IsUnary = true;
4545     SDValue MaskNode = N->getOperand(1);
4546     while (MaskNode->getOpcode() == ISD::BITCAST)
4547       MaskNode = MaskNode->getOperand(0);
4548
4549     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4550       // If we have a build-vector, then things are easy.
4551       EVT VT = MaskNode.getValueType();
4552       assert(VT.isVector() &&
4553              "Can't produce a non-vector with a build_vector!");
4554       if (!VT.isInteger())
4555         return false;
4556
4557       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4558
4559       SmallVector<uint64_t, 32> RawMask;
4560       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4561         SDValue Op = MaskNode->getOperand(i);
4562         if (Op->getOpcode() == ISD::UNDEF) {
4563           RawMask.push_back((uint64_t)SM_SentinelUndef);
4564           continue;
4565         }
4566         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4567         if (!CN)
4568           return false;
4569         APInt MaskElement = CN->getAPIntValue();
4570
4571         // We now have to decode the element which could be any integer size and
4572         // extract each byte of it.
4573         for (int j = 0; j < NumBytesPerElement; ++j) {
4574           // Note that this is x86 and so always little endian: the low byte is
4575           // the first byte of the mask.
4576           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4577           MaskElement = MaskElement.lshr(8);
4578         }
4579       }
4580       DecodePSHUFBMask(RawMask, Mask);
4581       break;
4582     }
4583
4584     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4585     if (!MaskLoad)
4586       return false;
4587
4588     SDValue Ptr = MaskLoad->getBasePtr();
4589     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4590         Ptr->getOpcode() == X86ISD::WrapperRIP)
4591       Ptr = Ptr->getOperand(0);
4592
4593     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4594     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4595       return false;
4596
4597     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4598       DecodePSHUFBMask(C, Mask);
4599       if (Mask.empty())
4600         return false;
4601       break;
4602     }
4603
4604     return false;
4605   }
4606   case X86ISD::VPERMI:
4607     ImmN = N->getOperand(N->getNumOperands()-1);
4608     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4609     IsUnary = true;
4610     break;
4611   case X86ISD::MOVSS:
4612   case X86ISD::MOVSD:
4613     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4614     break;
4615   case X86ISD::VPERM2X128:
4616     ImmN = N->getOperand(N->getNumOperands()-1);
4617     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4618     if (Mask.empty()) return false;
4619     // Mask only contains negative index if an element is zero.
4620     if (std::any_of(Mask.begin(), Mask.end(),
4621                     [](int M){ return M == SM_SentinelZero; }))
4622       return false;
4623     break;
4624   case X86ISD::MOVSLDUP:
4625     DecodeMOVSLDUPMask(VT, Mask);
4626     IsUnary = true;
4627     break;
4628   case X86ISD::MOVSHDUP:
4629     DecodeMOVSHDUPMask(VT, Mask);
4630     IsUnary = true;
4631     break;
4632   case X86ISD::MOVDDUP:
4633     DecodeMOVDDUPMask(VT, Mask);
4634     IsUnary = true;
4635     break;
4636   case X86ISD::MOVLHPD:
4637   case X86ISD::MOVLPD:
4638   case X86ISD::MOVLPS:
4639     // Not yet implemented
4640     return false;
4641   default: llvm_unreachable("unknown target shuffle node");
4642   }
4643
4644   // If we have a fake unary shuffle, the shuffle mask is spread across two
4645   // inputs that are actually the same node. Re-map the mask to always point
4646   // into the first input.
4647   if (IsFakeUnary)
4648     for (int &M : Mask)
4649       if (M >= (int)Mask.size())
4650         M -= Mask.size();
4651
4652   return true;
4653 }
4654
4655 /// Returns the scalar element that will make up the ith
4656 /// element of the result of the vector shuffle.
4657 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4658                                    unsigned Depth) {
4659   if (Depth == 6)
4660     return SDValue();  // Limit search depth.
4661
4662   SDValue V = SDValue(N, 0);
4663   EVT VT = V.getValueType();
4664   unsigned Opcode = V.getOpcode();
4665
4666   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4667   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4668     int Elt = SV->getMaskElt(Index);
4669
4670     if (Elt < 0)
4671       return DAG.getUNDEF(VT.getVectorElementType());
4672
4673     unsigned NumElems = VT.getVectorNumElements();
4674     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4675                                          : SV->getOperand(1);
4676     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4677   }
4678
4679   // Recurse into target specific vector shuffles to find scalars.
4680   if (isTargetShuffle(Opcode)) {
4681     MVT ShufVT = V.getSimpleValueType();
4682     unsigned NumElems = ShufVT.getVectorNumElements();
4683     SmallVector<int, 16> ShuffleMask;
4684     bool IsUnary;
4685
4686     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4687       return SDValue();
4688
4689     int Elt = ShuffleMask[Index];
4690     if (Elt < 0)
4691       return DAG.getUNDEF(ShufVT.getVectorElementType());
4692
4693     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4694                                          : N->getOperand(1);
4695     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4696                                Depth+1);
4697   }
4698
4699   // Actual nodes that may contain scalar elements
4700   if (Opcode == ISD::BITCAST) {
4701     V = V.getOperand(0);
4702     EVT SrcVT = V.getValueType();
4703     unsigned NumElems = VT.getVectorNumElements();
4704
4705     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4706       return SDValue();
4707   }
4708
4709   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4710     return (Index == 0) ? V.getOperand(0)
4711                         : DAG.getUNDEF(VT.getVectorElementType());
4712
4713   if (V.getOpcode() == ISD::BUILD_VECTOR)
4714     return V.getOperand(Index);
4715
4716   return SDValue();
4717 }
4718
4719 /// Custom lower build_vector of v16i8.
4720 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4721                                        unsigned NumNonZero, unsigned NumZero,
4722                                        SelectionDAG &DAG,
4723                                        const X86Subtarget* Subtarget,
4724                                        const TargetLowering &TLI) {
4725   if (NumNonZero > 8)
4726     return SDValue();
4727
4728   SDLoc dl(Op);
4729   SDValue V;
4730   bool First = true;
4731
4732   // SSE4.1 - use PINSRB to insert each byte directly.
4733   if (Subtarget->hasSSE41()) {
4734     for (unsigned i = 0; i < 16; ++i) {
4735       bool isNonZero = (NonZeros & (1 << i)) != 0;
4736       if (isNonZero) {
4737         if (First) {
4738           if (NumZero)
4739             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4740           else
4741             V = DAG.getUNDEF(MVT::v16i8);
4742           First = false;
4743         }
4744         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4745                         MVT::v16i8, V, Op.getOperand(i),
4746                         DAG.getIntPtrConstant(i, dl));
4747       }
4748     }
4749
4750     return V;
4751   }
4752
4753   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4754   for (unsigned i = 0; i < 16; ++i) {
4755     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4756     if (ThisIsNonZero && First) {
4757       if (NumZero)
4758         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4759       else
4760         V = DAG.getUNDEF(MVT::v8i16);
4761       First = false;
4762     }
4763
4764     if ((i & 1) != 0) {
4765       SDValue ThisElt, LastElt;
4766       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4767       if (LastIsNonZero) {
4768         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4769                               MVT::i16, Op.getOperand(i-1));
4770       }
4771       if (ThisIsNonZero) {
4772         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4773         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4774                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4775         if (LastIsNonZero)
4776           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4777       } else
4778         ThisElt = LastElt;
4779
4780       if (ThisElt.getNode())
4781         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4782                         DAG.getIntPtrConstant(i/2, dl));
4783     }
4784   }
4785
4786   return DAG.getBitcast(MVT::v16i8, V);
4787 }
4788
4789 /// Custom lower build_vector of v8i16.
4790 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4791                                      unsigned NumNonZero, unsigned NumZero,
4792                                      SelectionDAG &DAG,
4793                                      const X86Subtarget* Subtarget,
4794                                      const TargetLowering &TLI) {
4795   if (NumNonZero > 4)
4796     return SDValue();
4797
4798   SDLoc dl(Op);
4799   SDValue V;
4800   bool First = true;
4801   for (unsigned i = 0; i < 8; ++i) {
4802     bool isNonZero = (NonZeros & (1 << i)) != 0;
4803     if (isNonZero) {
4804       if (First) {
4805         if (NumZero)
4806           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4807         else
4808           V = DAG.getUNDEF(MVT::v8i16);
4809         First = false;
4810       }
4811       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4812                       MVT::v8i16, V, Op.getOperand(i),
4813                       DAG.getIntPtrConstant(i, dl));
4814     }
4815   }
4816
4817   return V;
4818 }
4819
4820 /// Custom lower build_vector of v4i32 or v4f32.
4821 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4822                                      const X86Subtarget *Subtarget,
4823                                      const TargetLowering &TLI) {
4824   // Find all zeroable elements.
4825   std::bitset<4> Zeroable;
4826   for (int i=0; i < 4; ++i) {
4827     SDValue Elt = Op->getOperand(i);
4828     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4829   }
4830   assert(Zeroable.size() - Zeroable.count() > 1 &&
4831          "We expect at least two non-zero elements!");
4832
4833   // We only know how to deal with build_vector nodes where elements are either
4834   // zeroable or extract_vector_elt with constant index.
4835   SDValue FirstNonZero;
4836   unsigned FirstNonZeroIdx;
4837   for (unsigned i=0; i < 4; ++i) {
4838     if (Zeroable[i])
4839       continue;
4840     SDValue Elt = Op->getOperand(i);
4841     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4842         !isa<ConstantSDNode>(Elt.getOperand(1)))
4843       return SDValue();
4844     // Make sure that this node is extracting from a 128-bit vector.
4845     MVT VT = Elt.getOperand(0).getSimpleValueType();
4846     if (!VT.is128BitVector())
4847       return SDValue();
4848     if (!FirstNonZero.getNode()) {
4849       FirstNonZero = Elt;
4850       FirstNonZeroIdx = i;
4851     }
4852   }
4853
4854   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4855   SDValue V1 = FirstNonZero.getOperand(0);
4856   MVT VT = V1.getSimpleValueType();
4857
4858   // See if this build_vector can be lowered as a blend with zero.
4859   SDValue Elt;
4860   unsigned EltMaskIdx, EltIdx;
4861   int Mask[4];
4862   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4863     if (Zeroable[EltIdx]) {
4864       // The zero vector will be on the right hand side.
4865       Mask[EltIdx] = EltIdx+4;
4866       continue;
4867     }
4868
4869     Elt = Op->getOperand(EltIdx);
4870     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4871     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4872     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4873       break;
4874     Mask[EltIdx] = EltIdx;
4875   }
4876
4877   if (EltIdx == 4) {
4878     // Let the shuffle legalizer deal with blend operations.
4879     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4880     if (V1.getSimpleValueType() != VT)
4881       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4882     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4883   }
4884
4885   // See if we can lower this build_vector to a INSERTPS.
4886   if (!Subtarget->hasSSE41())
4887     return SDValue();
4888
4889   SDValue V2 = Elt.getOperand(0);
4890   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4891     V1 = SDValue();
4892
4893   bool CanFold = true;
4894   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4895     if (Zeroable[i])
4896       continue;
4897
4898     SDValue Current = Op->getOperand(i);
4899     SDValue SrcVector = Current->getOperand(0);
4900     if (!V1.getNode())
4901       V1 = SrcVector;
4902     CanFold = SrcVector == V1 &&
4903       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4904   }
4905
4906   if (!CanFold)
4907     return SDValue();
4908
4909   assert(V1.getNode() && "Expected at least two non-zero elements!");
4910   if (V1.getSimpleValueType() != MVT::v4f32)
4911     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4912   if (V2.getSimpleValueType() != MVT::v4f32)
4913     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4914
4915   // Ok, we can emit an INSERTPS instruction.
4916   unsigned ZMask = Zeroable.to_ulong();
4917
4918   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4919   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4920   SDLoc DL(Op);
4921   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4922                                DAG.getIntPtrConstant(InsertPSMask, DL));
4923   return DAG.getBitcast(VT, Result);
4924 }
4925
4926 /// Return a vector logical shift node.
4927 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4928                          unsigned NumBits, SelectionDAG &DAG,
4929                          const TargetLowering &TLI, SDLoc dl) {
4930   assert(VT.is128BitVector() && "Unknown type for VShift");
4931   MVT ShVT = MVT::v2i64;
4932   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4933   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4934   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4935   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4936   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4937   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4938 }
4939
4940 static SDValue
4941 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4942
4943   // Check if the scalar load can be widened into a vector load. And if
4944   // the address is "base + cst" see if the cst can be "absorbed" into
4945   // the shuffle mask.
4946   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4947     SDValue Ptr = LD->getBasePtr();
4948     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4949       return SDValue();
4950     EVT PVT = LD->getValueType(0);
4951     if (PVT != MVT::i32 && PVT != MVT::f32)
4952       return SDValue();
4953
4954     int FI = -1;
4955     int64_t Offset = 0;
4956     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4957       FI = FINode->getIndex();
4958       Offset = 0;
4959     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4960                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4961       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4962       Offset = Ptr.getConstantOperandVal(1);
4963       Ptr = Ptr.getOperand(0);
4964     } else {
4965       return SDValue();
4966     }
4967
4968     // FIXME: 256-bit vector instructions don't require a strict alignment,
4969     // improve this code to support it better.
4970     unsigned RequiredAlign = VT.getSizeInBits()/8;
4971     SDValue Chain = LD->getChain();
4972     // Make sure the stack object alignment is at least 16 or 32.
4973     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4974     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4975       if (MFI->isFixedObjectIndex(FI)) {
4976         // Can't change the alignment. FIXME: It's possible to compute
4977         // the exact stack offset and reference FI + adjust offset instead.
4978         // If someone *really* cares about this. That's the way to implement it.
4979         return SDValue();
4980       } else {
4981         MFI->setObjectAlignment(FI, RequiredAlign);
4982       }
4983     }
4984
4985     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4986     // Ptr + (Offset & ~15).
4987     if (Offset < 0)
4988       return SDValue();
4989     if ((Offset % RequiredAlign) & 3)
4990       return SDValue();
4991     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
4992     if (StartOffset) {
4993       SDLoc DL(Ptr);
4994       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4995                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4996     }
4997
4998     int EltNo = (Offset - StartOffset) >> 2;
4999     unsigned NumElems = VT.getVectorNumElements();
5000
5001     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5002     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5003                              LD->getPointerInfo().getWithOffset(StartOffset),
5004                              false, false, false, 0);
5005
5006     SmallVector<int, 8> Mask(NumElems, EltNo);
5007
5008     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5009   }
5010
5011   return SDValue();
5012 }
5013
5014 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5015 /// elements can be replaced by a single large load which has the same value as
5016 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5017 ///
5018 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5019 ///
5020 /// FIXME: we'd also like to handle the case where the last elements are zero
5021 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5022 /// There's even a handy isZeroNode for that purpose.
5023 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5024                                         SDLoc &DL, SelectionDAG &DAG,
5025                                         bool isAfterLegalize) {
5026   unsigned NumElems = Elts.size();
5027
5028   LoadSDNode *LDBase = nullptr;
5029   unsigned LastLoadedElt = -1U;
5030
5031   // For each element in the initializer, see if we've found a load or an undef.
5032   // If we don't find an initial load element, or later load elements are
5033   // non-consecutive, bail out.
5034   for (unsigned i = 0; i < NumElems; ++i) {
5035     SDValue Elt = Elts[i];
5036     // Look through a bitcast.
5037     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5038       Elt = Elt.getOperand(0);
5039     if (!Elt.getNode() ||
5040         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5041       return SDValue();
5042     if (!LDBase) {
5043       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5044         return SDValue();
5045       LDBase = cast<LoadSDNode>(Elt.getNode());
5046       LastLoadedElt = i;
5047       continue;
5048     }
5049     if (Elt.getOpcode() == ISD::UNDEF)
5050       continue;
5051
5052     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5053     EVT LdVT = Elt.getValueType();
5054     // Each loaded element must be the correct fractional portion of the
5055     // requested vector load.
5056     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5057       return SDValue();
5058     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5059       return SDValue();
5060     LastLoadedElt = i;
5061   }
5062
5063   // If we have found an entire vector of loads and undefs, then return a large
5064   // load of the entire vector width starting at the base pointer.  If we found
5065   // consecutive loads for the low half, generate a vzext_load node.
5066   if (LastLoadedElt == NumElems - 1) {
5067     assert(LDBase && "Did not find base load for merging consecutive loads");
5068     EVT EltVT = LDBase->getValueType(0);
5069     // Ensure that the input vector size for the merged loads matches the
5070     // cumulative size of the input elements.
5071     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5072       return SDValue();
5073
5074     if (isAfterLegalize &&
5075         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5076       return SDValue();
5077
5078     SDValue NewLd = SDValue();
5079
5080     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5081                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5082                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5083                         LDBase->getAlignment());
5084
5085     if (LDBase->hasAnyUseOfValue(1)) {
5086       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5087                                      SDValue(LDBase, 1),
5088                                      SDValue(NewLd.getNode(), 1));
5089       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5090       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5091                              SDValue(NewLd.getNode(), 1));
5092     }
5093
5094     return NewLd;
5095   }
5096
5097   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5098   //of a v4i32 / v4f32. It's probably worth generalizing.
5099   EVT EltVT = VT.getVectorElementType();
5100   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5101       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5102     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5103     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5104     SDValue ResNode =
5105         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5106                                 LDBase->getPointerInfo(),
5107                                 LDBase->getAlignment(),
5108                                 false/*isVolatile*/, true/*ReadMem*/,
5109                                 false/*WriteMem*/);
5110
5111     // Make sure the newly-created LOAD is in the same position as LDBase in
5112     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5113     // update uses of LDBase's output chain to use the TokenFactor.
5114     if (LDBase->hasAnyUseOfValue(1)) {
5115       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5116                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5117       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5118       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5119                              SDValue(ResNode.getNode(), 1));
5120     }
5121
5122     return DAG.getBitcast(VT, ResNode);
5123   }
5124   return SDValue();
5125 }
5126
5127 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5128 /// to generate a splat value for the following cases:
5129 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5130 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5131 /// a scalar load, or a constant.
5132 /// The VBROADCAST node is returned when a pattern is found,
5133 /// or SDValue() otherwise.
5134 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5135                                     SelectionDAG &DAG) {
5136   // VBROADCAST requires AVX.
5137   // TODO: Splats could be generated for non-AVX CPUs using SSE
5138   // instructions, but there's less potential gain for only 128-bit vectors.
5139   if (!Subtarget->hasAVX())
5140     return SDValue();
5141
5142   MVT VT = Op.getSimpleValueType();
5143   SDLoc dl(Op);
5144
5145   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5146          "Unsupported vector type for broadcast.");
5147
5148   SDValue Ld;
5149   bool ConstSplatVal;
5150
5151   switch (Op.getOpcode()) {
5152     default:
5153       // Unknown pattern found.
5154       return SDValue();
5155
5156     case ISD::BUILD_VECTOR: {
5157       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5158       BitVector UndefElements;
5159       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5160
5161       // We need a splat of a single value to use broadcast, and it doesn't
5162       // make any sense if the value is only in one element of the vector.
5163       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5164         return SDValue();
5165
5166       Ld = Splat;
5167       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5168                        Ld.getOpcode() == ISD::ConstantFP);
5169
5170       // Make sure that all of the users of a non-constant load are from the
5171       // BUILD_VECTOR node.
5172       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5173         return SDValue();
5174       break;
5175     }
5176
5177     case ISD::VECTOR_SHUFFLE: {
5178       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5179
5180       // Shuffles must have a splat mask where the first element is
5181       // broadcasted.
5182       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5183         return SDValue();
5184
5185       SDValue Sc = Op.getOperand(0);
5186       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5187           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5188
5189         if (!Subtarget->hasInt256())
5190           return SDValue();
5191
5192         // Use the register form of the broadcast instruction available on AVX2.
5193         if (VT.getSizeInBits() >= 256)
5194           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5195         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5196       }
5197
5198       Ld = Sc.getOperand(0);
5199       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5200                        Ld.getOpcode() == ISD::ConstantFP);
5201
5202       // The scalar_to_vector node and the suspected
5203       // load node must have exactly one user.
5204       // Constants may have multiple users.
5205
5206       // AVX-512 has register version of the broadcast
5207       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5208         Ld.getValueType().getSizeInBits() >= 32;
5209       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5210           !hasRegVer))
5211         return SDValue();
5212       break;
5213     }
5214   }
5215
5216   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5217   bool IsGE256 = (VT.getSizeInBits() >= 256);
5218
5219   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5220   // instruction to save 8 or more bytes of constant pool data.
5221   // TODO: If multiple splats are generated to load the same constant,
5222   // it may be detrimental to overall size. There needs to be a way to detect
5223   // that condition to know if this is truly a size win.
5224   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5225
5226   // Handle broadcasting a single constant scalar from the constant pool
5227   // into a vector.
5228   // On Sandybridge (no AVX2), it is still better to load a constant vector
5229   // from the constant pool and not to broadcast it from a scalar.
5230   // But override that restriction when optimizing for size.
5231   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5232   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5233     EVT CVT = Ld.getValueType();
5234     assert(!CVT.isVector() && "Must not broadcast a vector type");
5235
5236     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5237     // For size optimization, also splat v2f64 and v2i64, and for size opt
5238     // with AVX2, also splat i8 and i16.
5239     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5240     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5241         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5242       const Constant *C = nullptr;
5243       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5244         C = CI->getConstantIntValue();
5245       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5246         C = CF->getConstantFPValue();
5247
5248       assert(C && "Invalid constant type");
5249
5250       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5251       SDValue CP =
5252           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5253       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5254       Ld = DAG.getLoad(
5255           CVT, dl, DAG.getEntryNode(), CP,
5256           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5257           false, false, Alignment);
5258
5259       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5260     }
5261   }
5262
5263   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5264
5265   // Handle AVX2 in-register broadcasts.
5266   if (!IsLoad && Subtarget->hasInt256() &&
5267       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5268     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5269
5270   // The scalar source must be a normal load.
5271   if (!IsLoad)
5272     return SDValue();
5273
5274   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5275       (Subtarget->hasVLX() && ScalarSize == 64))
5276     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5277
5278   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5279   // double since there is no vbroadcastsd xmm
5280   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5281     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5282       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5283   }
5284
5285   // Unsupported broadcast.
5286   return SDValue();
5287 }
5288
5289 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5290 /// underlying vector and index.
5291 ///
5292 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5293 /// index.
5294 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5295                                          SDValue ExtIdx) {
5296   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5297   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5298     return Idx;
5299
5300   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5301   // lowered this:
5302   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5303   // to:
5304   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5305   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5306   //                           undef)
5307   //                       Constant<0>)
5308   // In this case the vector is the extract_subvector expression and the index
5309   // is 2, as specified by the shuffle.
5310   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5311   SDValue ShuffleVec = SVOp->getOperand(0);
5312   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5313   assert(ShuffleVecVT.getVectorElementType() ==
5314          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5315
5316   int ShuffleIdx = SVOp->getMaskElt(Idx);
5317   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5318     ExtractedFromVec = ShuffleVec;
5319     return ShuffleIdx;
5320   }
5321   return Idx;
5322 }
5323
5324 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5325   MVT VT = Op.getSimpleValueType();
5326
5327   // Skip if insert_vec_elt is not supported.
5328   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5329   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5330     return SDValue();
5331
5332   SDLoc DL(Op);
5333   unsigned NumElems = Op.getNumOperands();
5334
5335   SDValue VecIn1;
5336   SDValue VecIn2;
5337   SmallVector<unsigned, 4> InsertIndices;
5338   SmallVector<int, 8> Mask(NumElems, -1);
5339
5340   for (unsigned i = 0; i != NumElems; ++i) {
5341     unsigned Opc = Op.getOperand(i).getOpcode();
5342
5343     if (Opc == ISD::UNDEF)
5344       continue;
5345
5346     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5347       // Quit if more than 1 elements need inserting.
5348       if (InsertIndices.size() > 1)
5349         return SDValue();
5350
5351       InsertIndices.push_back(i);
5352       continue;
5353     }
5354
5355     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5356     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5357     // Quit if non-constant index.
5358     if (!isa<ConstantSDNode>(ExtIdx))
5359       return SDValue();
5360     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5361
5362     // Quit if extracted from vector of different type.
5363     if (ExtractedFromVec.getValueType() != VT)
5364       return SDValue();
5365
5366     if (!VecIn1.getNode())
5367       VecIn1 = ExtractedFromVec;
5368     else if (VecIn1 != ExtractedFromVec) {
5369       if (!VecIn2.getNode())
5370         VecIn2 = ExtractedFromVec;
5371       else if (VecIn2 != ExtractedFromVec)
5372         // Quit if more than 2 vectors to shuffle
5373         return SDValue();
5374     }
5375
5376     if (ExtractedFromVec == VecIn1)
5377       Mask[i] = Idx;
5378     else if (ExtractedFromVec == VecIn2)
5379       Mask[i] = Idx + NumElems;
5380   }
5381
5382   if (!VecIn1.getNode())
5383     return SDValue();
5384
5385   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5386   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5387   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5388     unsigned Idx = InsertIndices[i];
5389     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5390                      DAG.getIntPtrConstant(Idx, DL));
5391   }
5392
5393   return NV;
5394 }
5395
5396 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5397   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5398          Op.getScalarValueSizeInBits() == 1 &&
5399          "Can not convert non-constant vector");
5400   uint64_t Immediate = 0;
5401   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5402     SDValue In = Op.getOperand(idx);
5403     if (In.getOpcode() != ISD::UNDEF)
5404       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5405   }
5406   SDLoc dl(Op);
5407   MVT VT =
5408    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5409   return DAG.getConstant(Immediate, dl, VT);
5410 }
5411 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5412 SDValue
5413 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5414
5415   MVT VT = Op.getSimpleValueType();
5416   assert((VT.getVectorElementType() == MVT::i1) &&
5417          "Unexpected type in LowerBUILD_VECTORvXi1!");
5418
5419   SDLoc dl(Op);
5420   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5421     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5422     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5423     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5424   }
5425
5426   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5427     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5428     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5429     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5430   }
5431
5432   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5433     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5434     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5435       return DAG.getBitcast(VT, Imm);
5436     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5437     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5438                         DAG.getIntPtrConstant(0, dl));
5439   }
5440
5441   // Vector has one or more non-const elements
5442   uint64_t Immediate = 0;
5443   SmallVector<unsigned, 16> NonConstIdx;
5444   bool IsSplat = true;
5445   bool HasConstElts = false;
5446   int SplatIdx = -1;
5447   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5448     SDValue In = Op.getOperand(idx);
5449     if (In.getOpcode() == ISD::UNDEF)
5450       continue;
5451     if (!isa<ConstantSDNode>(In))
5452       NonConstIdx.push_back(idx);
5453     else {
5454       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5455       HasConstElts = true;
5456     }
5457     if (SplatIdx == -1)
5458       SplatIdx = idx;
5459     else if (In != Op.getOperand(SplatIdx))
5460       IsSplat = false;
5461   }
5462
5463   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5464   if (IsSplat)
5465     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5466                        DAG.getConstant(1, dl, VT),
5467                        DAG.getConstant(0, dl, VT));
5468
5469   // insert elements one by one
5470   SDValue DstVec;
5471   SDValue Imm;
5472   if (Immediate) {
5473     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5474     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5475   }
5476   else if (HasConstElts)
5477     Imm = DAG.getConstant(0, dl, VT);
5478   else
5479     Imm = DAG.getUNDEF(VT);
5480   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5481     DstVec = DAG.getBitcast(VT, Imm);
5482   else {
5483     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5484     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5485                          DAG.getIntPtrConstant(0, dl));
5486   }
5487
5488   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5489     unsigned InsertIdx = NonConstIdx[i];
5490     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5491                          Op.getOperand(InsertIdx),
5492                          DAG.getIntPtrConstant(InsertIdx, dl));
5493   }
5494   return DstVec;
5495 }
5496
5497 /// \brief Return true if \p N implements a horizontal binop and return the
5498 /// operands for the horizontal binop into V0 and V1.
5499 ///
5500 /// This is a helper function of LowerToHorizontalOp().
5501 /// This function checks that the build_vector \p N in input implements a
5502 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5503 /// operation to match.
5504 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5505 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5506 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5507 /// arithmetic sub.
5508 ///
5509 /// This function only analyzes elements of \p N whose indices are
5510 /// in range [BaseIdx, LastIdx).
5511 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5512                               SelectionDAG &DAG,
5513                               unsigned BaseIdx, unsigned LastIdx,
5514                               SDValue &V0, SDValue &V1) {
5515   EVT VT = N->getValueType(0);
5516
5517   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5518   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5519          "Invalid Vector in input!");
5520
5521   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5522   bool CanFold = true;
5523   unsigned ExpectedVExtractIdx = BaseIdx;
5524   unsigned NumElts = LastIdx - BaseIdx;
5525   V0 = DAG.getUNDEF(VT);
5526   V1 = DAG.getUNDEF(VT);
5527
5528   // Check if N implements a horizontal binop.
5529   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5530     SDValue Op = N->getOperand(i + BaseIdx);
5531
5532     // Skip UNDEFs.
5533     if (Op->getOpcode() == ISD::UNDEF) {
5534       // Update the expected vector extract index.
5535       if (i * 2 == NumElts)
5536         ExpectedVExtractIdx = BaseIdx;
5537       ExpectedVExtractIdx += 2;
5538       continue;
5539     }
5540
5541     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5542
5543     if (!CanFold)
5544       break;
5545
5546     SDValue Op0 = Op.getOperand(0);
5547     SDValue Op1 = Op.getOperand(1);
5548
5549     // Try to match the following pattern:
5550     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5551     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5552         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5553         Op0.getOperand(0) == Op1.getOperand(0) &&
5554         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5555         isa<ConstantSDNode>(Op1.getOperand(1)));
5556     if (!CanFold)
5557       break;
5558
5559     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5560     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5561
5562     if (i * 2 < NumElts) {
5563       if (V0.getOpcode() == ISD::UNDEF) {
5564         V0 = Op0.getOperand(0);
5565         if (V0.getValueType() != VT)
5566           return false;
5567       }
5568     } else {
5569       if (V1.getOpcode() == ISD::UNDEF) {
5570         V1 = Op0.getOperand(0);
5571         if (V1.getValueType() != VT)
5572           return false;
5573       }
5574       if (i * 2 == NumElts)
5575         ExpectedVExtractIdx = BaseIdx;
5576     }
5577
5578     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5579     if (I0 == ExpectedVExtractIdx)
5580       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5581     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5582       // Try to match the following dag sequence:
5583       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5584       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5585     } else
5586       CanFold = false;
5587
5588     ExpectedVExtractIdx += 2;
5589   }
5590
5591   return CanFold;
5592 }
5593
5594 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5595 /// a concat_vector.
5596 ///
5597 /// This is a helper function of LowerToHorizontalOp().
5598 /// This function expects two 256-bit vectors called V0 and V1.
5599 /// At first, each vector is split into two separate 128-bit vectors.
5600 /// Then, the resulting 128-bit vectors are used to implement two
5601 /// horizontal binary operations.
5602 ///
5603 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5604 ///
5605 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5606 /// the two new horizontal binop.
5607 /// When Mode is set, the first horizontal binop dag node would take as input
5608 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5609 /// horizontal binop dag node would take as input the lower 128-bit of V1
5610 /// and the upper 128-bit of V1.
5611 ///   Example:
5612 ///     HADD V0_LO, V0_HI
5613 ///     HADD V1_LO, V1_HI
5614 ///
5615 /// Otherwise, the first horizontal binop dag node takes as input the lower
5616 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5617 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5618 ///   Example:
5619 ///     HADD V0_LO, V1_LO
5620 ///     HADD V0_HI, V1_HI
5621 ///
5622 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5623 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5624 /// the upper 128-bits of the result.
5625 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5626                                      SDLoc DL, SelectionDAG &DAG,
5627                                      unsigned X86Opcode, bool Mode,
5628                                      bool isUndefLO, bool isUndefHI) {
5629   EVT VT = V0.getValueType();
5630   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5631          "Invalid nodes in input!");
5632
5633   unsigned NumElts = VT.getVectorNumElements();
5634   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5635   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5636   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5637   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5638   EVT NewVT = V0_LO.getValueType();
5639
5640   SDValue LO = DAG.getUNDEF(NewVT);
5641   SDValue HI = DAG.getUNDEF(NewVT);
5642
5643   if (Mode) {
5644     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5645     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5646       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5647     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5648       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5649   } else {
5650     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5651     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5652                        V1_LO->getOpcode() != ISD::UNDEF))
5653       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5654
5655     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5656                        V1_HI->getOpcode() != ISD::UNDEF))
5657       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5658   }
5659
5660   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5661 }
5662
5663 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5664 /// node.
5665 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5666                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5667   EVT VT = BV->getValueType(0);
5668   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5669       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5670     return SDValue();
5671
5672   SDLoc DL(BV);
5673   unsigned NumElts = VT.getVectorNumElements();
5674   SDValue InVec0 = DAG.getUNDEF(VT);
5675   SDValue InVec1 = DAG.getUNDEF(VT);
5676
5677   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5678           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5679
5680   // Odd-numbered elements in the input build vector are obtained from
5681   // adding two integer/float elements.
5682   // Even-numbered elements in the input build vector are obtained from
5683   // subtracting two integer/float elements.
5684   unsigned ExpectedOpcode = ISD::FSUB;
5685   unsigned NextExpectedOpcode = ISD::FADD;
5686   bool AddFound = false;
5687   bool SubFound = false;
5688
5689   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5690     SDValue Op = BV->getOperand(i);
5691
5692     // Skip 'undef' values.
5693     unsigned Opcode = Op.getOpcode();
5694     if (Opcode == ISD::UNDEF) {
5695       std::swap(ExpectedOpcode, NextExpectedOpcode);
5696       continue;
5697     }
5698
5699     // Early exit if we found an unexpected opcode.
5700     if (Opcode != ExpectedOpcode)
5701       return SDValue();
5702
5703     SDValue Op0 = Op.getOperand(0);
5704     SDValue Op1 = Op.getOperand(1);
5705
5706     // Try to match the following pattern:
5707     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5708     // Early exit if we cannot match that sequence.
5709     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5710         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5711         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5712         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5713         Op0.getOperand(1) != Op1.getOperand(1))
5714       return SDValue();
5715
5716     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5717     if (I0 != i)
5718       return SDValue();
5719
5720     // We found a valid add/sub node. Update the information accordingly.
5721     if (i & 1)
5722       AddFound = true;
5723     else
5724       SubFound = true;
5725
5726     // Update InVec0 and InVec1.
5727     if (InVec0.getOpcode() == ISD::UNDEF) {
5728       InVec0 = Op0.getOperand(0);
5729       if (InVec0.getValueType() != VT)
5730         return SDValue();
5731     }
5732     if (InVec1.getOpcode() == ISD::UNDEF) {
5733       InVec1 = Op1.getOperand(0);
5734       if (InVec1.getValueType() != VT)
5735         return SDValue();
5736     }
5737
5738     // Make sure that operands in input to each add/sub node always
5739     // come from a same pair of vectors.
5740     if (InVec0 != Op0.getOperand(0)) {
5741       if (ExpectedOpcode == ISD::FSUB)
5742         return SDValue();
5743
5744       // FADD is commutable. Try to commute the operands
5745       // and then test again.
5746       std::swap(Op0, Op1);
5747       if (InVec0 != Op0.getOperand(0))
5748         return SDValue();
5749     }
5750
5751     if (InVec1 != Op1.getOperand(0))
5752       return SDValue();
5753
5754     // Update the pair of expected opcodes.
5755     std::swap(ExpectedOpcode, NextExpectedOpcode);
5756   }
5757
5758   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5759   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5760       InVec1.getOpcode() != ISD::UNDEF)
5761     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5762
5763   return SDValue();
5764 }
5765
5766 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5767 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5768                                    const X86Subtarget *Subtarget,
5769                                    SelectionDAG &DAG) {
5770   EVT VT = BV->getValueType(0);
5771   unsigned NumElts = VT.getVectorNumElements();
5772   unsigned NumUndefsLO = 0;
5773   unsigned NumUndefsHI = 0;
5774   unsigned Half = NumElts/2;
5775
5776   // Count the number of UNDEF operands in the build_vector in input.
5777   for (unsigned i = 0, e = Half; i != e; ++i)
5778     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5779       NumUndefsLO++;
5780
5781   for (unsigned i = Half, e = NumElts; i != e; ++i)
5782     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5783       NumUndefsHI++;
5784
5785   // Early exit if this is either a build_vector of all UNDEFs or all the
5786   // operands but one are UNDEF.
5787   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5788     return SDValue();
5789
5790   SDLoc DL(BV);
5791   SDValue InVec0, InVec1;
5792   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5793     // Try to match an SSE3 float HADD/HSUB.
5794     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5795       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5796
5797     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5798       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5799   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5800     // Try to match an SSSE3 integer HADD/HSUB.
5801     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5802       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5803
5804     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5805       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5806   }
5807
5808   if (!Subtarget->hasAVX())
5809     return SDValue();
5810
5811   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5812     // Try to match an AVX horizontal add/sub of packed single/double
5813     // precision floating point values from 256-bit vectors.
5814     SDValue InVec2, InVec3;
5815     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5816         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5817         ((InVec0.getOpcode() == ISD::UNDEF ||
5818           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5819         ((InVec1.getOpcode() == ISD::UNDEF ||
5820           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5821       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5822
5823     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5824         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5825         ((InVec0.getOpcode() == ISD::UNDEF ||
5826           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5827         ((InVec1.getOpcode() == ISD::UNDEF ||
5828           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5829       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5830   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5831     // Try to match an AVX2 horizontal add/sub of signed integers.
5832     SDValue InVec2, InVec3;
5833     unsigned X86Opcode;
5834     bool CanFold = true;
5835
5836     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5837         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5838         ((InVec0.getOpcode() == ISD::UNDEF ||
5839           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5840         ((InVec1.getOpcode() == ISD::UNDEF ||
5841           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5842       X86Opcode = X86ISD::HADD;
5843     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5844         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5845         ((InVec0.getOpcode() == ISD::UNDEF ||
5846           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5847         ((InVec1.getOpcode() == ISD::UNDEF ||
5848           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5849       X86Opcode = X86ISD::HSUB;
5850     else
5851       CanFold = false;
5852
5853     if (CanFold) {
5854       // Fold this build_vector into a single horizontal add/sub.
5855       // Do this only if the target has AVX2.
5856       if (Subtarget->hasAVX2())
5857         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5858
5859       // Do not try to expand this build_vector into a pair of horizontal
5860       // add/sub if we can emit a pair of scalar add/sub.
5861       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5862         return SDValue();
5863
5864       // Convert this build_vector into a pair of horizontal binop followed by
5865       // a concat vector.
5866       bool isUndefLO = NumUndefsLO == Half;
5867       bool isUndefHI = NumUndefsHI == Half;
5868       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5869                                    isUndefLO, isUndefHI);
5870     }
5871   }
5872
5873   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5874        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5875     unsigned X86Opcode;
5876     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5877       X86Opcode = X86ISD::HADD;
5878     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5879       X86Opcode = X86ISD::HSUB;
5880     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5881       X86Opcode = X86ISD::FHADD;
5882     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5883       X86Opcode = X86ISD::FHSUB;
5884     else
5885       return SDValue();
5886
5887     // Don't try to expand this build_vector into a pair of horizontal add/sub
5888     // if we can simply emit a pair of scalar add/sub.
5889     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5890       return SDValue();
5891
5892     // Convert this build_vector into two horizontal add/sub followed by
5893     // a concat vector.
5894     bool isUndefLO = NumUndefsLO == Half;
5895     bool isUndefHI = NumUndefsHI == Half;
5896     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5897                                  isUndefLO, isUndefHI);
5898   }
5899
5900   return SDValue();
5901 }
5902
5903 SDValue
5904 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5905   SDLoc dl(Op);
5906
5907   MVT VT = Op.getSimpleValueType();
5908   MVT ExtVT = VT.getVectorElementType();
5909   unsigned NumElems = Op.getNumOperands();
5910
5911   // Generate vectors for predicate vectors.
5912   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5913     return LowerBUILD_VECTORvXi1(Op, DAG);
5914
5915   // Vectors containing all zeros can be matched by pxor and xorps later
5916   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5917     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5918     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5919     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5920       return Op;
5921
5922     return getZeroVector(VT, Subtarget, DAG, dl);
5923   }
5924
5925   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5926   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5927   // vpcmpeqd on 256-bit vectors.
5928   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5929     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5930       return Op;
5931
5932     if (!VT.is512BitVector())
5933       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5934   }
5935
5936   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5937   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5938     return AddSub;
5939   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5940     return HorizontalOp;
5941   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5942     return Broadcast;
5943
5944   unsigned EVTBits = ExtVT.getSizeInBits();
5945
5946   unsigned NumZero  = 0;
5947   unsigned NumNonZero = 0;
5948   unsigned NonZeros = 0;
5949   bool IsAllConstants = true;
5950   SmallSet<SDValue, 8> Values;
5951   for (unsigned i = 0; i < NumElems; ++i) {
5952     SDValue Elt = Op.getOperand(i);
5953     if (Elt.getOpcode() == ISD::UNDEF)
5954       continue;
5955     Values.insert(Elt);
5956     if (Elt.getOpcode() != ISD::Constant &&
5957         Elt.getOpcode() != ISD::ConstantFP)
5958       IsAllConstants = false;
5959     if (X86::isZeroNode(Elt))
5960       NumZero++;
5961     else {
5962       NonZeros |= (1 << i);
5963       NumNonZero++;
5964     }
5965   }
5966
5967   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5968   if (NumNonZero == 0)
5969     return DAG.getUNDEF(VT);
5970
5971   // Special case for single non-zero, non-undef, element.
5972   if (NumNonZero == 1) {
5973     unsigned Idx = countTrailingZeros(NonZeros);
5974     SDValue Item = Op.getOperand(Idx);
5975
5976     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5977     // the value are obviously zero, truncate the value to i32 and do the
5978     // insertion that way.  Only do this if the value is non-constant or if the
5979     // value is a constant being inserted into element 0.  It is cheaper to do
5980     // a constant pool load than it is to do a movd + shuffle.
5981     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5982         (!IsAllConstants || Idx == 0)) {
5983       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5984         // Handle SSE only.
5985         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5986         EVT VecVT = MVT::v4i32;
5987
5988         // Truncate the value (which may itself be a constant) to i32, and
5989         // convert it to a vector with movd (S2V+shuffle to zero extend).
5990         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5991         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5992         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5993                                       Item, Idx * 2, true, Subtarget, DAG));
5994       }
5995     }
5996
5997     // If we have a constant or non-constant insertion into the low element of
5998     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5999     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6000     // depending on what the source datatype is.
6001     if (Idx == 0) {
6002       if (NumZero == 0)
6003         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6004
6005       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6006           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6007         if (VT.is512BitVector()) {
6008           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6009           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6010                              Item, DAG.getIntPtrConstant(0, dl));
6011         }
6012         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6013                "Expected an SSE value type!");
6014         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6015         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6016         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6017       }
6018
6019       // We can't directly insert an i8 or i16 into a vector, so zero extend
6020       // it to i32 first.
6021       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6022         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6023         if (VT.is256BitVector()) {
6024           if (Subtarget->hasAVX()) {
6025             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6026             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6027           } else {
6028             // Without AVX, we need to extend to a 128-bit vector and then
6029             // insert into the 256-bit vector.
6030             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6031             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6032             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6033           }
6034         } else {
6035           assert(VT.is128BitVector() && "Expected an SSE value type!");
6036           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6037           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6038         }
6039         return DAG.getBitcast(VT, Item);
6040       }
6041     }
6042
6043     // Is it a vector logical left shift?
6044     if (NumElems == 2 && Idx == 1 &&
6045         X86::isZeroNode(Op.getOperand(0)) &&
6046         !X86::isZeroNode(Op.getOperand(1))) {
6047       unsigned NumBits = VT.getSizeInBits();
6048       return getVShift(true, VT,
6049                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6050                                    VT, Op.getOperand(1)),
6051                        NumBits/2, DAG, *this, dl);
6052     }
6053
6054     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6055       return SDValue();
6056
6057     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6058     // is a non-constant being inserted into an element other than the low one,
6059     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6060     // movd/movss) to move this into the low element, then shuffle it into
6061     // place.
6062     if (EVTBits == 32) {
6063       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6064       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6065     }
6066   }
6067
6068   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6069   if (Values.size() == 1) {
6070     if (EVTBits == 32) {
6071       // Instead of a shuffle like this:
6072       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6073       // Check if it's possible to issue this instead.
6074       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6075       unsigned Idx = countTrailingZeros(NonZeros);
6076       SDValue Item = Op.getOperand(Idx);
6077       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6078         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6079     }
6080     return SDValue();
6081   }
6082
6083   // A vector full of immediates; various special cases are already
6084   // handled, so this is best done with a single constant-pool load.
6085   if (IsAllConstants)
6086     return SDValue();
6087
6088   // For AVX-length vectors, see if we can use a vector load to get all of the
6089   // elements, otherwise build the individual 128-bit pieces and use
6090   // shuffles to put them in place.
6091   if (VT.is256BitVector() || VT.is512BitVector()) {
6092     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6093
6094     // Check for a build vector of consecutive loads.
6095     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6096       return LD;
6097
6098     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6099
6100     // Build both the lower and upper subvector.
6101     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6102                                 makeArrayRef(&V[0], NumElems/2));
6103     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6104                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6105
6106     // Recreate the wider vector with the lower and upper part.
6107     if (VT.is256BitVector())
6108       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6109     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6110   }
6111
6112   // Let legalizer expand 2-wide build_vectors.
6113   if (EVTBits == 64) {
6114     if (NumNonZero == 1) {
6115       // One half is zero or undef.
6116       unsigned Idx = countTrailingZeros(NonZeros);
6117       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6118                                  Op.getOperand(Idx));
6119       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6120     }
6121     return SDValue();
6122   }
6123
6124   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6125   if (EVTBits == 8 && NumElems == 16)
6126     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6127                                         Subtarget, *this))
6128       return V;
6129
6130   if (EVTBits == 16 && NumElems == 8)
6131     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6132                                       Subtarget, *this))
6133       return V;
6134
6135   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6136   if (EVTBits == 32 && NumElems == 4)
6137     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6138       return V;
6139
6140   // If element VT is == 32 bits, turn it into a number of shuffles.
6141   SmallVector<SDValue, 8> V(NumElems);
6142   if (NumElems == 4 && NumZero > 0) {
6143     for (unsigned i = 0; i < 4; ++i) {
6144       bool isZero = !(NonZeros & (1 << i));
6145       if (isZero)
6146         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6147       else
6148         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6149     }
6150
6151     for (unsigned i = 0; i < 2; ++i) {
6152       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6153         default: break;
6154         case 0:
6155           V[i] = V[i*2];  // Must be a zero vector.
6156           break;
6157         case 1:
6158           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6159           break;
6160         case 2:
6161           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6162           break;
6163         case 3:
6164           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6165           break;
6166       }
6167     }
6168
6169     bool Reverse1 = (NonZeros & 0x3) == 2;
6170     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6171     int MaskVec[] = {
6172       Reverse1 ? 1 : 0,
6173       Reverse1 ? 0 : 1,
6174       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6175       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6176     };
6177     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6178   }
6179
6180   if (Values.size() > 1 && VT.is128BitVector()) {
6181     // Check for a build vector of consecutive loads.
6182     for (unsigned i = 0; i < NumElems; ++i)
6183       V[i] = Op.getOperand(i);
6184
6185     // Check for elements which are consecutive loads.
6186     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6187       return LD;
6188
6189     // Check for a build vector from mostly shuffle plus few inserting.
6190     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6191       return Sh;
6192
6193     // For SSE 4.1, use insertps to put the high elements into the low element.
6194     if (Subtarget->hasSSE41()) {
6195       SDValue Result;
6196       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6197         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6198       else
6199         Result = DAG.getUNDEF(VT);
6200
6201       for (unsigned i = 1; i < NumElems; ++i) {
6202         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6203         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6204                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6205       }
6206       return Result;
6207     }
6208
6209     // Otherwise, expand into a number of unpckl*, start by extending each of
6210     // our (non-undef) elements to the full vector width with the element in the
6211     // bottom slot of the vector (which generates no code for SSE).
6212     for (unsigned i = 0; i < NumElems; ++i) {
6213       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6214         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6215       else
6216         V[i] = DAG.getUNDEF(VT);
6217     }
6218
6219     // Next, we iteratively mix elements, e.g. for v4f32:
6220     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6221     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6222     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6223     unsigned EltStride = NumElems >> 1;
6224     while (EltStride != 0) {
6225       for (unsigned i = 0; i < EltStride; ++i) {
6226         // If V[i+EltStride] is undef and this is the first round of mixing,
6227         // then it is safe to just drop this shuffle: V[i] is already in the
6228         // right place, the one element (since it's the first round) being
6229         // inserted as undef can be dropped.  This isn't safe for successive
6230         // rounds because they will permute elements within both vectors.
6231         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6232             EltStride == NumElems/2)
6233           continue;
6234
6235         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6236       }
6237       EltStride >>= 1;
6238     }
6239     return V[0];
6240   }
6241   return SDValue();
6242 }
6243
6244 // 256-bit AVX can use the vinsertf128 instruction
6245 // to create 256-bit vectors from two other 128-bit ones.
6246 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6247   SDLoc dl(Op);
6248   MVT ResVT = Op.getSimpleValueType();
6249
6250   assert((ResVT.is256BitVector() ||
6251           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6252
6253   SDValue V1 = Op.getOperand(0);
6254   SDValue V2 = Op.getOperand(1);
6255   unsigned NumElems = ResVT.getVectorNumElements();
6256   if (ResVT.is256BitVector())
6257     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6258
6259   if (Op.getNumOperands() == 4) {
6260     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6261                                 ResVT.getVectorNumElements()/2);
6262     SDValue V3 = Op.getOperand(2);
6263     SDValue V4 = Op.getOperand(3);
6264     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6265       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6266   }
6267   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6268 }
6269
6270 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6271                                        const X86Subtarget *Subtarget,
6272                                        SelectionDAG & DAG) {
6273   SDLoc dl(Op);
6274   MVT ResVT = Op.getSimpleValueType();
6275   unsigned NumOfOperands = Op.getNumOperands();
6276
6277   assert(isPowerOf2_32(NumOfOperands) &&
6278          "Unexpected number of operands in CONCAT_VECTORS");
6279
6280   if (NumOfOperands > 2) {
6281     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6282                                   ResVT.getVectorNumElements()/2);
6283     SmallVector<SDValue, 2> Ops;
6284     for (unsigned i = 0; i < NumOfOperands/2; i++)
6285       Ops.push_back(Op.getOperand(i));
6286     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6287     Ops.clear();
6288     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6289       Ops.push_back(Op.getOperand(i));
6290     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6291     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6292   }
6293
6294   SDValue V1 = Op.getOperand(0);
6295   SDValue V2 = Op.getOperand(1);
6296   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6297   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6298
6299   if (IsZeroV1 && IsZeroV2)
6300     return getZeroVector(ResVT, Subtarget, DAG, dl);
6301
6302   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6303   SDValue Undef = DAG.getUNDEF(ResVT);
6304   unsigned NumElems = ResVT.getVectorNumElements();
6305   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6306
6307   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6308   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6309   if (IsZeroV1)
6310     return V2;
6311
6312   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6313   // Zero the upper bits of V1
6314   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6315   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6316   if (IsZeroV2)
6317     return V1;
6318   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6319 }
6320
6321 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6322                                    const X86Subtarget *Subtarget,
6323                                    SelectionDAG &DAG) {
6324   MVT VT = Op.getSimpleValueType();
6325   if (VT.getVectorElementType() == MVT::i1)
6326     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6327
6328   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6329          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6330           Op.getNumOperands() == 4)));
6331
6332   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6333   // from two other 128-bit ones.
6334
6335   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6336   return LowerAVXCONCAT_VECTORS(Op, DAG);
6337 }
6338
6339
6340 //===----------------------------------------------------------------------===//
6341 // Vector shuffle lowering
6342 //
6343 // This is an experimental code path for lowering vector shuffles on x86. It is
6344 // designed to handle arbitrary vector shuffles and blends, gracefully
6345 // degrading performance as necessary. It works hard to recognize idiomatic
6346 // shuffles and lower them to optimal instruction patterns without leaving
6347 // a framework that allows reasonably efficient handling of all vector shuffle
6348 // patterns.
6349 //===----------------------------------------------------------------------===//
6350
6351 /// \brief Tiny helper function to identify a no-op mask.
6352 ///
6353 /// This is a somewhat boring predicate function. It checks whether the mask
6354 /// array input, which is assumed to be a single-input shuffle mask of the kind
6355 /// used by the X86 shuffle instructions (not a fully general
6356 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6357 /// in-place shuffle are 'no-op's.
6358 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6359   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6360     if (Mask[i] != -1 && Mask[i] != i)
6361       return false;
6362   return true;
6363 }
6364
6365 /// \brief Helper function to classify a mask as a single-input mask.
6366 ///
6367 /// This isn't a generic single-input test because in the vector shuffle
6368 /// lowering we canonicalize single inputs to be the first input operand. This
6369 /// means we can more quickly test for a single input by only checking whether
6370 /// an input from the second operand exists. We also assume that the size of
6371 /// mask corresponds to the size of the input vectors which isn't true in the
6372 /// fully general case.
6373 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6374   for (int M : Mask)
6375     if (M >= (int)Mask.size())
6376       return false;
6377   return true;
6378 }
6379
6380 /// \brief Test whether there are elements crossing 128-bit lanes in this
6381 /// shuffle mask.
6382 ///
6383 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6384 /// and we routinely test for these.
6385 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6386   int LaneSize = 128 / VT.getScalarSizeInBits();
6387   int Size = Mask.size();
6388   for (int i = 0; i < Size; ++i)
6389     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6390       return true;
6391   return false;
6392 }
6393
6394 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6395 ///
6396 /// This checks a shuffle mask to see if it is performing the same
6397 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6398 /// that it is also not lane-crossing. It may however involve a blend from the
6399 /// same lane of a second vector.
6400 ///
6401 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6402 /// non-trivial to compute in the face of undef lanes. The representation is
6403 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6404 /// entries from both V1 and V2 inputs to the wider mask.
6405 static bool
6406 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6407                                 SmallVectorImpl<int> &RepeatedMask) {
6408   int LaneSize = 128 / VT.getScalarSizeInBits();
6409   RepeatedMask.resize(LaneSize, -1);
6410   int Size = Mask.size();
6411   for (int i = 0; i < Size; ++i) {
6412     if (Mask[i] < 0)
6413       continue;
6414     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6415       // This entry crosses lanes, so there is no way to model this shuffle.
6416       return false;
6417
6418     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6419     if (RepeatedMask[i % LaneSize] == -1)
6420       // This is the first non-undef entry in this slot of a 128-bit lane.
6421       RepeatedMask[i % LaneSize] =
6422           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6423     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6424       // Found a mismatch with the repeated mask.
6425       return false;
6426   }
6427   return true;
6428 }
6429
6430 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6431 /// arguments.
6432 ///
6433 /// This is a fast way to test a shuffle mask against a fixed pattern:
6434 ///
6435 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6436 ///
6437 /// It returns true if the mask is exactly as wide as the argument list, and
6438 /// each element of the mask is either -1 (signifying undef) or the value given
6439 /// in the argument.
6440 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6441                                 ArrayRef<int> ExpectedMask) {
6442   if (Mask.size() != ExpectedMask.size())
6443     return false;
6444
6445   int Size = Mask.size();
6446
6447   // If the values are build vectors, we can look through them to find
6448   // equivalent inputs that make the shuffles equivalent.
6449   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6450   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6451
6452   for (int i = 0; i < Size; ++i)
6453     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6454       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6455       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6456       if (!MaskBV || !ExpectedBV ||
6457           MaskBV->getOperand(Mask[i] % Size) !=
6458               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6459         return false;
6460     }
6461
6462   return true;
6463 }
6464
6465 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6466 ///
6467 /// This helper function produces an 8-bit shuffle immediate corresponding to
6468 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6469 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6470 /// example.
6471 ///
6472 /// NB: We rely heavily on "undef" masks preserving the input lane.
6473 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6474                                           SelectionDAG &DAG) {
6475   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6476   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6477   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6478   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6479   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6480
6481   unsigned Imm = 0;
6482   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6483   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6484   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6485   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6486   return DAG.getConstant(Imm, DL, MVT::i8);
6487 }
6488
6489 /// \brief Compute whether each element of a shuffle is zeroable.
6490 ///
6491 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6492 /// Either it is an undef element in the shuffle mask, the element of the input
6493 /// referenced is undef, or the element of the input referenced is known to be
6494 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6495 /// as many lanes with this technique as possible to simplify the remaining
6496 /// shuffle.
6497 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6498                                                      SDValue V1, SDValue V2) {
6499   SmallBitVector Zeroable(Mask.size(), false);
6500
6501   while (V1.getOpcode() == ISD::BITCAST)
6502     V1 = V1->getOperand(0);
6503   while (V2.getOpcode() == ISD::BITCAST)
6504     V2 = V2->getOperand(0);
6505
6506   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6507   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6508
6509   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6510     int M = Mask[i];
6511     // Handle the easy cases.
6512     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6513       Zeroable[i] = true;
6514       continue;
6515     }
6516
6517     // If this is an index into a build_vector node (which has the same number
6518     // of elements), dig out the input value and use it.
6519     SDValue V = M < Size ? V1 : V2;
6520     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6521       continue;
6522
6523     SDValue Input = V.getOperand(M % Size);
6524     // The UNDEF opcode check really should be dead code here, but not quite
6525     // worth asserting on (it isn't invalid, just unexpected).
6526     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6527       Zeroable[i] = true;
6528   }
6529
6530   return Zeroable;
6531 }
6532
6533 /// \brief Try to emit a bitmask instruction for a shuffle.
6534 ///
6535 /// This handles cases where we can model a blend exactly as a bitmask due to
6536 /// one of the inputs being zeroable.
6537 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6538                                            SDValue V2, ArrayRef<int> Mask,
6539                                            SelectionDAG &DAG) {
6540   MVT EltVT = VT.getScalarType();
6541   int NumEltBits = EltVT.getSizeInBits();
6542   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6543   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6544   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6545                                     IntEltVT);
6546   if (EltVT.isFloatingPoint()) {
6547     Zero = DAG.getBitcast(EltVT, Zero);
6548     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6549   }
6550   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6551   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6552   SDValue V;
6553   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6554     if (Zeroable[i])
6555       continue;
6556     if (Mask[i] % Size != i)
6557       return SDValue(); // Not a blend.
6558     if (!V)
6559       V = Mask[i] < Size ? V1 : V2;
6560     else if (V != (Mask[i] < Size ? V1 : V2))
6561       return SDValue(); // Can only let one input through the mask.
6562
6563     VMaskOps[i] = AllOnes;
6564   }
6565   if (!V)
6566     return SDValue(); // No non-zeroable elements!
6567
6568   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6569   V = DAG.getNode(VT.isFloatingPoint()
6570                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6571                   DL, VT, V, VMask);
6572   return V;
6573 }
6574
6575 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6576 ///
6577 /// This is used as a fallback approach when first class blend instructions are
6578 /// unavailable. Currently it is only suitable for integer vectors, but could
6579 /// be generalized for floating point vectors if desirable.
6580 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6581                                             SDValue V2, ArrayRef<int> Mask,
6582                                             SelectionDAG &DAG) {
6583   assert(VT.isInteger() && "Only supports integer vector types!");
6584   MVT EltVT = VT.getScalarType();
6585   int NumEltBits = EltVT.getSizeInBits();
6586   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6587   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6588                                     EltVT);
6589   SmallVector<SDValue, 16> MaskOps;
6590   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6591     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6592       return SDValue(); // Shuffled input!
6593     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6594   }
6595
6596   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6597   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6598   // We have to cast V2 around.
6599   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6600   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6601                                       DAG.getBitcast(MaskVT, V1Mask),
6602                                       DAG.getBitcast(MaskVT, V2)));
6603   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6604 }
6605
6606 /// \brief Try to emit a blend instruction for a shuffle.
6607 ///
6608 /// This doesn't do any checks for the availability of instructions for blending
6609 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6610 /// be matched in the backend with the type given. What it does check for is
6611 /// that the shuffle mask is in fact a blend.
6612 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6613                                          SDValue V2, ArrayRef<int> Mask,
6614                                          const X86Subtarget *Subtarget,
6615                                          SelectionDAG &DAG) {
6616   unsigned BlendMask = 0;
6617   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6618     if (Mask[i] >= Size) {
6619       if (Mask[i] != i + Size)
6620         return SDValue(); // Shuffled V2 input!
6621       BlendMask |= 1u << i;
6622       continue;
6623     }
6624     if (Mask[i] >= 0 && Mask[i] != i)
6625       return SDValue(); // Shuffled V1 input!
6626   }
6627   switch (VT.SimpleTy) {
6628   case MVT::v2f64:
6629   case MVT::v4f32:
6630   case MVT::v4f64:
6631   case MVT::v8f32:
6632     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6633                        DAG.getConstant(BlendMask, DL, MVT::i8));
6634
6635   case MVT::v4i64:
6636   case MVT::v8i32:
6637     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6638     // FALLTHROUGH
6639   case MVT::v2i64:
6640   case MVT::v4i32:
6641     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6642     // that instruction.
6643     if (Subtarget->hasAVX2()) {
6644       // Scale the blend by the number of 32-bit dwords per element.
6645       int Scale =  VT.getScalarSizeInBits() / 32;
6646       BlendMask = 0;
6647       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6648         if (Mask[i] >= Size)
6649           for (int j = 0; j < Scale; ++j)
6650             BlendMask |= 1u << (i * Scale + j);
6651
6652       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6653       V1 = DAG.getBitcast(BlendVT, V1);
6654       V2 = DAG.getBitcast(BlendVT, V2);
6655       return DAG.getBitcast(
6656           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6657                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6658     }
6659     // FALLTHROUGH
6660   case MVT::v8i16: {
6661     // For integer shuffles we need to expand the mask and cast the inputs to
6662     // v8i16s prior to blending.
6663     int Scale = 8 / VT.getVectorNumElements();
6664     BlendMask = 0;
6665     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6666       if (Mask[i] >= Size)
6667         for (int j = 0; j < Scale; ++j)
6668           BlendMask |= 1u << (i * Scale + j);
6669
6670     V1 = DAG.getBitcast(MVT::v8i16, V1);
6671     V2 = DAG.getBitcast(MVT::v8i16, V2);
6672     return DAG.getBitcast(VT,
6673                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6674                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6675   }
6676
6677   case MVT::v16i16: {
6678     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6679     SmallVector<int, 8> RepeatedMask;
6680     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6681       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6682       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6683       BlendMask = 0;
6684       for (int i = 0; i < 8; ++i)
6685         if (RepeatedMask[i] >= 16)
6686           BlendMask |= 1u << i;
6687       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6688                          DAG.getConstant(BlendMask, DL, MVT::i8));
6689     }
6690   }
6691     // FALLTHROUGH
6692   case MVT::v16i8:
6693   case MVT::v32i8: {
6694     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6695            "256-bit byte-blends require AVX2 support!");
6696
6697     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6698     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6699       return Masked;
6700
6701     // Scale the blend by the number of bytes per element.
6702     int Scale = VT.getScalarSizeInBits() / 8;
6703
6704     // This form of blend is always done on bytes. Compute the byte vector
6705     // type.
6706     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6707
6708     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6709     // mix of LLVM's code generator and the x86 backend. We tell the code
6710     // generator that boolean values in the elements of an x86 vector register
6711     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6712     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6713     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6714     // of the element (the remaining are ignored) and 0 in that high bit would
6715     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6716     // the LLVM model for boolean values in vector elements gets the relevant
6717     // bit set, it is set backwards and over constrained relative to x86's
6718     // actual model.
6719     SmallVector<SDValue, 32> VSELECTMask;
6720     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6721       for (int j = 0; j < Scale; ++j)
6722         VSELECTMask.push_back(
6723             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6724                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6725                                           MVT::i8));
6726
6727     V1 = DAG.getBitcast(BlendVT, V1);
6728     V2 = DAG.getBitcast(BlendVT, V2);
6729     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6730                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6731                                                       BlendVT, VSELECTMask),
6732                                           V1, V2));
6733   }
6734
6735   default:
6736     llvm_unreachable("Not a supported integer vector type!");
6737   }
6738 }
6739
6740 /// \brief Try to lower as a blend of elements from two inputs followed by
6741 /// a single-input permutation.
6742 ///
6743 /// This matches the pattern where we can blend elements from two inputs and
6744 /// then reduce the shuffle to a single-input permutation.
6745 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6746                                                    SDValue V2,
6747                                                    ArrayRef<int> Mask,
6748                                                    SelectionDAG &DAG) {
6749   // We build up the blend mask while checking whether a blend is a viable way
6750   // to reduce the shuffle.
6751   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6752   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6753
6754   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6755     if (Mask[i] < 0)
6756       continue;
6757
6758     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6759
6760     if (BlendMask[Mask[i] % Size] == -1)
6761       BlendMask[Mask[i] % Size] = Mask[i];
6762     else if (BlendMask[Mask[i] % Size] != Mask[i])
6763       return SDValue(); // Can't blend in the needed input!
6764
6765     PermuteMask[i] = Mask[i] % Size;
6766   }
6767
6768   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6769   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6770 }
6771
6772 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6773 /// blends and permutes.
6774 ///
6775 /// This matches the extremely common pattern for handling combined
6776 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6777 /// operations. It will try to pick the best arrangement of shuffles and
6778 /// blends.
6779 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6780                                                           SDValue V1,
6781                                                           SDValue V2,
6782                                                           ArrayRef<int> Mask,
6783                                                           SelectionDAG &DAG) {
6784   // Shuffle the input elements into the desired positions in V1 and V2 and
6785   // blend them together.
6786   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6787   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6788   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6789   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6790     if (Mask[i] >= 0 && Mask[i] < Size) {
6791       V1Mask[i] = Mask[i];
6792       BlendMask[i] = i;
6793     } else if (Mask[i] >= Size) {
6794       V2Mask[i] = Mask[i] - Size;
6795       BlendMask[i] = i + Size;
6796     }
6797
6798   // Try to lower with the simpler initial blend strategy unless one of the
6799   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6800   // shuffle may be able to fold with a load or other benefit. However, when
6801   // we'll have to do 2x as many shuffles in order to achieve this, blending
6802   // first is a better strategy.
6803   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6804     if (SDValue BlendPerm =
6805             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6806       return BlendPerm;
6807
6808   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6809   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6810   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6811 }
6812
6813 /// \brief Try to lower a vector shuffle as a byte rotation.
6814 ///
6815 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6816 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6817 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6818 /// try to generically lower a vector shuffle through such an pattern. It
6819 /// does not check for the profitability of lowering either as PALIGNR or
6820 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6821 /// This matches shuffle vectors that look like:
6822 ///
6823 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6824 ///
6825 /// Essentially it concatenates V1 and V2, shifts right by some number of
6826 /// elements, and takes the low elements as the result. Note that while this is
6827 /// specified as a *right shift* because x86 is little-endian, it is a *left
6828 /// rotate* of the vector lanes.
6829 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6830                                               SDValue V2,
6831                                               ArrayRef<int> Mask,
6832                                               const X86Subtarget *Subtarget,
6833                                               SelectionDAG &DAG) {
6834   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6835
6836   int NumElts = Mask.size();
6837   int NumLanes = VT.getSizeInBits() / 128;
6838   int NumLaneElts = NumElts / NumLanes;
6839
6840   // We need to detect various ways of spelling a rotation:
6841   //   [11, 12, 13, 14, 15,  0,  1,  2]
6842   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6843   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6844   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6845   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6846   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6847   int Rotation = 0;
6848   SDValue Lo, Hi;
6849   for (int l = 0; l < NumElts; l += NumLaneElts) {
6850     for (int i = 0; i < NumLaneElts; ++i) {
6851       if (Mask[l + i] == -1)
6852         continue;
6853       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6854
6855       // Get the mod-Size index and lane correct it.
6856       int LaneIdx = (Mask[l + i] % NumElts) - l;
6857       // Make sure it was in this lane.
6858       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6859         return SDValue();
6860
6861       // Determine where a rotated vector would have started.
6862       int StartIdx = i - LaneIdx;
6863       if (StartIdx == 0)
6864         // The identity rotation isn't interesting, stop.
6865         return SDValue();
6866
6867       // If we found the tail of a vector the rotation must be the missing
6868       // front. If we found the head of a vector, it must be how much of the
6869       // head.
6870       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6871
6872       if (Rotation == 0)
6873         Rotation = CandidateRotation;
6874       else if (Rotation != CandidateRotation)
6875         // The rotations don't match, so we can't match this mask.
6876         return SDValue();
6877
6878       // Compute which value this mask is pointing at.
6879       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6880
6881       // Compute which of the two target values this index should be assigned
6882       // to. This reflects whether the high elements are remaining or the low
6883       // elements are remaining.
6884       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6885
6886       // Either set up this value if we've not encountered it before, or check
6887       // that it remains consistent.
6888       if (!TargetV)
6889         TargetV = MaskV;
6890       else if (TargetV != MaskV)
6891         // This may be a rotation, but it pulls from the inputs in some
6892         // unsupported interleaving.
6893         return SDValue();
6894     }
6895   }
6896
6897   // Check that we successfully analyzed the mask, and normalize the results.
6898   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6899   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6900   if (!Lo)
6901     Lo = Hi;
6902   else if (!Hi)
6903     Hi = Lo;
6904
6905   // The actual rotate instruction rotates bytes, so we need to scale the
6906   // rotation based on how many bytes are in the vector lane.
6907   int Scale = 16 / NumLaneElts;
6908
6909   // SSSE3 targets can use the palignr instruction.
6910   if (Subtarget->hasSSSE3()) {
6911     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6912     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6913     Lo = DAG.getBitcast(AlignVT, Lo);
6914     Hi = DAG.getBitcast(AlignVT, Hi);
6915
6916     return DAG.getBitcast(
6917         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
6918                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6919   }
6920
6921   assert(VT.getSizeInBits() == 128 &&
6922          "Rotate-based lowering only supports 128-bit lowering!");
6923   assert(Mask.size() <= 16 &&
6924          "Can shuffle at most 16 bytes in a 128-bit vector!");
6925
6926   // Default SSE2 implementation
6927   int LoByteShift = 16 - Rotation * Scale;
6928   int HiByteShift = Rotation * Scale;
6929
6930   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6931   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6932   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6933
6934   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6935                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6936   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6937                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6938   return DAG.getBitcast(VT,
6939                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6940 }
6941
6942 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6943 ///
6944 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6945 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6946 /// matches elements from one of the input vectors shuffled to the left or
6947 /// right with zeroable elements 'shifted in'. It handles both the strictly
6948 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6949 /// quad word lane.
6950 ///
6951 /// PSHL : (little-endian) left bit shift.
6952 /// [ zz, 0, zz,  2 ]
6953 /// [ -1, 4, zz, -1 ]
6954 /// PSRL : (little-endian) right bit shift.
6955 /// [  1, zz,  3, zz]
6956 /// [ -1, -1,  7, zz]
6957 /// PSLLDQ : (little-endian) left byte shift
6958 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6959 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6960 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6961 /// PSRLDQ : (little-endian) right byte shift
6962 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6963 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6964 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6965 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6966                                          SDValue V2, ArrayRef<int> Mask,
6967                                          SelectionDAG &DAG) {
6968   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6969
6970   int Size = Mask.size();
6971   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6972
6973   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6974     for (int i = 0; i < Size; i += Scale)
6975       for (int j = 0; j < Shift; ++j)
6976         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6977           return false;
6978
6979     return true;
6980   };
6981
6982   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6983     for (int i = 0; i != Size; i += Scale) {
6984       unsigned Pos = Left ? i + Shift : i;
6985       unsigned Low = Left ? i : i + Shift;
6986       unsigned Len = Scale - Shift;
6987       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6988                                       Low + (V == V1 ? 0 : Size)))
6989         return SDValue();
6990     }
6991
6992     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6993     bool ByteShift = ShiftEltBits > 64;
6994     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6995                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6996     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6997
6998     // Normalize the scale for byte shifts to still produce an i64 element
6999     // type.
7000     Scale = ByteShift ? Scale / 2 : Scale;
7001
7002     // We need to round trip through the appropriate type for the shift.
7003     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7004     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7005     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7006            "Illegal integer vector type");
7007     V = DAG.getBitcast(ShiftVT, V);
7008
7009     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7010                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7011     return DAG.getBitcast(VT, V);
7012   };
7013
7014   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7015   // keep doubling the size of the integer elements up to that. We can
7016   // then shift the elements of the integer vector by whole multiples of
7017   // their width within the elements of the larger integer vector. Test each
7018   // multiple to see if we can find a match with the moved element indices
7019   // and that the shifted in elements are all zeroable.
7020   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7021     for (int Shift = 1; Shift != Scale; ++Shift)
7022       for (bool Left : {true, false})
7023         if (CheckZeros(Shift, Scale, Left))
7024           for (SDValue V : {V1, V2})
7025             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7026               return Match;
7027
7028   // no match
7029   return SDValue();
7030 }
7031
7032 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7033 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7034                                            SDValue V2, ArrayRef<int> Mask,
7035                                            SelectionDAG &DAG) {
7036   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7037   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7038
7039   int Size = Mask.size();
7040   int HalfSize = Size / 2;
7041   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7042
7043   // Upper half must be undefined.
7044   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7045     return SDValue();
7046
7047   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7048   // Remainder of lower half result is zero and upper half is all undef.
7049   auto LowerAsEXTRQ = [&]() {
7050     // Determine the extraction length from the part of the
7051     // lower half that isn't zeroable.
7052     int Len = HalfSize;
7053     for (; Len >= 0; --Len)
7054       if (!Zeroable[Len - 1])
7055         break;
7056     assert(Len > 0 && "Zeroable shuffle mask");
7057
7058     // Attempt to match first Len sequential elements from the lower half.
7059     SDValue Src;
7060     int Idx = -1;
7061     for (int i = 0; i != Len; ++i) {
7062       int M = Mask[i];
7063       if (M < 0)
7064         continue;
7065       SDValue &V = (M < Size ? V1 : V2);
7066       M = M % Size;
7067
7068       // All mask elements must be in the lower half.
7069       if (M > HalfSize)
7070         return SDValue();
7071
7072       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7073         Src = V;
7074         Idx = M - i;
7075         continue;
7076       }
7077       return SDValue();
7078     }
7079
7080     if (Idx < 0)
7081       return SDValue();
7082
7083     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7084     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7085     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7086     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7087                        DAG.getConstant(BitLen, DL, MVT::i8),
7088                        DAG.getConstant(BitIdx, DL, MVT::i8));
7089   };
7090
7091   if (SDValue ExtrQ = LowerAsEXTRQ())
7092     return ExtrQ;
7093
7094   // INSERTQ: Extract lowest Len elements from lower half of second source and
7095   // insert over first source, starting at Idx.
7096   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7097   auto LowerAsInsertQ = [&]() {
7098     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7099       SDValue Base;
7100
7101       // Attempt to match first source from mask before insertion point.
7102       if (isUndefInRange(Mask, 0, Idx)) {
7103         /* EMPTY */
7104       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7105         Base = V1;
7106       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7107         Base = V2;
7108       } else {
7109         continue;
7110       }
7111
7112       // Extend the extraction length looking to match both the insertion of
7113       // the second source and the remaining elements of the first.
7114       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7115         SDValue Insert;
7116         int Len = Hi - Idx;
7117
7118         // Match insertion.
7119         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7120           Insert = V1;
7121         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7122           Insert = V2;
7123         } else {
7124           continue;
7125         }
7126
7127         // Match the remaining elements of the lower half.
7128         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7129           /* EMPTY */
7130         } else if ((!Base || (Base == V1)) &&
7131                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7132           Base = V1;
7133         } else if ((!Base || (Base == V2)) &&
7134                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7135                                               Size + Hi)) {
7136           Base = V2;
7137         } else {
7138           continue;
7139         }
7140
7141         // We may not have a base (first source) - this can safely be undefined.
7142         if (!Base)
7143           Base = DAG.getUNDEF(VT);
7144
7145         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7146         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7147         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7148                            DAG.getConstant(BitLen, DL, MVT::i8),
7149                            DAG.getConstant(BitIdx, DL, MVT::i8));
7150       }
7151     }
7152
7153     return SDValue();
7154   };
7155
7156   if (SDValue InsertQ = LowerAsInsertQ())
7157     return InsertQ;
7158
7159   return SDValue();
7160 }
7161
7162 /// \brief Lower a vector shuffle as a zero or any extension.
7163 ///
7164 /// Given a specific number of elements, element bit width, and extension
7165 /// stride, produce either a zero or any extension based on the available
7166 /// features of the subtarget.
7167 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7168     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7169     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7170   assert(Scale > 1 && "Need a scale to extend.");
7171   int NumElements = VT.getVectorNumElements();
7172   int EltBits = VT.getScalarSizeInBits();
7173   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7174          "Only 8, 16, and 32 bit elements can be extended.");
7175   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7176
7177   // Found a valid zext mask! Try various lowering strategies based on the
7178   // input type and available ISA extensions.
7179   if (Subtarget->hasSSE41()) {
7180     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7181                                  NumElements / Scale);
7182     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7183   }
7184
7185   // For any extends we can cheat for larger element sizes and use shuffle
7186   // instructions that can fold with a load and/or copy.
7187   if (AnyExt && EltBits == 32) {
7188     int PSHUFDMask[4] = {0, -1, 1, -1};
7189     return DAG.getBitcast(
7190         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7191                         DAG.getBitcast(MVT::v4i32, InputV),
7192                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7193   }
7194   if (AnyExt && EltBits == 16 && Scale > 2) {
7195     int PSHUFDMask[4] = {0, -1, 0, -1};
7196     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7197                          DAG.getBitcast(MVT::v4i32, InputV),
7198                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7199     int PSHUFHWMask[4] = {1, -1, -1, -1};
7200     return DAG.getBitcast(
7201         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7202                         DAG.getBitcast(MVT::v8i16, InputV),
7203                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7204   }
7205
7206   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7207   // to 64-bits.
7208   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7209     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7210     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7211
7212     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7213                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7214                                          DAG.getConstant(EltBits, DL, MVT::i8),
7215                                          DAG.getConstant(0, DL, MVT::i8)));
7216     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7217       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7218
7219     SDValue Hi =
7220         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7221                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7222                                 DAG.getConstant(EltBits, DL, MVT::i8),
7223                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7224     return DAG.getNode(ISD::BITCAST, DL, VT,
7225                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7226   }
7227
7228   // If this would require more than 2 unpack instructions to expand, use
7229   // pshufb when available. We can only use more than 2 unpack instructions
7230   // when zero extending i8 elements which also makes it easier to use pshufb.
7231   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7232     assert(NumElements == 16 && "Unexpected byte vector width!");
7233     SDValue PSHUFBMask[16];
7234     for (int i = 0; i < 16; ++i)
7235       PSHUFBMask[i] =
7236           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7237     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7238     return DAG.getBitcast(VT,
7239                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7240                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7241                                                   MVT::v16i8, PSHUFBMask)));
7242   }
7243
7244   // Otherwise emit a sequence of unpacks.
7245   do {
7246     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7247     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7248                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7249     InputV = DAG.getBitcast(InputVT, InputV);
7250     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7251     Scale /= 2;
7252     EltBits *= 2;
7253     NumElements /= 2;
7254   } while (Scale > 1);
7255   return DAG.getBitcast(VT, InputV);
7256 }
7257
7258 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7259 ///
7260 /// This routine will try to do everything in its power to cleverly lower
7261 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7262 /// check for the profitability of this lowering,  it tries to aggressively
7263 /// match this pattern. It will use all of the micro-architectural details it
7264 /// can to emit an efficient lowering. It handles both blends with all-zero
7265 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7266 /// masking out later).
7267 ///
7268 /// The reason we have dedicated lowering for zext-style shuffles is that they
7269 /// are both incredibly common and often quite performance sensitive.
7270 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7271     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7272     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7273   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7274
7275   int Bits = VT.getSizeInBits();
7276   int NumElements = VT.getVectorNumElements();
7277   assert(VT.getScalarSizeInBits() <= 32 &&
7278          "Exceeds 32-bit integer zero extension limit");
7279   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7280
7281   // Define a helper function to check a particular ext-scale and lower to it if
7282   // valid.
7283   auto Lower = [&](int Scale) -> SDValue {
7284     SDValue InputV;
7285     bool AnyExt = true;
7286     for (int i = 0; i < NumElements; ++i) {
7287       if (Mask[i] == -1)
7288         continue; // Valid anywhere but doesn't tell us anything.
7289       if (i % Scale != 0) {
7290         // Each of the extended elements need to be zeroable.
7291         if (!Zeroable[i])
7292           return SDValue();
7293
7294         // We no longer are in the anyext case.
7295         AnyExt = false;
7296         continue;
7297       }
7298
7299       // Each of the base elements needs to be consecutive indices into the
7300       // same input vector.
7301       SDValue V = Mask[i] < NumElements ? V1 : V2;
7302       if (!InputV)
7303         InputV = V;
7304       else if (InputV != V)
7305         return SDValue(); // Flip-flopping inputs.
7306
7307       if (Mask[i] % NumElements != i / Scale)
7308         return SDValue(); // Non-consecutive strided elements.
7309     }
7310
7311     // If we fail to find an input, we have a zero-shuffle which should always
7312     // have already been handled.
7313     // FIXME: Maybe handle this here in case during blending we end up with one?
7314     if (!InputV)
7315       return SDValue();
7316
7317     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7318         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7319   };
7320
7321   // The widest scale possible for extending is to a 64-bit integer.
7322   assert(Bits % 64 == 0 &&
7323          "The number of bits in a vector must be divisible by 64 on x86!");
7324   int NumExtElements = Bits / 64;
7325
7326   // Each iteration, try extending the elements half as much, but into twice as
7327   // many elements.
7328   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7329     assert(NumElements % NumExtElements == 0 &&
7330            "The input vector size must be divisible by the extended size.");
7331     if (SDValue V = Lower(NumElements / NumExtElements))
7332       return V;
7333   }
7334
7335   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7336   if (Bits != 128)
7337     return SDValue();
7338
7339   // Returns one of the source operands if the shuffle can be reduced to a
7340   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7341   auto CanZExtLowHalf = [&]() {
7342     for (int i = NumElements / 2; i != NumElements; ++i)
7343       if (!Zeroable[i])
7344         return SDValue();
7345     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7346       return V1;
7347     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7348       return V2;
7349     return SDValue();
7350   };
7351
7352   if (SDValue V = CanZExtLowHalf()) {
7353     V = DAG.getBitcast(MVT::v2i64, V);
7354     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7355     return DAG.getBitcast(VT, V);
7356   }
7357
7358   // No viable ext lowering found.
7359   return SDValue();
7360 }
7361
7362 /// \brief Try to get a scalar value for a specific element of a vector.
7363 ///
7364 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7365 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7366                                               SelectionDAG &DAG) {
7367   MVT VT = V.getSimpleValueType();
7368   MVT EltVT = VT.getVectorElementType();
7369   while (V.getOpcode() == ISD::BITCAST)
7370     V = V.getOperand(0);
7371   // If the bitcasts shift the element size, we can't extract an equivalent
7372   // element from it.
7373   MVT NewVT = V.getSimpleValueType();
7374   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7375     return SDValue();
7376
7377   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7378       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7379     // Ensure the scalar operand is the same size as the destination.
7380     // FIXME: Add support for scalar truncation where possible.
7381     SDValue S = V.getOperand(Idx);
7382     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7383       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7384   }
7385
7386   return SDValue();
7387 }
7388
7389 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7390 ///
7391 /// This is particularly important because the set of instructions varies
7392 /// significantly based on whether the operand is a load or not.
7393 static bool isShuffleFoldableLoad(SDValue V) {
7394   while (V.getOpcode() == ISD::BITCAST)
7395     V = V.getOperand(0);
7396
7397   return ISD::isNON_EXTLoad(V.getNode());
7398 }
7399
7400 /// \brief Try to lower insertion of a single element into a zero vector.
7401 ///
7402 /// This is a common pattern that we have especially efficient patterns to lower
7403 /// across all subtarget feature sets.
7404 static SDValue lowerVectorShuffleAsElementInsertion(
7405     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7406     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7407   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7408   MVT ExtVT = VT;
7409   MVT EltVT = VT.getVectorElementType();
7410
7411   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7412                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7413                 Mask.begin();
7414   bool IsV1Zeroable = true;
7415   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7416     if (i != V2Index && !Zeroable[i]) {
7417       IsV1Zeroable = false;
7418       break;
7419     }
7420
7421   // Check for a single input from a SCALAR_TO_VECTOR node.
7422   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7423   // all the smarts here sunk into that routine. However, the current
7424   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7425   // vector shuffle lowering is dead.
7426   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7427                                                DAG);
7428   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7429     // We need to zext the scalar if it is smaller than an i32.
7430     V2S = DAG.getBitcast(EltVT, V2S);
7431     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7432       // Using zext to expand a narrow element won't work for non-zero
7433       // insertions.
7434       if (!IsV1Zeroable)
7435         return SDValue();
7436
7437       // Zero-extend directly to i32.
7438       ExtVT = MVT::v4i32;
7439       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7440     }
7441     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7442   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7443              EltVT == MVT::i16) {
7444     // Either not inserting from the low element of the input or the input
7445     // element size is too small to use VZEXT_MOVL to clear the high bits.
7446     return SDValue();
7447   }
7448
7449   if (!IsV1Zeroable) {
7450     // If V1 can't be treated as a zero vector we have fewer options to lower
7451     // this. We can't support integer vectors or non-zero targets cheaply, and
7452     // the V1 elements can't be permuted in any way.
7453     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7454     if (!VT.isFloatingPoint() || V2Index != 0)
7455       return SDValue();
7456     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7457     V1Mask[V2Index] = -1;
7458     if (!isNoopShuffleMask(V1Mask))
7459       return SDValue();
7460     // This is essentially a special case blend operation, but if we have
7461     // general purpose blend operations, they are always faster. Bail and let
7462     // the rest of the lowering handle these as blends.
7463     if (Subtarget->hasSSE41())
7464       return SDValue();
7465
7466     // Otherwise, use MOVSD or MOVSS.
7467     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7468            "Only two types of floating point element types to handle!");
7469     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7470                        ExtVT, V1, V2);
7471   }
7472
7473   // This lowering only works for the low element with floating point vectors.
7474   if (VT.isFloatingPoint() && V2Index != 0)
7475     return SDValue();
7476
7477   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7478   if (ExtVT != VT)
7479     V2 = DAG.getBitcast(VT, V2);
7480
7481   if (V2Index != 0) {
7482     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7483     // the desired position. Otherwise it is more efficient to do a vector
7484     // shift left. We know that we can do a vector shift left because all
7485     // the inputs are zero.
7486     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7487       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7488       V2Shuffle[V2Index] = 0;
7489       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7490     } else {
7491       V2 = DAG.getBitcast(MVT::v2i64, V2);
7492       V2 = DAG.getNode(
7493           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7494           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7495                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7496                               DAG.getDataLayout(), VT)));
7497       V2 = DAG.getBitcast(VT, V2);
7498     }
7499   }
7500   return V2;
7501 }
7502
7503 /// \brief Try to lower broadcast of a single element.
7504 ///
7505 /// For convenience, this code also bundles all of the subtarget feature set
7506 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7507 /// a convenient way to factor it out.
7508 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7509                                              ArrayRef<int> Mask,
7510                                              const X86Subtarget *Subtarget,
7511                                              SelectionDAG &DAG) {
7512   if (!Subtarget->hasAVX())
7513     return SDValue();
7514   if (VT.isInteger() && !Subtarget->hasAVX2())
7515     return SDValue();
7516
7517   // Check that the mask is a broadcast.
7518   int BroadcastIdx = -1;
7519   for (int M : Mask)
7520     if (M >= 0 && BroadcastIdx == -1)
7521       BroadcastIdx = M;
7522     else if (M >= 0 && M != BroadcastIdx)
7523       return SDValue();
7524
7525   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7526                                             "a sorted mask where the broadcast "
7527                                             "comes from V1.");
7528
7529   // Go up the chain of (vector) values to find a scalar load that we can
7530   // combine with the broadcast.
7531   for (;;) {
7532     switch (V.getOpcode()) {
7533     case ISD::CONCAT_VECTORS: {
7534       int OperandSize = Mask.size() / V.getNumOperands();
7535       V = V.getOperand(BroadcastIdx / OperandSize);
7536       BroadcastIdx %= OperandSize;
7537       continue;
7538     }
7539
7540     case ISD::INSERT_SUBVECTOR: {
7541       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7542       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7543       if (!ConstantIdx)
7544         break;
7545
7546       int BeginIdx = (int)ConstantIdx->getZExtValue();
7547       int EndIdx =
7548           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7549       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7550         BroadcastIdx -= BeginIdx;
7551         V = VInner;
7552       } else {
7553         V = VOuter;
7554       }
7555       continue;
7556     }
7557     }
7558     break;
7559   }
7560
7561   // Check if this is a broadcast of a scalar. We special case lowering
7562   // for scalars so that we can more effectively fold with loads.
7563   // First, look through bitcast: if the original value has a larger element
7564   // type than the shuffle, the broadcast element is in essence truncated.
7565   // Make that explicit to ease folding.
7566   if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7567     EVT EltVT = VT.getVectorElementType();
7568     SDValue V0 = V.getOperand(0);
7569     EVT V0VT = V0.getValueType();
7570
7571     if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7572         ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7573          (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7574       V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7575       BroadcastIdx = 0;
7576     }
7577   }
7578
7579   // Also check the simpler case, where we can directly reuse the scalar.
7580   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7581       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7582     V = V.getOperand(BroadcastIdx);
7583
7584     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7585     // Only AVX2 has register broadcasts.
7586     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7587       return SDValue();
7588   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7589     // We can't broadcast from a vector register without AVX2, and we can only
7590     // broadcast from the zero-element of a vector register.
7591     return SDValue();
7592   }
7593
7594   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7595 }
7596
7597 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7598 // INSERTPS when the V1 elements are already in the correct locations
7599 // because otherwise we can just always use two SHUFPS instructions which
7600 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7601 // perform INSERTPS if a single V1 element is out of place and all V2
7602 // elements are zeroable.
7603 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7604                                             ArrayRef<int> Mask,
7605                                             SelectionDAG &DAG) {
7606   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7607   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7608   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7609   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7610
7611   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7612
7613   unsigned ZMask = 0;
7614   int V1DstIndex = -1;
7615   int V2DstIndex = -1;
7616   bool V1UsedInPlace = false;
7617
7618   for (int i = 0; i < 4; ++i) {
7619     // Synthesize a zero mask from the zeroable elements (includes undefs).
7620     if (Zeroable[i]) {
7621       ZMask |= 1 << i;
7622       continue;
7623     }
7624
7625     // Flag if we use any V1 inputs in place.
7626     if (i == Mask[i]) {
7627       V1UsedInPlace = true;
7628       continue;
7629     }
7630
7631     // We can only insert a single non-zeroable element.
7632     if (V1DstIndex != -1 || V2DstIndex != -1)
7633       return SDValue();
7634
7635     if (Mask[i] < 4) {
7636       // V1 input out of place for insertion.
7637       V1DstIndex = i;
7638     } else {
7639       // V2 input for insertion.
7640       V2DstIndex = i;
7641     }
7642   }
7643
7644   // Don't bother if we have no (non-zeroable) element for insertion.
7645   if (V1DstIndex == -1 && V2DstIndex == -1)
7646     return SDValue();
7647
7648   // Determine element insertion src/dst indices. The src index is from the
7649   // start of the inserted vector, not the start of the concatenated vector.
7650   unsigned V2SrcIndex = 0;
7651   if (V1DstIndex != -1) {
7652     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7653     // and don't use the original V2 at all.
7654     V2SrcIndex = Mask[V1DstIndex];
7655     V2DstIndex = V1DstIndex;
7656     V2 = V1;
7657   } else {
7658     V2SrcIndex = Mask[V2DstIndex] - 4;
7659   }
7660
7661   // If no V1 inputs are used in place, then the result is created only from
7662   // the zero mask and the V2 insertion - so remove V1 dependency.
7663   if (!V1UsedInPlace)
7664     V1 = DAG.getUNDEF(MVT::v4f32);
7665
7666   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7667   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7668
7669   // Insert the V2 element into the desired position.
7670   SDLoc DL(Op);
7671   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7672                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7673 }
7674
7675 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7676 /// UNPCK instruction.
7677 ///
7678 /// This specifically targets cases where we end up with alternating between
7679 /// the two inputs, and so can permute them into something that feeds a single
7680 /// UNPCK instruction. Note that this routine only targets integer vectors
7681 /// because for floating point vectors we have a generalized SHUFPS lowering
7682 /// strategy that handles everything that doesn't *exactly* match an unpack,
7683 /// making this clever lowering unnecessary.
7684 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7685                                           SDValue V2, ArrayRef<int> Mask,
7686                                           SelectionDAG &DAG) {
7687   assert(!VT.isFloatingPoint() &&
7688          "This routine only supports integer vectors.");
7689   assert(!isSingleInputShuffleMask(Mask) &&
7690          "This routine should only be used when blending two inputs.");
7691   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7692
7693   int Size = Mask.size();
7694
7695   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7696     return M >= 0 && M % Size < Size / 2;
7697   });
7698   int NumHiInputs = std::count_if(
7699       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7700
7701   bool UnpackLo = NumLoInputs >= NumHiInputs;
7702
7703   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7704     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7705     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7706
7707     for (int i = 0; i < Size; ++i) {
7708       if (Mask[i] < 0)
7709         continue;
7710
7711       // Each element of the unpack contains Scale elements from this mask.
7712       int UnpackIdx = i / Scale;
7713
7714       // We only handle the case where V1 feeds the first slots of the unpack.
7715       // We rely on canonicalization to ensure this is the case.
7716       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7717         return SDValue();
7718
7719       // Setup the mask for this input. The indexing is tricky as we have to
7720       // handle the unpack stride.
7721       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7722       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7723           Mask[i] % Size;
7724     }
7725
7726     // If we will have to shuffle both inputs to use the unpack, check whether
7727     // we can just unpack first and shuffle the result. If so, skip this unpack.
7728     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7729         !isNoopShuffleMask(V2Mask))
7730       return SDValue();
7731
7732     // Shuffle the inputs into place.
7733     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7734     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7735
7736     // Cast the inputs to the type we will use to unpack them.
7737     V1 = DAG.getBitcast(UnpackVT, V1);
7738     V2 = DAG.getBitcast(UnpackVT, V2);
7739
7740     // Unpack the inputs and cast the result back to the desired type.
7741     return DAG.getBitcast(
7742         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7743                         UnpackVT, V1, V2));
7744   };
7745
7746   // We try each unpack from the largest to the smallest to try and find one
7747   // that fits this mask.
7748   int OrigNumElements = VT.getVectorNumElements();
7749   int OrigScalarSize = VT.getScalarSizeInBits();
7750   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7751     int Scale = ScalarSize / OrigScalarSize;
7752     int NumElements = OrigNumElements / Scale;
7753     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7754     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7755       return Unpack;
7756   }
7757
7758   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7759   // initial unpack.
7760   if (NumLoInputs == 0 || NumHiInputs == 0) {
7761     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7762            "We have to have *some* inputs!");
7763     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7764
7765     // FIXME: We could consider the total complexity of the permute of each
7766     // possible unpacking. Or at the least we should consider how many
7767     // half-crossings are created.
7768     // FIXME: We could consider commuting the unpacks.
7769
7770     SmallVector<int, 32> PermMask;
7771     PermMask.assign(Size, -1);
7772     for (int i = 0; i < Size; ++i) {
7773       if (Mask[i] < 0)
7774         continue;
7775
7776       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7777
7778       PermMask[i] =
7779           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7780     }
7781     return DAG.getVectorShuffle(
7782         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7783                             DL, VT, V1, V2),
7784         DAG.getUNDEF(VT), PermMask);
7785   }
7786
7787   return SDValue();
7788 }
7789
7790 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7791 ///
7792 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7793 /// support for floating point shuffles but not integer shuffles. These
7794 /// instructions will incur a domain crossing penalty on some chips though so
7795 /// it is better to avoid lowering through this for integer vectors where
7796 /// possible.
7797 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7798                                        const X86Subtarget *Subtarget,
7799                                        SelectionDAG &DAG) {
7800   SDLoc DL(Op);
7801   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7802   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7803   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7804   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7805   ArrayRef<int> Mask = SVOp->getMask();
7806   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7807
7808   if (isSingleInputShuffleMask(Mask)) {
7809     // Use low duplicate instructions for masks that match their pattern.
7810     if (Subtarget->hasSSE3())
7811       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7812         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7813
7814     // Straight shuffle of a single input vector. Simulate this by using the
7815     // single input as both of the "inputs" to this instruction..
7816     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7817
7818     if (Subtarget->hasAVX()) {
7819       // If we have AVX, we can use VPERMILPS which will allow folding a load
7820       // into the shuffle.
7821       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7822                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7823     }
7824
7825     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7826                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7827   }
7828   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7829   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7830
7831   // If we have a single input, insert that into V1 if we can do so cheaply.
7832   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7833     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7834             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7835       return Insertion;
7836     // Try inverting the insertion since for v2 masks it is easy to do and we
7837     // can't reliably sort the mask one way or the other.
7838     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7839                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7840     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7841             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7842       return Insertion;
7843   }
7844
7845   // Try to use one of the special instruction patterns to handle two common
7846   // blend patterns if a zero-blend above didn't work.
7847   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7848       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7849     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7850       // We can either use a special instruction to load over the low double or
7851       // to move just the low double.
7852       return DAG.getNode(
7853           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7854           DL, MVT::v2f64, V2,
7855           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7856
7857   if (Subtarget->hasSSE41())
7858     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7859                                                   Subtarget, DAG))
7860       return Blend;
7861
7862   // Use dedicated unpack instructions for masks that match their pattern.
7863   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7864     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7865   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7866     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7867
7868   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7869   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7870                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7871 }
7872
7873 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7874 ///
7875 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7876 /// the integer unit to minimize domain crossing penalties. However, for blends
7877 /// it falls back to the floating point shuffle operation with appropriate bit
7878 /// casting.
7879 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7880                                        const X86Subtarget *Subtarget,
7881                                        SelectionDAG &DAG) {
7882   SDLoc DL(Op);
7883   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7884   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7885   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7886   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7887   ArrayRef<int> Mask = SVOp->getMask();
7888   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7889
7890   if (isSingleInputShuffleMask(Mask)) {
7891     // Check for being able to broadcast a single element.
7892     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7893                                                           Mask, Subtarget, DAG))
7894       return Broadcast;
7895
7896     // Straight shuffle of a single input vector. For everything from SSE2
7897     // onward this has a single fast instruction with no scary immediates.
7898     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7899     V1 = DAG.getBitcast(MVT::v4i32, V1);
7900     int WidenedMask[4] = {
7901         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7902         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7903     return DAG.getBitcast(
7904         MVT::v2i64,
7905         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7906                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7907   }
7908   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7909   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7910   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7911   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7912
7913   // If we have a blend of two PACKUS operations an the blend aligns with the
7914   // low and half halves, we can just merge the PACKUS operations. This is
7915   // particularly important as it lets us merge shuffles that this routine itself
7916   // creates.
7917   auto GetPackNode = [](SDValue V) {
7918     while (V.getOpcode() == ISD::BITCAST)
7919       V = V.getOperand(0);
7920
7921     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7922   };
7923   if (SDValue V1Pack = GetPackNode(V1))
7924     if (SDValue V2Pack = GetPackNode(V2))
7925       return DAG.getBitcast(MVT::v2i64,
7926                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7927                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7928                                                      : V1Pack.getOperand(1),
7929                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7930                                                      : V2Pack.getOperand(1)));
7931
7932   // Try to use shift instructions.
7933   if (SDValue Shift =
7934           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7935     return Shift;
7936
7937   // When loading a scalar and then shuffling it into a vector we can often do
7938   // the insertion cheaply.
7939   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7940           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7941     return Insertion;
7942   // Try inverting the insertion since for v2 masks it is easy to do and we
7943   // can't reliably sort the mask one way or the other.
7944   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7945   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7946           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7947     return Insertion;
7948
7949   // We have different paths for blend lowering, but they all must use the
7950   // *exact* same predicate.
7951   bool IsBlendSupported = Subtarget->hasSSE41();
7952   if (IsBlendSupported)
7953     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7954                                                   Subtarget, DAG))
7955       return Blend;
7956
7957   // Use dedicated unpack instructions for masks that match their pattern.
7958   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7959     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7960   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7961     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7962
7963   // Try to use byte rotation instructions.
7964   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7965   if (Subtarget->hasSSSE3())
7966     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7967             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7968       return Rotate;
7969
7970   // If we have direct support for blends, we should lower by decomposing into
7971   // a permute. That will be faster than the domain cross.
7972   if (IsBlendSupported)
7973     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7974                                                       Mask, DAG);
7975
7976   // We implement this with SHUFPD which is pretty lame because it will likely
7977   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7978   // However, all the alternatives are still more cycles and newer chips don't
7979   // have this problem. It would be really nice if x86 had better shuffles here.
7980   V1 = DAG.getBitcast(MVT::v2f64, V1);
7981   V2 = DAG.getBitcast(MVT::v2f64, V2);
7982   return DAG.getBitcast(MVT::v2i64,
7983                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7984 }
7985
7986 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7987 ///
7988 /// This is used to disable more specialized lowerings when the shufps lowering
7989 /// will happen to be efficient.
7990 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7991   // This routine only handles 128-bit shufps.
7992   assert(Mask.size() == 4 && "Unsupported mask size!");
7993
7994   // To lower with a single SHUFPS we need to have the low half and high half
7995   // each requiring a single input.
7996   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7997     return false;
7998   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7999     return false;
8000
8001   return true;
8002 }
8003
8004 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8005 ///
8006 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8007 /// It makes no assumptions about whether this is the *best* lowering, it simply
8008 /// uses it.
8009 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8010                                             ArrayRef<int> Mask, SDValue V1,
8011                                             SDValue V2, SelectionDAG &DAG) {
8012   SDValue LowV = V1, HighV = V2;
8013   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8014
8015   int NumV2Elements =
8016       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8017
8018   if (NumV2Elements == 1) {
8019     int V2Index =
8020         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8021         Mask.begin();
8022
8023     // Compute the index adjacent to V2Index and in the same half by toggling
8024     // the low bit.
8025     int V2AdjIndex = V2Index ^ 1;
8026
8027     if (Mask[V2AdjIndex] == -1) {
8028       // Handles all the cases where we have a single V2 element and an undef.
8029       // This will only ever happen in the high lanes because we commute the
8030       // vector otherwise.
8031       if (V2Index < 2)
8032         std::swap(LowV, HighV);
8033       NewMask[V2Index] -= 4;
8034     } else {
8035       // Handle the case where the V2 element ends up adjacent to a V1 element.
8036       // To make this work, blend them together as the first step.
8037       int V1Index = V2AdjIndex;
8038       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8039       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8040                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8041
8042       // Now proceed to reconstruct the final blend as we have the necessary
8043       // high or low half formed.
8044       if (V2Index < 2) {
8045         LowV = V2;
8046         HighV = V1;
8047       } else {
8048         HighV = V2;
8049       }
8050       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8051       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8052     }
8053   } else if (NumV2Elements == 2) {
8054     if (Mask[0] < 4 && Mask[1] < 4) {
8055       // Handle the easy case where we have V1 in the low lanes and V2 in the
8056       // high lanes.
8057       NewMask[2] -= 4;
8058       NewMask[3] -= 4;
8059     } else if (Mask[2] < 4 && Mask[3] < 4) {
8060       // We also handle the reversed case because this utility may get called
8061       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8062       // arrange things in the right direction.
8063       NewMask[0] -= 4;
8064       NewMask[1] -= 4;
8065       HighV = V1;
8066       LowV = V2;
8067     } else {
8068       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8069       // trying to place elements directly, just blend them and set up the final
8070       // shuffle to place them.
8071
8072       // The first two blend mask elements are for V1, the second two are for
8073       // V2.
8074       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8075                           Mask[2] < 4 ? Mask[2] : Mask[3],
8076                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8077                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8078       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8079                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8080
8081       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8082       // a blend.
8083       LowV = HighV = V1;
8084       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8085       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8086       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8087       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8088     }
8089   }
8090   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8091                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8092 }
8093
8094 /// \brief Lower 4-lane 32-bit floating point shuffles.
8095 ///
8096 /// Uses instructions exclusively from the floating point unit to minimize
8097 /// domain crossing penalties, as these are sufficient to implement all v4f32
8098 /// shuffles.
8099 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8100                                        const X86Subtarget *Subtarget,
8101                                        SelectionDAG &DAG) {
8102   SDLoc DL(Op);
8103   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8104   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8105   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8106   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8107   ArrayRef<int> Mask = SVOp->getMask();
8108   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8109
8110   int NumV2Elements =
8111       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8112
8113   if (NumV2Elements == 0) {
8114     // Check for being able to broadcast a single element.
8115     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8116                                                           Mask, Subtarget, DAG))
8117       return Broadcast;
8118
8119     // Use even/odd duplicate instructions for masks that match their pattern.
8120     if (Subtarget->hasSSE3()) {
8121       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8122         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8123       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8124         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8125     }
8126
8127     if (Subtarget->hasAVX()) {
8128       // If we have AVX, we can use VPERMILPS which will allow folding a load
8129       // into the shuffle.
8130       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8131                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8132     }
8133
8134     // Otherwise, use a straight shuffle of a single input vector. We pass the
8135     // input vector to both operands to simulate this with a SHUFPS.
8136     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8137                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8138   }
8139
8140   // There are special ways we can lower some single-element blends. However, we
8141   // have custom ways we can lower more complex single-element blends below that
8142   // we defer to if both this and BLENDPS fail to match, so restrict this to
8143   // when the V2 input is targeting element 0 of the mask -- that is the fast
8144   // case here.
8145   if (NumV2Elements == 1 && Mask[0] >= 4)
8146     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8147                                                          Mask, Subtarget, DAG))
8148       return V;
8149
8150   if (Subtarget->hasSSE41()) {
8151     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8152                                                   Subtarget, DAG))
8153       return Blend;
8154
8155     // Use INSERTPS if we can complete the shuffle efficiently.
8156     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8157       return V;
8158
8159     if (!isSingleSHUFPSMask(Mask))
8160       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8161               DL, MVT::v4f32, V1, V2, Mask, DAG))
8162         return BlendPerm;
8163   }
8164
8165   // Use dedicated unpack instructions for masks that match their pattern.
8166   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8167     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8168   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8169     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8170   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8171     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8172   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8173     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8174
8175   // Otherwise fall back to a SHUFPS lowering strategy.
8176   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8177 }
8178
8179 /// \brief Lower 4-lane i32 vector shuffles.
8180 ///
8181 /// We try to handle these with integer-domain shuffles where we can, but for
8182 /// blends we use the floating point domain blend instructions.
8183 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8184                                        const X86Subtarget *Subtarget,
8185                                        SelectionDAG &DAG) {
8186   SDLoc DL(Op);
8187   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8188   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8189   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8190   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8191   ArrayRef<int> Mask = SVOp->getMask();
8192   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8193
8194   // Whenever we can lower this as a zext, that instruction is strictly faster
8195   // than any alternative. It also allows us to fold memory operands into the
8196   // shuffle in many cases.
8197   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8198                                                          Mask, Subtarget, DAG))
8199     return ZExt;
8200
8201   int NumV2Elements =
8202       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8203
8204   if (NumV2Elements == 0) {
8205     // Check for being able to broadcast a single element.
8206     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8207                                                           Mask, Subtarget, DAG))
8208       return Broadcast;
8209
8210     // Straight shuffle of a single input vector. For everything from SSE2
8211     // onward this has a single fast instruction with no scary immediates.
8212     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8213     // but we aren't actually going to use the UNPCK instruction because doing
8214     // so prevents folding a load into this instruction or making a copy.
8215     const int UnpackLoMask[] = {0, 0, 1, 1};
8216     const int UnpackHiMask[] = {2, 2, 3, 3};
8217     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8218       Mask = UnpackLoMask;
8219     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8220       Mask = UnpackHiMask;
8221
8222     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8223                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8224   }
8225
8226   // Try to use shift instructions.
8227   if (SDValue Shift =
8228           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8229     return Shift;
8230
8231   // There are special ways we can lower some single-element blends.
8232   if (NumV2Elements == 1)
8233     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8234                                                          Mask, Subtarget, DAG))
8235       return V;
8236
8237   // We have different paths for blend lowering, but they all must use the
8238   // *exact* same predicate.
8239   bool IsBlendSupported = Subtarget->hasSSE41();
8240   if (IsBlendSupported)
8241     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8242                                                   Subtarget, DAG))
8243       return Blend;
8244
8245   if (SDValue Masked =
8246           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8247     return Masked;
8248
8249   // Use dedicated unpack instructions for masks that match their pattern.
8250   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8251     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8252   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8253     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8254   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8255     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8256   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8257     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8258
8259   // Try to use byte rotation instructions.
8260   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8261   if (Subtarget->hasSSSE3())
8262     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8263             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8264       return Rotate;
8265
8266   // If we have direct support for blends, we should lower by decomposing into
8267   // a permute. That will be faster than the domain cross.
8268   if (IsBlendSupported)
8269     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8270                                                       Mask, DAG);
8271
8272   // Try to lower by permuting the inputs into an unpack instruction.
8273   if (SDValue Unpack =
8274           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8275     return Unpack;
8276
8277   // We implement this with SHUFPS because it can blend from two vectors.
8278   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8279   // up the inputs, bypassing domain shift penalties that we would encur if we
8280   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8281   // relevant.
8282   return DAG.getBitcast(
8283       MVT::v4i32,
8284       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8285                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8286 }
8287
8288 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8289 /// shuffle lowering, and the most complex part.
8290 ///
8291 /// The lowering strategy is to try to form pairs of input lanes which are
8292 /// targeted at the same half of the final vector, and then use a dword shuffle
8293 /// to place them onto the right half, and finally unpack the paired lanes into
8294 /// their final position.
8295 ///
8296 /// The exact breakdown of how to form these dword pairs and align them on the
8297 /// correct sides is really tricky. See the comments within the function for
8298 /// more of the details.
8299 ///
8300 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8301 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8302 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8303 /// vector, form the analogous 128-bit 8-element Mask.
8304 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8305     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8306     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8307   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8308   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8309
8310   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8311   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8312   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8313
8314   SmallVector<int, 4> LoInputs;
8315   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8316                [](int M) { return M >= 0; });
8317   std::sort(LoInputs.begin(), LoInputs.end());
8318   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8319   SmallVector<int, 4> HiInputs;
8320   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8321                [](int M) { return M >= 0; });
8322   std::sort(HiInputs.begin(), HiInputs.end());
8323   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8324   int NumLToL =
8325       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8326   int NumHToL = LoInputs.size() - NumLToL;
8327   int NumLToH =
8328       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8329   int NumHToH = HiInputs.size() - NumLToH;
8330   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8331   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8332   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8333   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8334
8335   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8336   // such inputs we can swap two of the dwords across the half mark and end up
8337   // with <=2 inputs to each half in each half. Once there, we can fall through
8338   // to the generic code below. For example:
8339   //
8340   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8341   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8342   //
8343   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8344   // and an existing 2-into-2 on the other half. In this case we may have to
8345   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8346   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8347   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8348   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8349   // half than the one we target for fixing) will be fixed when we re-enter this
8350   // path. We will also combine away any sequence of PSHUFD instructions that
8351   // result into a single instruction. Here is an example of the tricky case:
8352   //
8353   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8354   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8355   //
8356   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8357   //
8358   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8359   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8360   //
8361   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8362   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8363   //
8364   // The result is fine to be handled by the generic logic.
8365   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8366                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8367                           int AOffset, int BOffset) {
8368     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8369            "Must call this with A having 3 or 1 inputs from the A half.");
8370     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8371            "Must call this with B having 1 or 3 inputs from the B half.");
8372     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8373            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8374
8375     bool ThreeAInputs = AToAInputs.size() == 3;
8376
8377     // Compute the index of dword with only one word among the three inputs in
8378     // a half by taking the sum of the half with three inputs and subtracting
8379     // the sum of the actual three inputs. The difference is the remaining
8380     // slot.
8381     int ADWord, BDWord;
8382     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8383     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8384     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8385     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8386     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8387     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8388     int TripleNonInputIdx =
8389         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8390     TripleDWord = TripleNonInputIdx / 2;
8391
8392     // We use xor with one to compute the adjacent DWord to whichever one the
8393     // OneInput is in.
8394     OneInputDWord = (OneInput / 2) ^ 1;
8395
8396     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8397     // and BToA inputs. If there is also such a problem with the BToB and AToB
8398     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8399     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8400     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8401     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8402       // Compute how many inputs will be flipped by swapping these DWords. We
8403       // need
8404       // to balance this to ensure we don't form a 3-1 shuffle in the other
8405       // half.
8406       int NumFlippedAToBInputs =
8407           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8408           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8409       int NumFlippedBToBInputs =
8410           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8411           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8412       if ((NumFlippedAToBInputs == 1 &&
8413            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8414           (NumFlippedBToBInputs == 1 &&
8415            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8416         // We choose whether to fix the A half or B half based on whether that
8417         // half has zero flipped inputs. At zero, we may not be able to fix it
8418         // with that half. We also bias towards fixing the B half because that
8419         // will more commonly be the high half, and we have to bias one way.
8420         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8421                                                        ArrayRef<int> Inputs) {
8422           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8423           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8424                                          PinnedIdx ^ 1) != Inputs.end();
8425           // Determine whether the free index is in the flipped dword or the
8426           // unflipped dword based on where the pinned index is. We use this bit
8427           // in an xor to conditionally select the adjacent dword.
8428           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8429           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8430                                              FixFreeIdx) != Inputs.end();
8431           if (IsFixIdxInput == IsFixFreeIdxInput)
8432             FixFreeIdx += 1;
8433           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8434                                         FixFreeIdx) != Inputs.end();
8435           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8436                  "We need to be changing the number of flipped inputs!");
8437           int PSHUFHalfMask[] = {0, 1, 2, 3};
8438           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8439           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8440                           MVT::v8i16, V,
8441                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8442
8443           for (int &M : Mask)
8444             if (M != -1 && M == FixIdx)
8445               M = FixFreeIdx;
8446             else if (M != -1 && M == FixFreeIdx)
8447               M = FixIdx;
8448         };
8449         if (NumFlippedBToBInputs != 0) {
8450           int BPinnedIdx =
8451               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8452           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8453         } else {
8454           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8455           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8456           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8457         }
8458       }
8459     }
8460
8461     int PSHUFDMask[] = {0, 1, 2, 3};
8462     PSHUFDMask[ADWord] = BDWord;
8463     PSHUFDMask[BDWord] = ADWord;
8464     V = DAG.getBitcast(
8465         VT,
8466         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8467                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8468
8469     // Adjust the mask to match the new locations of A and B.
8470     for (int &M : Mask)
8471       if (M != -1 && M/2 == ADWord)
8472         M = 2 * BDWord + M % 2;
8473       else if (M != -1 && M/2 == BDWord)
8474         M = 2 * ADWord + M % 2;
8475
8476     // Recurse back into this routine to re-compute state now that this isn't
8477     // a 3 and 1 problem.
8478     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8479                                                      DAG);
8480   };
8481   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8482     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8483   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8484     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8485
8486   // At this point there are at most two inputs to the low and high halves from
8487   // each half. That means the inputs can always be grouped into dwords and
8488   // those dwords can then be moved to the correct half with a dword shuffle.
8489   // We use at most one low and one high word shuffle to collect these paired
8490   // inputs into dwords, and finally a dword shuffle to place them.
8491   int PSHUFLMask[4] = {-1, -1, -1, -1};
8492   int PSHUFHMask[4] = {-1, -1, -1, -1};
8493   int PSHUFDMask[4] = {-1, -1, -1, -1};
8494
8495   // First fix the masks for all the inputs that are staying in their
8496   // original halves. This will then dictate the targets of the cross-half
8497   // shuffles.
8498   auto fixInPlaceInputs =
8499       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8500                     MutableArrayRef<int> SourceHalfMask,
8501                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8502     if (InPlaceInputs.empty())
8503       return;
8504     if (InPlaceInputs.size() == 1) {
8505       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8506           InPlaceInputs[0] - HalfOffset;
8507       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8508       return;
8509     }
8510     if (IncomingInputs.empty()) {
8511       // Just fix all of the in place inputs.
8512       for (int Input : InPlaceInputs) {
8513         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8514         PSHUFDMask[Input / 2] = Input / 2;
8515       }
8516       return;
8517     }
8518
8519     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8520     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8521         InPlaceInputs[0] - HalfOffset;
8522     // Put the second input next to the first so that they are packed into
8523     // a dword. We find the adjacent index by toggling the low bit.
8524     int AdjIndex = InPlaceInputs[0] ^ 1;
8525     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8526     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8527     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8528   };
8529   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8530   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8531
8532   // Now gather the cross-half inputs and place them into a free dword of
8533   // their target half.
8534   // FIXME: This operation could almost certainly be simplified dramatically to
8535   // look more like the 3-1 fixing operation.
8536   auto moveInputsToRightHalf = [&PSHUFDMask](
8537       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8538       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8539       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8540       int DestOffset) {
8541     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8542       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8543     };
8544     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8545                                                int Word) {
8546       int LowWord = Word & ~1;
8547       int HighWord = Word | 1;
8548       return isWordClobbered(SourceHalfMask, LowWord) ||
8549              isWordClobbered(SourceHalfMask, HighWord);
8550     };
8551
8552     if (IncomingInputs.empty())
8553       return;
8554
8555     if (ExistingInputs.empty()) {
8556       // Map any dwords with inputs from them into the right half.
8557       for (int Input : IncomingInputs) {
8558         // If the source half mask maps over the inputs, turn those into
8559         // swaps and use the swapped lane.
8560         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8561           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8562             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8563                 Input - SourceOffset;
8564             // We have to swap the uses in our half mask in one sweep.
8565             for (int &M : HalfMask)
8566               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8567                 M = Input;
8568               else if (M == Input)
8569                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8570           } else {
8571             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8572                        Input - SourceOffset &&
8573                    "Previous placement doesn't match!");
8574           }
8575           // Note that this correctly re-maps both when we do a swap and when
8576           // we observe the other side of the swap above. We rely on that to
8577           // avoid swapping the members of the input list directly.
8578           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8579         }
8580
8581         // Map the input's dword into the correct half.
8582         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8583           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8584         else
8585           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8586                      Input / 2 &&
8587                  "Previous placement doesn't match!");
8588       }
8589
8590       // And just directly shift any other-half mask elements to be same-half
8591       // as we will have mirrored the dword containing the element into the
8592       // same position within that half.
8593       for (int &M : HalfMask)
8594         if (M >= SourceOffset && M < SourceOffset + 4) {
8595           M = M - SourceOffset + DestOffset;
8596           assert(M >= 0 && "This should never wrap below zero!");
8597         }
8598       return;
8599     }
8600
8601     // Ensure we have the input in a viable dword of its current half. This
8602     // is particularly tricky because the original position may be clobbered
8603     // by inputs being moved and *staying* in that half.
8604     if (IncomingInputs.size() == 1) {
8605       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8606         int InputFixed = std::find(std::begin(SourceHalfMask),
8607                                    std::end(SourceHalfMask), -1) -
8608                          std::begin(SourceHalfMask) + SourceOffset;
8609         SourceHalfMask[InputFixed - SourceOffset] =
8610             IncomingInputs[0] - SourceOffset;
8611         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8612                      InputFixed);
8613         IncomingInputs[0] = InputFixed;
8614       }
8615     } else if (IncomingInputs.size() == 2) {
8616       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8617           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8618         // We have two non-adjacent or clobbered inputs we need to extract from
8619         // the source half. To do this, we need to map them into some adjacent
8620         // dword slot in the source mask.
8621         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8622                               IncomingInputs[1] - SourceOffset};
8623
8624         // If there is a free slot in the source half mask adjacent to one of
8625         // the inputs, place the other input in it. We use (Index XOR 1) to
8626         // compute an adjacent index.
8627         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8628             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8629           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8630           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8631           InputsFixed[1] = InputsFixed[0] ^ 1;
8632         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8633                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8634           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8635           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8636           InputsFixed[0] = InputsFixed[1] ^ 1;
8637         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8638                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8639           // The two inputs are in the same DWord but it is clobbered and the
8640           // adjacent DWord isn't used at all. Move both inputs to the free
8641           // slot.
8642           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8643           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8644           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8645           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8646         } else {
8647           // The only way we hit this point is if there is no clobbering
8648           // (because there are no off-half inputs to this half) and there is no
8649           // free slot adjacent to one of the inputs. In this case, we have to
8650           // swap an input with a non-input.
8651           for (int i = 0; i < 4; ++i)
8652             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8653                    "We can't handle any clobbers here!");
8654           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8655                  "Cannot have adjacent inputs here!");
8656
8657           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8658           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8659
8660           // We also have to update the final source mask in this case because
8661           // it may need to undo the above swap.
8662           for (int &M : FinalSourceHalfMask)
8663             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8664               M = InputsFixed[1] + SourceOffset;
8665             else if (M == InputsFixed[1] + SourceOffset)
8666               M = (InputsFixed[0] ^ 1) + SourceOffset;
8667
8668           InputsFixed[1] = InputsFixed[0] ^ 1;
8669         }
8670
8671         // Point everything at the fixed inputs.
8672         for (int &M : HalfMask)
8673           if (M == IncomingInputs[0])
8674             M = InputsFixed[0] + SourceOffset;
8675           else if (M == IncomingInputs[1])
8676             M = InputsFixed[1] + SourceOffset;
8677
8678         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8679         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8680       }
8681     } else {
8682       llvm_unreachable("Unhandled input size!");
8683     }
8684
8685     // Now hoist the DWord down to the right half.
8686     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8687     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8688     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8689     for (int &M : HalfMask)
8690       for (int Input : IncomingInputs)
8691         if (M == Input)
8692           M = FreeDWord * 2 + Input % 2;
8693   };
8694   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8695                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8696   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8697                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8698
8699   // Now enact all the shuffles we've computed to move the inputs into their
8700   // target half.
8701   if (!isNoopShuffleMask(PSHUFLMask))
8702     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8703                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8704   if (!isNoopShuffleMask(PSHUFHMask))
8705     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8706                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8707   if (!isNoopShuffleMask(PSHUFDMask))
8708     V = DAG.getBitcast(
8709         VT,
8710         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8711                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8712
8713   // At this point, each half should contain all its inputs, and we can then
8714   // just shuffle them into their final position.
8715   assert(std::count_if(LoMask.begin(), LoMask.end(),
8716                        [](int M) { return M >= 4; }) == 0 &&
8717          "Failed to lift all the high half inputs to the low mask!");
8718   assert(std::count_if(HiMask.begin(), HiMask.end(),
8719                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8720          "Failed to lift all the low half inputs to the high mask!");
8721
8722   // Do a half shuffle for the low mask.
8723   if (!isNoopShuffleMask(LoMask))
8724     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8725                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8726
8727   // Do a half shuffle with the high mask after shifting its values down.
8728   for (int &M : HiMask)
8729     if (M >= 0)
8730       M -= 4;
8731   if (!isNoopShuffleMask(HiMask))
8732     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8733                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8734
8735   return V;
8736 }
8737
8738 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8739 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8740                                           SDValue V2, ArrayRef<int> Mask,
8741                                           SelectionDAG &DAG, bool &V1InUse,
8742                                           bool &V2InUse) {
8743   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8744   SDValue V1Mask[16];
8745   SDValue V2Mask[16];
8746   V1InUse = false;
8747   V2InUse = false;
8748
8749   int Size = Mask.size();
8750   int Scale = 16 / Size;
8751   for (int i = 0; i < 16; ++i) {
8752     if (Mask[i / Scale] == -1) {
8753       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8754     } else {
8755       const int ZeroMask = 0x80;
8756       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8757                                           : ZeroMask;
8758       int V2Idx = Mask[i / Scale] < Size
8759                       ? ZeroMask
8760                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8761       if (Zeroable[i / Scale])
8762         V1Idx = V2Idx = ZeroMask;
8763       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8764       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8765       V1InUse |= (ZeroMask != V1Idx);
8766       V2InUse |= (ZeroMask != V2Idx);
8767     }
8768   }
8769
8770   if (V1InUse)
8771     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8772                      DAG.getBitcast(MVT::v16i8, V1),
8773                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8774   if (V2InUse)
8775     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8776                      DAG.getBitcast(MVT::v16i8, V2),
8777                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8778
8779   // If we need shuffled inputs from both, blend the two.
8780   SDValue V;
8781   if (V1InUse && V2InUse)
8782     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8783   else
8784     V = V1InUse ? V1 : V2;
8785
8786   // Cast the result back to the correct type.
8787   return DAG.getBitcast(VT, V);
8788 }
8789
8790 /// \brief Generic lowering of 8-lane i16 shuffles.
8791 ///
8792 /// This handles both single-input shuffles and combined shuffle/blends with
8793 /// two inputs. The single input shuffles are immediately delegated to
8794 /// a dedicated lowering routine.
8795 ///
8796 /// The blends are lowered in one of three fundamental ways. If there are few
8797 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8798 /// of the input is significantly cheaper when lowered as an interleaving of
8799 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8800 /// halves of the inputs separately (making them have relatively few inputs)
8801 /// and then concatenate them.
8802 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8803                                        const X86Subtarget *Subtarget,
8804                                        SelectionDAG &DAG) {
8805   SDLoc DL(Op);
8806   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8807   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8808   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8809   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8810   ArrayRef<int> OrigMask = SVOp->getMask();
8811   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8812                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8813   MutableArrayRef<int> Mask(MaskStorage);
8814
8815   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8816
8817   // Whenever we can lower this as a zext, that instruction is strictly faster
8818   // than any alternative.
8819   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8820           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8821     return ZExt;
8822
8823   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8824   (void)isV1;
8825   auto isV2 = [](int M) { return M >= 8; };
8826
8827   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8828
8829   if (NumV2Inputs == 0) {
8830     // Check for being able to broadcast a single element.
8831     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8832                                                           Mask, Subtarget, DAG))
8833       return Broadcast;
8834
8835     // Try to use shift instructions.
8836     if (SDValue Shift =
8837             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8838       return Shift;
8839
8840     // Use dedicated unpack instructions for masks that match their pattern.
8841     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8842       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8843     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8844       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8845
8846     // Try to use byte rotation instructions.
8847     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8848                                                         Mask, Subtarget, DAG))
8849       return Rotate;
8850
8851     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8852                                                      Subtarget, DAG);
8853   }
8854
8855   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8856          "All single-input shuffles should be canonicalized to be V1-input "
8857          "shuffles.");
8858
8859   // Try to use shift instructions.
8860   if (SDValue Shift =
8861           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8862     return Shift;
8863
8864   // See if we can use SSE4A Extraction / Insertion.
8865   if (Subtarget->hasSSE4A())
8866     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8867       return V;
8868
8869   // There are special ways we can lower some single-element blends.
8870   if (NumV2Inputs == 1)
8871     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8872                                                          Mask, Subtarget, DAG))
8873       return V;
8874
8875   // We have different paths for blend lowering, but they all must use the
8876   // *exact* same predicate.
8877   bool IsBlendSupported = Subtarget->hasSSE41();
8878   if (IsBlendSupported)
8879     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8880                                                   Subtarget, DAG))
8881       return Blend;
8882
8883   if (SDValue Masked =
8884           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8885     return Masked;
8886
8887   // Use dedicated unpack instructions for masks that match their pattern.
8888   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8889     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8890   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8891     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8892
8893   // Try to use byte rotation instructions.
8894   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8895           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8896     return Rotate;
8897
8898   if (SDValue BitBlend =
8899           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8900     return BitBlend;
8901
8902   if (SDValue Unpack =
8903           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8904     return Unpack;
8905
8906   // If we can't directly blend but can use PSHUFB, that will be better as it
8907   // can both shuffle and set up the inefficient blend.
8908   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8909     bool V1InUse, V2InUse;
8910     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8911                                       V1InUse, V2InUse);
8912   }
8913
8914   // We can always bit-blend if we have to so the fallback strategy is to
8915   // decompose into single-input permutes and blends.
8916   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8917                                                       Mask, DAG);
8918 }
8919
8920 /// \brief Check whether a compaction lowering can be done by dropping even
8921 /// elements and compute how many times even elements must be dropped.
8922 ///
8923 /// This handles shuffles which take every Nth element where N is a power of
8924 /// two. Example shuffle masks:
8925 ///
8926 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8927 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8928 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8929 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8930 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8931 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8932 ///
8933 /// Any of these lanes can of course be undef.
8934 ///
8935 /// This routine only supports N <= 3.
8936 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8937 /// for larger N.
8938 ///
8939 /// \returns N above, or the number of times even elements must be dropped if
8940 /// there is such a number. Otherwise returns zero.
8941 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8942   // Figure out whether we're looping over two inputs or just one.
8943   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8944
8945   // The modulus for the shuffle vector entries is based on whether this is
8946   // a single input or not.
8947   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8948   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8949          "We should only be called with masks with a power-of-2 size!");
8950
8951   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8952
8953   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8954   // and 2^3 simultaneously. This is because we may have ambiguity with
8955   // partially undef inputs.
8956   bool ViableForN[3] = {true, true, true};
8957
8958   for (int i = 0, e = Mask.size(); i < e; ++i) {
8959     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8960     // want.
8961     if (Mask[i] == -1)
8962       continue;
8963
8964     bool IsAnyViable = false;
8965     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8966       if (ViableForN[j]) {
8967         uint64_t N = j + 1;
8968
8969         // The shuffle mask must be equal to (i * 2^N) % M.
8970         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8971           IsAnyViable = true;
8972         else
8973           ViableForN[j] = false;
8974       }
8975     // Early exit if we exhaust the possible powers of two.
8976     if (!IsAnyViable)
8977       break;
8978   }
8979
8980   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8981     if (ViableForN[j])
8982       return j + 1;
8983
8984   // Return 0 as there is no viable power of two.
8985   return 0;
8986 }
8987
8988 /// \brief Generic lowering of v16i8 shuffles.
8989 ///
8990 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8991 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8992 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8993 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8994 /// back together.
8995 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8996                                        const X86Subtarget *Subtarget,
8997                                        SelectionDAG &DAG) {
8998   SDLoc DL(Op);
8999   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9000   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9001   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9002   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9003   ArrayRef<int> Mask = SVOp->getMask();
9004   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9005
9006   // Try to use shift instructions.
9007   if (SDValue Shift =
9008           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9009     return Shift;
9010
9011   // Try to use byte rotation instructions.
9012   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9013           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9014     return Rotate;
9015
9016   // Try to use a zext lowering.
9017   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9018           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9019     return ZExt;
9020
9021   // See if we can use SSE4A Extraction / Insertion.
9022   if (Subtarget->hasSSE4A())
9023     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9024       return V;
9025
9026   int NumV2Elements =
9027       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9028
9029   // For single-input shuffles, there are some nicer lowering tricks we can use.
9030   if (NumV2Elements == 0) {
9031     // Check for being able to broadcast a single element.
9032     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9033                                                           Mask, Subtarget, DAG))
9034       return Broadcast;
9035
9036     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9037     // Notably, this handles splat and partial-splat shuffles more efficiently.
9038     // However, it only makes sense if the pre-duplication shuffle simplifies
9039     // things significantly. Currently, this means we need to be able to
9040     // express the pre-duplication shuffle as an i16 shuffle.
9041     //
9042     // FIXME: We should check for other patterns which can be widened into an
9043     // i16 shuffle as well.
9044     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9045       for (int i = 0; i < 16; i += 2)
9046         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9047           return false;
9048
9049       return true;
9050     };
9051     auto tryToWidenViaDuplication = [&]() -> SDValue {
9052       if (!canWidenViaDuplication(Mask))
9053         return SDValue();
9054       SmallVector<int, 4> LoInputs;
9055       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9056                    [](int M) { return M >= 0 && M < 8; });
9057       std::sort(LoInputs.begin(), LoInputs.end());
9058       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9059                      LoInputs.end());
9060       SmallVector<int, 4> HiInputs;
9061       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9062                    [](int M) { return M >= 8; });
9063       std::sort(HiInputs.begin(), HiInputs.end());
9064       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9065                      HiInputs.end());
9066
9067       bool TargetLo = LoInputs.size() >= HiInputs.size();
9068       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9069       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9070
9071       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9072       SmallDenseMap<int, int, 8> LaneMap;
9073       for (int I : InPlaceInputs) {
9074         PreDupI16Shuffle[I/2] = I/2;
9075         LaneMap[I] = I;
9076       }
9077       int j = TargetLo ? 0 : 4, je = j + 4;
9078       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9079         // Check if j is already a shuffle of this input. This happens when
9080         // there are two adjacent bytes after we move the low one.
9081         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9082           // If we haven't yet mapped the input, search for a slot into which
9083           // we can map it.
9084           while (j < je && PreDupI16Shuffle[j] != -1)
9085             ++j;
9086
9087           if (j == je)
9088             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9089             return SDValue();
9090
9091           // Map this input with the i16 shuffle.
9092           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9093         }
9094
9095         // Update the lane map based on the mapping we ended up with.
9096         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9097       }
9098       V1 = DAG.getBitcast(
9099           MVT::v16i8,
9100           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9101                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9102
9103       // Unpack the bytes to form the i16s that will be shuffled into place.
9104       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9105                        MVT::v16i8, V1, V1);
9106
9107       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9108       for (int i = 0; i < 16; ++i)
9109         if (Mask[i] != -1) {
9110           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9111           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9112           if (PostDupI16Shuffle[i / 2] == -1)
9113             PostDupI16Shuffle[i / 2] = MappedMask;
9114           else
9115             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9116                    "Conflicting entrties in the original shuffle!");
9117         }
9118       return DAG.getBitcast(
9119           MVT::v16i8,
9120           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9121                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9122     };
9123     if (SDValue V = tryToWidenViaDuplication())
9124       return V;
9125   }
9126
9127   if (SDValue Masked =
9128           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9129     return Masked;
9130
9131   // Use dedicated unpack instructions for masks that match their pattern.
9132   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9133                                          0, 16, 1, 17, 2, 18, 3, 19,
9134                                          // High half.
9135                                          4, 20, 5, 21, 6, 22, 7, 23}))
9136     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9137   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9138                                          8, 24, 9, 25, 10, 26, 11, 27,
9139                                          // High half.
9140                                          12, 28, 13, 29, 14, 30, 15, 31}))
9141     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9142
9143   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9144   // with PSHUFB. It is important to do this before we attempt to generate any
9145   // blends but after all of the single-input lowerings. If the single input
9146   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9147   // want to preserve that and we can DAG combine any longer sequences into
9148   // a PSHUFB in the end. But once we start blending from multiple inputs,
9149   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9150   // and there are *very* few patterns that would actually be faster than the
9151   // PSHUFB approach because of its ability to zero lanes.
9152   //
9153   // FIXME: The only exceptions to the above are blends which are exact
9154   // interleavings with direct instructions supporting them. We currently don't
9155   // handle those well here.
9156   if (Subtarget->hasSSSE3()) {
9157     bool V1InUse = false;
9158     bool V2InUse = false;
9159
9160     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9161                                                 DAG, V1InUse, V2InUse);
9162
9163     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9164     // do so. This avoids using them to handle blends-with-zero which is
9165     // important as a single pshufb is significantly faster for that.
9166     if (V1InUse && V2InUse) {
9167       if (Subtarget->hasSSE41())
9168         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9169                                                       Mask, Subtarget, DAG))
9170           return Blend;
9171
9172       // We can use an unpack to do the blending rather than an or in some
9173       // cases. Even though the or may be (very minorly) more efficient, we
9174       // preference this lowering because there are common cases where part of
9175       // the complexity of the shuffles goes away when we do the final blend as
9176       // an unpack.
9177       // FIXME: It might be worth trying to detect if the unpack-feeding
9178       // shuffles will both be pshufb, in which case we shouldn't bother with
9179       // this.
9180       if (SDValue Unpack =
9181               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9182         return Unpack;
9183     }
9184
9185     return PSHUFB;
9186   }
9187
9188   // There are special ways we can lower some single-element blends.
9189   if (NumV2Elements == 1)
9190     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9191                                                          Mask, Subtarget, DAG))
9192       return V;
9193
9194   if (SDValue BitBlend =
9195           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9196     return BitBlend;
9197
9198   // Check whether a compaction lowering can be done. This handles shuffles
9199   // which take every Nth element for some even N. See the helper function for
9200   // details.
9201   //
9202   // We special case these as they can be particularly efficiently handled with
9203   // the PACKUSB instruction on x86 and they show up in common patterns of
9204   // rearranging bytes to truncate wide elements.
9205   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9206     // NumEvenDrops is the power of two stride of the elements. Another way of
9207     // thinking about it is that we need to drop the even elements this many
9208     // times to get the original input.
9209     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9210
9211     // First we need to zero all the dropped bytes.
9212     assert(NumEvenDrops <= 3 &&
9213            "No support for dropping even elements more than 3 times.");
9214     // We use the mask type to pick which bytes are preserved based on how many
9215     // elements are dropped.
9216     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9217     SDValue ByteClearMask = DAG.getBitcast(
9218         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9219     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9220     if (!IsSingleInput)
9221       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9222
9223     // Now pack things back together.
9224     V1 = DAG.getBitcast(MVT::v8i16, V1);
9225     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9226     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9227     for (int i = 1; i < NumEvenDrops; ++i) {
9228       Result = DAG.getBitcast(MVT::v8i16, Result);
9229       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9230     }
9231
9232     return Result;
9233   }
9234
9235   // Handle multi-input cases by blending single-input shuffles.
9236   if (NumV2Elements > 0)
9237     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9238                                                       Mask, DAG);
9239
9240   // The fallback path for single-input shuffles widens this into two v8i16
9241   // vectors with unpacks, shuffles those, and then pulls them back together
9242   // with a pack.
9243   SDValue V = V1;
9244
9245   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9246   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9247   for (int i = 0; i < 16; ++i)
9248     if (Mask[i] >= 0)
9249       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9250
9251   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9252
9253   SDValue VLoHalf, VHiHalf;
9254   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9255   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9256   // i16s.
9257   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9258                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9259       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9260                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9261     // Use a mask to drop the high bytes.
9262     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9263     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9264                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9265
9266     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9267     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9268
9269     // Squash the masks to point directly into VLoHalf.
9270     for (int &M : LoBlendMask)
9271       if (M >= 0)
9272         M /= 2;
9273     for (int &M : HiBlendMask)
9274       if (M >= 0)
9275         M /= 2;
9276   } else {
9277     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9278     // VHiHalf so that we can blend them as i16s.
9279     VLoHalf = DAG.getBitcast(
9280         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9281     VHiHalf = DAG.getBitcast(
9282         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9283   }
9284
9285   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9286   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9287
9288   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9289 }
9290
9291 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9292 ///
9293 /// This routine breaks down the specific type of 128-bit shuffle and
9294 /// dispatches to the lowering routines accordingly.
9295 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9296                                         MVT VT, const X86Subtarget *Subtarget,
9297                                         SelectionDAG &DAG) {
9298   switch (VT.SimpleTy) {
9299   case MVT::v2i64:
9300     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9301   case MVT::v2f64:
9302     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9303   case MVT::v4i32:
9304     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9305   case MVT::v4f32:
9306     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9307   case MVT::v8i16:
9308     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9309   case MVT::v16i8:
9310     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9311
9312   default:
9313     llvm_unreachable("Unimplemented!");
9314   }
9315 }
9316
9317 /// \brief Helper function to test whether a shuffle mask could be
9318 /// simplified by widening the elements being shuffled.
9319 ///
9320 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9321 /// leaves it in an unspecified state.
9322 ///
9323 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9324 /// shuffle masks. The latter have the special property of a '-2' representing
9325 /// a zero-ed lane of a vector.
9326 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9327                                     SmallVectorImpl<int> &WidenedMask) {
9328   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9329     // If both elements are undef, its trivial.
9330     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9331       WidenedMask.push_back(SM_SentinelUndef);
9332       continue;
9333     }
9334
9335     // Check for an undef mask and a mask value properly aligned to fit with
9336     // a pair of values. If we find such a case, use the non-undef mask's value.
9337     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9338       WidenedMask.push_back(Mask[i + 1] / 2);
9339       continue;
9340     }
9341     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9342       WidenedMask.push_back(Mask[i] / 2);
9343       continue;
9344     }
9345
9346     // When zeroing, we need to spread the zeroing across both lanes to widen.
9347     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9348       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9349           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9350         WidenedMask.push_back(SM_SentinelZero);
9351         continue;
9352       }
9353       return false;
9354     }
9355
9356     // Finally check if the two mask values are adjacent and aligned with
9357     // a pair.
9358     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9359       WidenedMask.push_back(Mask[i] / 2);
9360       continue;
9361     }
9362
9363     // Otherwise we can't safely widen the elements used in this shuffle.
9364     return false;
9365   }
9366   assert(WidenedMask.size() == Mask.size() / 2 &&
9367          "Incorrect size of mask after widening the elements!");
9368
9369   return true;
9370 }
9371
9372 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9373 ///
9374 /// This routine just extracts two subvectors, shuffles them independently, and
9375 /// then concatenates them back together. This should work effectively with all
9376 /// AVX vector shuffle types.
9377 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9378                                           SDValue V2, ArrayRef<int> Mask,
9379                                           SelectionDAG &DAG) {
9380   assert(VT.getSizeInBits() >= 256 &&
9381          "Only for 256-bit or wider vector shuffles!");
9382   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9383   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9384
9385   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9386   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9387
9388   int NumElements = VT.getVectorNumElements();
9389   int SplitNumElements = NumElements / 2;
9390   MVT ScalarVT = VT.getScalarType();
9391   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9392
9393   // Rather than splitting build-vectors, just build two narrower build
9394   // vectors. This helps shuffling with splats and zeros.
9395   auto SplitVector = [&](SDValue V) {
9396     while (V.getOpcode() == ISD::BITCAST)
9397       V = V->getOperand(0);
9398
9399     MVT OrigVT = V.getSimpleValueType();
9400     int OrigNumElements = OrigVT.getVectorNumElements();
9401     int OrigSplitNumElements = OrigNumElements / 2;
9402     MVT OrigScalarVT = OrigVT.getScalarType();
9403     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9404
9405     SDValue LoV, HiV;
9406
9407     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9408     if (!BV) {
9409       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9410                         DAG.getIntPtrConstant(0, DL));
9411       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9412                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9413     } else {
9414
9415       SmallVector<SDValue, 16> LoOps, HiOps;
9416       for (int i = 0; i < OrigSplitNumElements; ++i) {
9417         LoOps.push_back(BV->getOperand(i));
9418         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9419       }
9420       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9421       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9422     }
9423     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9424                           DAG.getBitcast(SplitVT, HiV));
9425   };
9426
9427   SDValue LoV1, HiV1, LoV2, HiV2;
9428   std::tie(LoV1, HiV1) = SplitVector(V1);
9429   std::tie(LoV2, HiV2) = SplitVector(V2);
9430
9431   // Now create two 4-way blends of these half-width vectors.
9432   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9433     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9434     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9435     for (int i = 0; i < SplitNumElements; ++i) {
9436       int M = HalfMask[i];
9437       if (M >= NumElements) {
9438         if (M >= NumElements + SplitNumElements)
9439           UseHiV2 = true;
9440         else
9441           UseLoV2 = true;
9442         V2BlendMask.push_back(M - NumElements);
9443         V1BlendMask.push_back(-1);
9444         BlendMask.push_back(SplitNumElements + i);
9445       } else if (M >= 0) {
9446         if (M >= SplitNumElements)
9447           UseHiV1 = true;
9448         else
9449           UseLoV1 = true;
9450         V2BlendMask.push_back(-1);
9451         V1BlendMask.push_back(M);
9452         BlendMask.push_back(i);
9453       } else {
9454         V2BlendMask.push_back(-1);
9455         V1BlendMask.push_back(-1);
9456         BlendMask.push_back(-1);
9457       }
9458     }
9459
9460     // Because the lowering happens after all combining takes place, we need to
9461     // manually combine these blend masks as much as possible so that we create
9462     // a minimal number of high-level vector shuffle nodes.
9463
9464     // First try just blending the halves of V1 or V2.
9465     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9466       return DAG.getUNDEF(SplitVT);
9467     if (!UseLoV2 && !UseHiV2)
9468       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9469     if (!UseLoV1 && !UseHiV1)
9470       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9471
9472     SDValue V1Blend, V2Blend;
9473     if (UseLoV1 && UseHiV1) {
9474       V1Blend =
9475         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9476     } else {
9477       // We only use half of V1 so map the usage down into the final blend mask.
9478       V1Blend = UseLoV1 ? LoV1 : HiV1;
9479       for (int i = 0; i < SplitNumElements; ++i)
9480         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9481           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9482     }
9483     if (UseLoV2 && UseHiV2) {
9484       V2Blend =
9485         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9486     } else {
9487       // We only use half of V2 so map the usage down into the final blend mask.
9488       V2Blend = UseLoV2 ? LoV2 : HiV2;
9489       for (int i = 0; i < SplitNumElements; ++i)
9490         if (BlendMask[i] >= SplitNumElements)
9491           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9492     }
9493     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9494   };
9495   SDValue Lo = HalfBlend(LoMask);
9496   SDValue Hi = HalfBlend(HiMask);
9497   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9498 }
9499
9500 /// \brief Either split a vector in halves or decompose the shuffles and the
9501 /// blend.
9502 ///
9503 /// This is provided as a good fallback for many lowerings of non-single-input
9504 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9505 /// between splitting the shuffle into 128-bit components and stitching those
9506 /// back together vs. extracting the single-input shuffles and blending those
9507 /// results.
9508 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9509                                                 SDValue V2, ArrayRef<int> Mask,
9510                                                 SelectionDAG &DAG) {
9511   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9512                                             "lower single-input shuffles as it "
9513                                             "could then recurse on itself.");
9514   int Size = Mask.size();
9515
9516   // If this can be modeled as a broadcast of two elements followed by a blend,
9517   // prefer that lowering. This is especially important because broadcasts can
9518   // often fold with memory operands.
9519   auto DoBothBroadcast = [&] {
9520     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9521     for (int M : Mask)
9522       if (M >= Size) {
9523         if (V2BroadcastIdx == -1)
9524           V2BroadcastIdx = M - Size;
9525         else if (M - Size != V2BroadcastIdx)
9526           return false;
9527       } else if (M >= 0) {
9528         if (V1BroadcastIdx == -1)
9529           V1BroadcastIdx = M;
9530         else if (M != V1BroadcastIdx)
9531           return false;
9532       }
9533     return true;
9534   };
9535   if (DoBothBroadcast())
9536     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9537                                                       DAG);
9538
9539   // If the inputs all stem from a single 128-bit lane of each input, then we
9540   // split them rather than blending because the split will decompose to
9541   // unusually few instructions.
9542   int LaneCount = VT.getSizeInBits() / 128;
9543   int LaneSize = Size / LaneCount;
9544   SmallBitVector LaneInputs[2];
9545   LaneInputs[0].resize(LaneCount, false);
9546   LaneInputs[1].resize(LaneCount, false);
9547   for (int i = 0; i < Size; ++i)
9548     if (Mask[i] >= 0)
9549       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9550   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9551     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9552
9553   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9554   // that the decomposed single-input shuffles don't end up here.
9555   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9556 }
9557
9558 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9559 /// a permutation and blend of those lanes.
9560 ///
9561 /// This essentially blends the out-of-lane inputs to each lane into the lane
9562 /// from a permuted copy of the vector. This lowering strategy results in four
9563 /// instructions in the worst case for a single-input cross lane shuffle which
9564 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9565 /// of. Special cases for each particular shuffle pattern should be handled
9566 /// prior to trying this lowering.
9567 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9568                                                        SDValue V1, SDValue V2,
9569                                                        ArrayRef<int> Mask,
9570                                                        SelectionDAG &DAG) {
9571   // FIXME: This should probably be generalized for 512-bit vectors as well.
9572   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9573   int LaneSize = Mask.size() / 2;
9574
9575   // If there are only inputs from one 128-bit lane, splitting will in fact be
9576   // less expensive. The flags track whether the given lane contains an element
9577   // that crosses to another lane.
9578   bool LaneCrossing[2] = {false, false};
9579   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9580     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9581       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9582   if (!LaneCrossing[0] || !LaneCrossing[1])
9583     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9584
9585   if (isSingleInputShuffleMask(Mask)) {
9586     SmallVector<int, 32> FlippedBlendMask;
9587     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9588       FlippedBlendMask.push_back(
9589           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9590                                   ? Mask[i]
9591                                   : Mask[i] % LaneSize +
9592                                         (i / LaneSize) * LaneSize + Size));
9593
9594     // Flip the vector, and blend the results which should now be in-lane. The
9595     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9596     // 5 for the high source. The value 3 selects the high half of source 2 and
9597     // the value 2 selects the low half of source 2. We only use source 2 to
9598     // allow folding it into a memory operand.
9599     unsigned PERMMask = 3 | 2 << 4;
9600     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9601                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9602     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9603   }
9604
9605   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9606   // will be handled by the above logic and a blend of the results, much like
9607   // other patterns in AVX.
9608   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9609 }
9610
9611 /// \brief Handle lowering 2-lane 128-bit shuffles.
9612 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9613                                         SDValue V2, ArrayRef<int> Mask,
9614                                         const X86Subtarget *Subtarget,
9615                                         SelectionDAG &DAG) {
9616   // TODO: If minimizing size and one of the inputs is a zero vector and the
9617   // the zero vector has only one use, we could use a VPERM2X128 to save the
9618   // instruction bytes needed to explicitly generate the zero vector.
9619
9620   // Blends are faster and handle all the non-lane-crossing cases.
9621   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9622                                                 Subtarget, DAG))
9623     return Blend;
9624
9625   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9626   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9627
9628   // If either input operand is a zero vector, use VPERM2X128 because its mask
9629   // allows us to replace the zero input with an implicit zero.
9630   if (!IsV1Zero && !IsV2Zero) {
9631     // Check for patterns which can be matched with a single insert of a 128-bit
9632     // subvector.
9633     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9634     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9635       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9636                                    VT.getVectorNumElements() / 2);
9637       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9638                                 DAG.getIntPtrConstant(0, DL));
9639       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9640                                 OnlyUsesV1 ? V1 : V2,
9641                                 DAG.getIntPtrConstant(0, DL));
9642       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9643     }
9644   }
9645
9646   // Otherwise form a 128-bit permutation. After accounting for undefs,
9647   // convert the 64-bit shuffle mask selection values into 128-bit
9648   // selection bits by dividing the indexes by 2 and shifting into positions
9649   // defined by a vperm2*128 instruction's immediate control byte.
9650
9651   // The immediate permute control byte looks like this:
9652   //    [1:0] - select 128 bits from sources for low half of destination
9653   //    [2]   - ignore
9654   //    [3]   - zero low half of destination
9655   //    [5:4] - select 128 bits from sources for high half of destination
9656   //    [6]   - ignore
9657   //    [7]   - zero high half of destination
9658
9659   int MaskLO = Mask[0];
9660   if (MaskLO == SM_SentinelUndef)
9661     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9662
9663   int MaskHI = Mask[2];
9664   if (MaskHI == SM_SentinelUndef)
9665     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9666
9667   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9668
9669   // If either input is a zero vector, replace it with an undef input.
9670   // Shuffle mask values <  4 are selecting elements of V1.
9671   // Shuffle mask values >= 4 are selecting elements of V2.
9672   // Adjust each half of the permute mask by clearing the half that was
9673   // selecting the zero vector and setting the zero mask bit.
9674   if (IsV1Zero) {
9675     V1 = DAG.getUNDEF(VT);
9676     if (MaskLO < 4)
9677       PermMask = (PermMask & 0xf0) | 0x08;
9678     if (MaskHI < 4)
9679       PermMask = (PermMask & 0x0f) | 0x80;
9680   }
9681   if (IsV2Zero) {
9682     V2 = DAG.getUNDEF(VT);
9683     if (MaskLO >= 4)
9684       PermMask = (PermMask & 0xf0) | 0x08;
9685     if (MaskHI >= 4)
9686       PermMask = (PermMask & 0x0f) | 0x80;
9687   }
9688
9689   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9690                      DAG.getConstant(PermMask, DL, MVT::i8));
9691 }
9692
9693 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9694 /// shuffling each lane.
9695 ///
9696 /// This will only succeed when the result of fixing the 128-bit lanes results
9697 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9698 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9699 /// the lane crosses early and then use simpler shuffles within each lane.
9700 ///
9701 /// FIXME: It might be worthwhile at some point to support this without
9702 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9703 /// in x86 only floating point has interesting non-repeating shuffles, and even
9704 /// those are still *marginally* more expensive.
9705 static SDValue lowerVectorShuffleByMerging128BitLanes(
9706     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9707     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9708   assert(!isSingleInputShuffleMask(Mask) &&
9709          "This is only useful with multiple inputs.");
9710
9711   int Size = Mask.size();
9712   int LaneSize = 128 / VT.getScalarSizeInBits();
9713   int NumLanes = Size / LaneSize;
9714   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9715
9716   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9717   // check whether the in-128-bit lane shuffles share a repeating pattern.
9718   SmallVector<int, 4> Lanes;
9719   Lanes.resize(NumLanes, -1);
9720   SmallVector<int, 4> InLaneMask;
9721   InLaneMask.resize(LaneSize, -1);
9722   for (int i = 0; i < Size; ++i) {
9723     if (Mask[i] < 0)
9724       continue;
9725
9726     int j = i / LaneSize;
9727
9728     if (Lanes[j] < 0) {
9729       // First entry we've seen for this lane.
9730       Lanes[j] = Mask[i] / LaneSize;
9731     } else if (Lanes[j] != Mask[i] / LaneSize) {
9732       // This doesn't match the lane selected previously!
9733       return SDValue();
9734     }
9735
9736     // Check that within each lane we have a consistent shuffle mask.
9737     int k = i % LaneSize;
9738     if (InLaneMask[k] < 0) {
9739       InLaneMask[k] = Mask[i] % LaneSize;
9740     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9741       // This doesn't fit a repeating in-lane mask.
9742       return SDValue();
9743     }
9744   }
9745
9746   // First shuffle the lanes into place.
9747   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9748                                 VT.getSizeInBits() / 64);
9749   SmallVector<int, 8> LaneMask;
9750   LaneMask.resize(NumLanes * 2, -1);
9751   for (int i = 0; i < NumLanes; ++i)
9752     if (Lanes[i] >= 0) {
9753       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9754       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9755     }
9756
9757   V1 = DAG.getBitcast(LaneVT, V1);
9758   V2 = DAG.getBitcast(LaneVT, V2);
9759   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9760
9761   // Cast it back to the type we actually want.
9762   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9763
9764   // Now do a simple shuffle that isn't lane crossing.
9765   SmallVector<int, 8> NewMask;
9766   NewMask.resize(Size, -1);
9767   for (int i = 0; i < Size; ++i)
9768     if (Mask[i] >= 0)
9769       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9770   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9771          "Must not introduce lane crosses at this point!");
9772
9773   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9774 }
9775
9776 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9777 /// given mask.
9778 ///
9779 /// This returns true if the elements from a particular input are already in the
9780 /// slot required by the given mask and require no permutation.
9781 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9782   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9783   int Size = Mask.size();
9784   for (int i = 0; i < Size; ++i)
9785     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9786       return false;
9787
9788   return true;
9789 }
9790
9791 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9792                                             ArrayRef<int> Mask, SDValue V1,
9793                                             SDValue V2, SelectionDAG &DAG) {
9794
9795   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9796   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9797   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9798   int NumElts = VT.getVectorNumElements();
9799   bool ShufpdMask = true;
9800   bool CommutableMask = true;
9801   unsigned Immediate = 0;
9802   for (int i = 0; i < NumElts; ++i) {
9803     if (Mask[i] < 0)
9804       continue;
9805     int Val = (i & 6) + NumElts * (i & 1);
9806     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9807     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9808       ShufpdMask = false;
9809     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9810       CommutableMask = false;
9811     Immediate |= (Mask[i] % 2) << i;
9812   }
9813   if (ShufpdMask)
9814     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9815                        DAG.getConstant(Immediate, DL, MVT::i8));
9816   if (CommutableMask)
9817     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9818                        DAG.getConstant(Immediate, DL, MVT::i8));
9819   return SDValue();
9820 }
9821
9822 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9823 ///
9824 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9825 /// isn't available.
9826 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9827                                        const X86Subtarget *Subtarget,
9828                                        SelectionDAG &DAG) {
9829   SDLoc DL(Op);
9830   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9831   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9832   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9833   ArrayRef<int> Mask = SVOp->getMask();
9834   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9835
9836   SmallVector<int, 4> WidenedMask;
9837   if (canWidenShuffleElements(Mask, WidenedMask))
9838     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9839                                     DAG);
9840
9841   if (isSingleInputShuffleMask(Mask)) {
9842     // Check for being able to broadcast a single element.
9843     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9844                                                           Mask, Subtarget, DAG))
9845       return Broadcast;
9846
9847     // Use low duplicate instructions for masks that match their pattern.
9848     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9849       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9850
9851     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9852       // Non-half-crossing single input shuffles can be lowerid with an
9853       // interleaved permutation.
9854       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9855                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9856       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9857                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9858     }
9859
9860     // With AVX2 we have direct support for this permutation.
9861     if (Subtarget->hasAVX2())
9862       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9863                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9864
9865     // Otherwise, fall back.
9866     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9867                                                    DAG);
9868   }
9869
9870   // X86 has dedicated unpack instructions that can handle specific blend
9871   // operations: UNPCKH and UNPCKL.
9872   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9873     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9874   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9875     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9876   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9877     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9878   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9879     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9880
9881   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9882                                                 Subtarget, DAG))
9883     return Blend;
9884
9885   // Check if the blend happens to exactly fit that of SHUFPD.
9886   if (SDValue Op =
9887       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9888     return Op;
9889
9890   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9891   // shuffle. However, if we have AVX2 and either inputs are already in place,
9892   // we will be able to shuffle even across lanes the other input in a single
9893   // instruction so skip this pattern.
9894   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9895                                  isShuffleMaskInputInPlace(1, Mask))))
9896     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9897             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9898       return Result;
9899
9900   // If we have AVX2 then we always want to lower with a blend because an v4 we
9901   // can fully permute the elements.
9902   if (Subtarget->hasAVX2())
9903     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9904                                                       Mask, DAG);
9905
9906   // Otherwise fall back on generic lowering.
9907   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9908 }
9909
9910 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9911 ///
9912 /// This routine is only called when we have AVX2 and thus a reasonable
9913 /// instruction set for v4i64 shuffling..
9914 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9915                                        const X86Subtarget *Subtarget,
9916                                        SelectionDAG &DAG) {
9917   SDLoc DL(Op);
9918   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9919   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9920   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9921   ArrayRef<int> Mask = SVOp->getMask();
9922   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9923   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9924
9925   SmallVector<int, 4> WidenedMask;
9926   if (canWidenShuffleElements(Mask, WidenedMask))
9927     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9928                                     DAG);
9929
9930   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9931                                                 Subtarget, DAG))
9932     return Blend;
9933
9934   // Check for being able to broadcast a single element.
9935   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9936                                                         Mask, Subtarget, DAG))
9937     return Broadcast;
9938
9939   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9940   // use lower latency instructions that will operate on both 128-bit lanes.
9941   SmallVector<int, 2> RepeatedMask;
9942   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9943     if (isSingleInputShuffleMask(Mask)) {
9944       int PSHUFDMask[] = {-1, -1, -1, -1};
9945       for (int i = 0; i < 2; ++i)
9946         if (RepeatedMask[i] >= 0) {
9947           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9948           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9949         }
9950       return DAG.getBitcast(
9951           MVT::v4i64,
9952           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9953                       DAG.getBitcast(MVT::v8i32, V1),
9954                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9955     }
9956   }
9957
9958   // AVX2 provides a direct instruction for permuting a single input across
9959   // lanes.
9960   if (isSingleInputShuffleMask(Mask))
9961     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9962                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9963
9964   // Try to use shift instructions.
9965   if (SDValue Shift =
9966           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9967     return Shift;
9968
9969   // Use dedicated unpack instructions for masks that match their pattern.
9970   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9971     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9972   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9973     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9974   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9975     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9976   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9977     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9978
9979   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9980   // shuffle. However, if we have AVX2 and either inputs are already in place,
9981   // we will be able to shuffle even across lanes the other input in a single
9982   // instruction so skip this pattern.
9983   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9984                                  isShuffleMaskInputInPlace(1, Mask))))
9985     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9986             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9987       return Result;
9988
9989   // Otherwise fall back on generic blend lowering.
9990   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9991                                                     Mask, DAG);
9992 }
9993
9994 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9995 ///
9996 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9997 /// isn't available.
9998 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9999                                        const X86Subtarget *Subtarget,
10000                                        SelectionDAG &DAG) {
10001   SDLoc DL(Op);
10002   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10003   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10004   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10005   ArrayRef<int> Mask = SVOp->getMask();
10006   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10007
10008   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10009                                                 Subtarget, DAG))
10010     return Blend;
10011
10012   // Check for being able to broadcast a single element.
10013   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10014                                                         Mask, Subtarget, DAG))
10015     return Broadcast;
10016
10017   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10018   // options to efficiently lower the shuffle.
10019   SmallVector<int, 4> RepeatedMask;
10020   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10021     assert(RepeatedMask.size() == 4 &&
10022            "Repeated masks must be half the mask width!");
10023
10024     // Use even/odd duplicate instructions for masks that match their pattern.
10025     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10026       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10027     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10028       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10029
10030     if (isSingleInputShuffleMask(Mask))
10031       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10032                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10033
10034     // Use dedicated unpack instructions for masks that match their pattern.
10035     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10036       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10037     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10038       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10039     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10040       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10041     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10042       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10043
10044     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10045     // have already handled any direct blends. We also need to squash the
10046     // repeated mask into a simulated v4f32 mask.
10047     for (int i = 0; i < 4; ++i)
10048       if (RepeatedMask[i] >= 8)
10049         RepeatedMask[i] -= 4;
10050     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10051   }
10052
10053   // If we have a single input shuffle with different shuffle patterns in the
10054   // two 128-bit lanes use the variable mask to VPERMILPS.
10055   if (isSingleInputShuffleMask(Mask)) {
10056     SDValue VPermMask[8];
10057     for (int i = 0; i < 8; ++i)
10058       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10059                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10060     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10061       return DAG.getNode(
10062           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10063           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10064
10065     if (Subtarget->hasAVX2())
10066       return DAG.getNode(
10067           X86ISD::VPERMV, DL, MVT::v8f32,
10068           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10069                                                  MVT::v8i32, VPermMask)),
10070           V1);
10071
10072     // Otherwise, fall back.
10073     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10074                                                    DAG);
10075   }
10076
10077   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10078   // shuffle.
10079   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10080           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10081     return Result;
10082
10083   // If we have AVX2 then we always want to lower with a blend because at v8 we
10084   // can fully permute the elements.
10085   if (Subtarget->hasAVX2())
10086     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10087                                                       Mask, DAG);
10088
10089   // Otherwise fall back on generic lowering.
10090   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10091 }
10092
10093 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10094 ///
10095 /// This routine is only called when we have AVX2 and thus a reasonable
10096 /// instruction set for v8i32 shuffling..
10097 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10098                                        const X86Subtarget *Subtarget,
10099                                        SelectionDAG &DAG) {
10100   SDLoc DL(Op);
10101   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10102   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10103   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10104   ArrayRef<int> Mask = SVOp->getMask();
10105   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10106   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10107
10108   // Whenever we can lower this as a zext, that instruction is strictly faster
10109   // than any alternative. It also allows us to fold memory operands into the
10110   // shuffle in many cases.
10111   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10112                                                          Mask, Subtarget, DAG))
10113     return ZExt;
10114
10115   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10116                                                 Subtarget, DAG))
10117     return Blend;
10118
10119   // Check for being able to broadcast a single element.
10120   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10121                                                         Mask, Subtarget, DAG))
10122     return Broadcast;
10123
10124   // If the shuffle mask is repeated in each 128-bit lane we can use more
10125   // efficient instructions that mirror the shuffles across the two 128-bit
10126   // lanes.
10127   SmallVector<int, 4> RepeatedMask;
10128   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10129     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10130     if (isSingleInputShuffleMask(Mask))
10131       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10132                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10133
10134     // Use dedicated unpack instructions for masks that match their pattern.
10135     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10136       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10137     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10138       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10139     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10140       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10141     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10142       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10143   }
10144
10145   // Try to use shift instructions.
10146   if (SDValue Shift =
10147           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10148     return Shift;
10149
10150   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10151           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10152     return Rotate;
10153
10154   // If the shuffle patterns aren't repeated but it is a single input, directly
10155   // generate a cross-lane VPERMD instruction.
10156   if (isSingleInputShuffleMask(Mask)) {
10157     SDValue VPermMask[8];
10158     for (int i = 0; i < 8; ++i)
10159       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10160                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10161     return DAG.getNode(
10162         X86ISD::VPERMV, DL, MVT::v8i32,
10163         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10164   }
10165
10166   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10167   // shuffle.
10168   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10169           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10170     return Result;
10171
10172   // Otherwise fall back on generic blend lowering.
10173   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10174                                                     Mask, DAG);
10175 }
10176
10177 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10178 ///
10179 /// This routine is only called when we have AVX2 and thus a reasonable
10180 /// instruction set for v16i16 shuffling..
10181 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10182                                         const X86Subtarget *Subtarget,
10183                                         SelectionDAG &DAG) {
10184   SDLoc DL(Op);
10185   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10186   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10187   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10188   ArrayRef<int> Mask = SVOp->getMask();
10189   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10190   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10191
10192   // Whenever we can lower this as a zext, that instruction is strictly faster
10193   // than any alternative. It also allows us to fold memory operands into the
10194   // shuffle in many cases.
10195   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10196                                                          Mask, Subtarget, DAG))
10197     return ZExt;
10198
10199   // Check for being able to broadcast a single element.
10200   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10201                                                         Mask, Subtarget, DAG))
10202     return Broadcast;
10203
10204   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10205                                                 Subtarget, DAG))
10206     return Blend;
10207
10208   // Use dedicated unpack instructions for masks that match their pattern.
10209   if (isShuffleEquivalent(V1, V2, Mask,
10210                           {// First 128-bit lane:
10211                            0, 16, 1, 17, 2, 18, 3, 19,
10212                            // Second 128-bit lane:
10213                            8, 24, 9, 25, 10, 26, 11, 27}))
10214     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10215   if (isShuffleEquivalent(V1, V2, Mask,
10216                           {// First 128-bit lane:
10217                            4, 20, 5, 21, 6, 22, 7, 23,
10218                            // Second 128-bit lane:
10219                            12, 28, 13, 29, 14, 30, 15, 31}))
10220     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10221
10222   // Try to use shift instructions.
10223   if (SDValue Shift =
10224           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10225     return Shift;
10226
10227   // Try to use byte rotation instructions.
10228   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10229           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10230     return Rotate;
10231
10232   if (isSingleInputShuffleMask(Mask)) {
10233     // There are no generalized cross-lane shuffle operations available on i16
10234     // element types.
10235     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10236       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10237                                                      Mask, DAG);
10238
10239     SmallVector<int, 8> RepeatedMask;
10240     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10241       // As this is a single-input shuffle, the repeated mask should be
10242       // a strictly valid v8i16 mask that we can pass through to the v8i16
10243       // lowering to handle even the v16 case.
10244       return lowerV8I16GeneralSingleInputVectorShuffle(
10245           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10246     }
10247
10248     SDValue PSHUFBMask[32];
10249     for (int i = 0; i < 16; ++i) {
10250       if (Mask[i] == -1) {
10251         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10252         continue;
10253       }
10254
10255       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10256       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10257       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10258       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10259     }
10260     return DAG.getBitcast(MVT::v16i16,
10261                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10262                                       DAG.getBitcast(MVT::v32i8, V1),
10263                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10264                                                   MVT::v32i8, PSHUFBMask)));
10265   }
10266
10267   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10268   // shuffle.
10269   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10270           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10271     return Result;
10272
10273   // Otherwise fall back on generic lowering.
10274   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10275 }
10276
10277 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10278 ///
10279 /// This routine is only called when we have AVX2 and thus a reasonable
10280 /// instruction set for v32i8 shuffling..
10281 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10282                                        const X86Subtarget *Subtarget,
10283                                        SelectionDAG &DAG) {
10284   SDLoc DL(Op);
10285   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10286   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10287   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10288   ArrayRef<int> Mask = SVOp->getMask();
10289   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10290   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10291
10292   // Whenever we can lower this as a zext, that instruction is strictly faster
10293   // than any alternative. It also allows us to fold memory operands into the
10294   // shuffle in many cases.
10295   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10296                                                          Mask, Subtarget, DAG))
10297     return ZExt;
10298
10299   // Check for being able to broadcast a single element.
10300   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10301                                                         Mask, Subtarget, DAG))
10302     return Broadcast;
10303
10304   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10305                                                 Subtarget, DAG))
10306     return Blend;
10307
10308   // Use dedicated unpack instructions for masks that match their pattern.
10309   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10310   // 256-bit lanes.
10311   if (isShuffleEquivalent(
10312           V1, V2, Mask,
10313           {// First 128-bit lane:
10314            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10315            // Second 128-bit lane:
10316            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10317     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10318   if (isShuffleEquivalent(
10319           V1, V2, Mask,
10320           {// First 128-bit lane:
10321            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10322            // Second 128-bit lane:
10323            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10324     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10325
10326   // Try to use shift instructions.
10327   if (SDValue Shift =
10328           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10329     return Shift;
10330
10331   // Try to use byte rotation instructions.
10332   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10333           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10334     return Rotate;
10335
10336   if (isSingleInputShuffleMask(Mask)) {
10337     // There are no generalized cross-lane shuffle operations available on i8
10338     // element types.
10339     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10340       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10341                                                      Mask, DAG);
10342
10343     SDValue PSHUFBMask[32];
10344     for (int i = 0; i < 32; ++i)
10345       PSHUFBMask[i] =
10346           Mask[i] < 0
10347               ? DAG.getUNDEF(MVT::i8)
10348               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10349                                 MVT::i8);
10350
10351     return DAG.getNode(
10352         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10353         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10354   }
10355
10356   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10357   // shuffle.
10358   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10359           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10360     return Result;
10361
10362   // Otherwise fall back on generic lowering.
10363   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10364 }
10365
10366 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10367 ///
10368 /// This routine either breaks down the specific type of a 256-bit x86 vector
10369 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10370 /// together based on the available instructions.
10371 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10372                                         MVT VT, const X86Subtarget *Subtarget,
10373                                         SelectionDAG &DAG) {
10374   SDLoc DL(Op);
10375   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10376   ArrayRef<int> Mask = SVOp->getMask();
10377
10378   // If we have a single input to the zero element, insert that into V1 if we
10379   // can do so cheaply.
10380   int NumElts = VT.getVectorNumElements();
10381   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10382     return M >= NumElts;
10383   });
10384
10385   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10386     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10387                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10388       return Insertion;
10389
10390   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10391   // check for those subtargets here and avoid much of the subtarget querying in
10392   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10393   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10394   // floating point types there eventually, just immediately cast everything to
10395   // a float and operate entirely in that domain.
10396   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10397     int ElementBits = VT.getScalarSizeInBits();
10398     if (ElementBits < 32)
10399       // No floating point type available, decompose into 128-bit vectors.
10400       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10401
10402     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10403                                 VT.getVectorNumElements());
10404     V1 = DAG.getBitcast(FpVT, V1);
10405     V2 = DAG.getBitcast(FpVT, V2);
10406     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10407   }
10408
10409   switch (VT.SimpleTy) {
10410   case MVT::v4f64:
10411     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10412   case MVT::v4i64:
10413     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10414   case MVT::v8f32:
10415     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10416   case MVT::v8i32:
10417     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10418   case MVT::v16i16:
10419     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10420   case MVT::v32i8:
10421     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10422
10423   default:
10424     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10425   }
10426 }
10427
10428 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10429 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10430                                        const X86Subtarget *Subtarget,
10431                                        SelectionDAG &DAG) {
10432   SDLoc DL(Op);
10433   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10434   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10435   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10436   ArrayRef<int> Mask = SVOp->getMask();
10437   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10438
10439   // X86 has dedicated unpack instructions that can handle specific blend
10440   // operations: UNPCKH and UNPCKL.
10441   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10442     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10443   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10444     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10445
10446   // FIXME: Implement direct support for this type!
10447   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10448 }
10449
10450 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10451 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10452                                        const X86Subtarget *Subtarget,
10453                                        SelectionDAG &DAG) {
10454   SDLoc DL(Op);
10455   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10456   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10457   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10458   ArrayRef<int> Mask = SVOp->getMask();
10459   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10460
10461   // Use dedicated unpack instructions for masks that match their pattern.
10462   if (isShuffleEquivalent(V1, V2, Mask,
10463                           {// First 128-bit lane.
10464                            0, 16, 1, 17, 4, 20, 5, 21,
10465                            // Second 128-bit lane.
10466                            8, 24, 9, 25, 12, 28, 13, 29}))
10467     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10468   if (isShuffleEquivalent(V1, V2, Mask,
10469                           {// First 128-bit lane.
10470                            2, 18, 3, 19, 6, 22, 7, 23,
10471                            // Second 128-bit lane.
10472                            10, 26, 11, 27, 14, 30, 15, 31}))
10473     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10474
10475   // FIXME: Implement direct support for this type!
10476   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10477 }
10478
10479 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10480 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10481                                        const X86Subtarget *Subtarget,
10482                                        SelectionDAG &DAG) {
10483   SDLoc DL(Op);
10484   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10485   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10486   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10487   ArrayRef<int> Mask = SVOp->getMask();
10488   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10489
10490   // X86 has dedicated unpack instructions that can handle specific blend
10491   // operations: UNPCKH and UNPCKL.
10492   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10493     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10494   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10495     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10496
10497   // FIXME: Implement direct support for this type!
10498   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10499 }
10500
10501 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10502 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10503                                        const X86Subtarget *Subtarget,
10504                                        SelectionDAG &DAG) {
10505   SDLoc DL(Op);
10506   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10507   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10508   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10509   ArrayRef<int> Mask = SVOp->getMask();
10510   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10511
10512   // Use dedicated unpack instructions for masks that match their pattern.
10513   if (isShuffleEquivalent(V1, V2, Mask,
10514                           {// First 128-bit lane.
10515                            0, 16, 1, 17, 4, 20, 5, 21,
10516                            // Second 128-bit lane.
10517                            8, 24, 9, 25, 12, 28, 13, 29}))
10518     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10519   if (isShuffleEquivalent(V1, V2, Mask,
10520                           {// First 128-bit lane.
10521                            2, 18, 3, 19, 6, 22, 7, 23,
10522                            // Second 128-bit lane.
10523                            10, 26, 11, 27, 14, 30, 15, 31}))
10524     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10525
10526   // FIXME: Implement direct support for this type!
10527   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10528 }
10529
10530 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10531 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10532                                         const X86Subtarget *Subtarget,
10533                                         SelectionDAG &DAG) {
10534   SDLoc DL(Op);
10535   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10536   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10537   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10538   ArrayRef<int> Mask = SVOp->getMask();
10539   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10540   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10541
10542   // FIXME: Implement direct support for this type!
10543   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10544 }
10545
10546 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10547 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10548                                        const X86Subtarget *Subtarget,
10549                                        SelectionDAG &DAG) {
10550   SDLoc DL(Op);
10551   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10552   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10553   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10554   ArrayRef<int> Mask = SVOp->getMask();
10555   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10556   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10557
10558   // FIXME: Implement direct support for this type!
10559   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10560 }
10561
10562 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10563 ///
10564 /// This routine either breaks down the specific type of a 512-bit x86 vector
10565 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10566 /// together based on the available instructions.
10567 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10568                                         MVT VT, const X86Subtarget *Subtarget,
10569                                         SelectionDAG &DAG) {
10570   SDLoc DL(Op);
10571   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10572   ArrayRef<int> Mask = SVOp->getMask();
10573   assert(Subtarget->hasAVX512() &&
10574          "Cannot lower 512-bit vectors w/ basic ISA!");
10575
10576   // Check for being able to broadcast a single element.
10577   if (SDValue Broadcast =
10578           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10579     return Broadcast;
10580
10581   // Dispatch to each element type for lowering. If we don't have supprot for
10582   // specific element type shuffles at 512 bits, immediately split them and
10583   // lower them. Each lowering routine of a given type is allowed to assume that
10584   // the requisite ISA extensions for that element type are available.
10585   switch (VT.SimpleTy) {
10586   case MVT::v8f64:
10587     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10588   case MVT::v16f32:
10589     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10590   case MVT::v8i64:
10591     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10592   case MVT::v16i32:
10593     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10594   case MVT::v32i16:
10595     if (Subtarget->hasBWI())
10596       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10597     break;
10598   case MVT::v64i8:
10599     if (Subtarget->hasBWI())
10600       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10601     break;
10602
10603   default:
10604     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10605   }
10606
10607   // Otherwise fall back on splitting.
10608   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10609 }
10610
10611 /// \brief Top-level lowering for x86 vector shuffles.
10612 ///
10613 /// This handles decomposition, canonicalization, and lowering of all x86
10614 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10615 /// above in helper routines. The canonicalization attempts to widen shuffles
10616 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10617 /// s.t. only one of the two inputs needs to be tested, etc.
10618 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10619                                   SelectionDAG &DAG) {
10620   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10621   ArrayRef<int> Mask = SVOp->getMask();
10622   SDValue V1 = Op.getOperand(0);
10623   SDValue V2 = Op.getOperand(1);
10624   MVT VT = Op.getSimpleValueType();
10625   int NumElements = VT.getVectorNumElements();
10626   SDLoc dl(Op);
10627
10628   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10629
10630   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10631   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10632   if (V1IsUndef && V2IsUndef)
10633     return DAG.getUNDEF(VT);
10634
10635   // When we create a shuffle node we put the UNDEF node to second operand,
10636   // but in some cases the first operand may be transformed to UNDEF.
10637   // In this case we should just commute the node.
10638   if (V1IsUndef)
10639     return DAG.getCommutedVectorShuffle(*SVOp);
10640
10641   // Check for non-undef masks pointing at an undef vector and make the masks
10642   // undef as well. This makes it easier to match the shuffle based solely on
10643   // the mask.
10644   if (V2IsUndef)
10645     for (int M : Mask)
10646       if (M >= NumElements) {
10647         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10648         for (int &M : NewMask)
10649           if (M >= NumElements)
10650             M = -1;
10651         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10652       }
10653
10654   // We actually see shuffles that are entirely re-arrangements of a set of
10655   // zero inputs. This mostly happens while decomposing complex shuffles into
10656   // simple ones. Directly lower these as a buildvector of zeros.
10657   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10658   if (Zeroable.all())
10659     return getZeroVector(VT, Subtarget, DAG, dl);
10660
10661   // Try to collapse shuffles into using a vector type with fewer elements but
10662   // wider element types. We cap this to not form integers or floating point
10663   // elements wider than 64 bits, but it might be interesting to form i128
10664   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10665   SmallVector<int, 16> WidenedMask;
10666   if (VT.getScalarSizeInBits() < 64 &&
10667       canWidenShuffleElements(Mask, WidenedMask)) {
10668     MVT NewEltVT = VT.isFloatingPoint()
10669                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10670                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10671     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10672     // Make sure that the new vector type is legal. For example, v2f64 isn't
10673     // legal on SSE1.
10674     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10675       V1 = DAG.getBitcast(NewVT, V1);
10676       V2 = DAG.getBitcast(NewVT, V2);
10677       return DAG.getBitcast(
10678           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10679     }
10680   }
10681
10682   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10683   for (int M : SVOp->getMask())
10684     if (M < 0)
10685       ++NumUndefElements;
10686     else if (M < NumElements)
10687       ++NumV1Elements;
10688     else
10689       ++NumV2Elements;
10690
10691   // Commute the shuffle as needed such that more elements come from V1 than
10692   // V2. This allows us to match the shuffle pattern strictly on how many
10693   // elements come from V1 without handling the symmetric cases.
10694   if (NumV2Elements > NumV1Elements)
10695     return DAG.getCommutedVectorShuffle(*SVOp);
10696
10697   // When the number of V1 and V2 elements are the same, try to minimize the
10698   // number of uses of V2 in the low half of the vector. When that is tied,
10699   // ensure that the sum of indices for V1 is equal to or lower than the sum
10700   // indices for V2. When those are equal, try to ensure that the number of odd
10701   // indices for V1 is lower than the number of odd indices for V2.
10702   if (NumV1Elements == NumV2Elements) {
10703     int LowV1Elements = 0, LowV2Elements = 0;
10704     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10705       if (M >= NumElements)
10706         ++LowV2Elements;
10707       else if (M >= 0)
10708         ++LowV1Elements;
10709     if (LowV2Elements > LowV1Elements) {
10710       return DAG.getCommutedVectorShuffle(*SVOp);
10711     } else if (LowV2Elements == LowV1Elements) {
10712       int SumV1Indices = 0, SumV2Indices = 0;
10713       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10714         if (SVOp->getMask()[i] >= NumElements)
10715           SumV2Indices += i;
10716         else if (SVOp->getMask()[i] >= 0)
10717           SumV1Indices += i;
10718       if (SumV2Indices < SumV1Indices) {
10719         return DAG.getCommutedVectorShuffle(*SVOp);
10720       } else if (SumV2Indices == SumV1Indices) {
10721         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10722         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10723           if (SVOp->getMask()[i] >= NumElements)
10724             NumV2OddIndices += i % 2;
10725           else if (SVOp->getMask()[i] >= 0)
10726             NumV1OddIndices += i % 2;
10727         if (NumV2OddIndices < NumV1OddIndices)
10728           return DAG.getCommutedVectorShuffle(*SVOp);
10729       }
10730     }
10731   }
10732
10733   // For each vector width, delegate to a specialized lowering routine.
10734   if (VT.getSizeInBits() == 128)
10735     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10736
10737   if (VT.getSizeInBits() == 256)
10738     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10739
10740   // Force AVX-512 vectors to be scalarized for now.
10741   // FIXME: Implement AVX-512 support!
10742   if (VT.getSizeInBits() == 512)
10743     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10744
10745   llvm_unreachable("Unimplemented!");
10746 }
10747
10748 // This function assumes its argument is a BUILD_VECTOR of constants or
10749 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10750 // true.
10751 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10752                                     unsigned &MaskValue) {
10753   MaskValue = 0;
10754   unsigned NumElems = BuildVector->getNumOperands();
10755   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10756   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10757   unsigned NumElemsInLane = NumElems / NumLanes;
10758
10759   // Blend for v16i16 should be symmetric for the both lanes.
10760   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10761     SDValue EltCond = BuildVector->getOperand(i);
10762     SDValue SndLaneEltCond =
10763         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10764
10765     int Lane1Cond = -1, Lane2Cond = -1;
10766     if (isa<ConstantSDNode>(EltCond))
10767       Lane1Cond = !isZero(EltCond);
10768     if (isa<ConstantSDNode>(SndLaneEltCond))
10769       Lane2Cond = !isZero(SndLaneEltCond);
10770
10771     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10772       // Lane1Cond != 0, means we want the first argument.
10773       // Lane1Cond == 0, means we want the second argument.
10774       // The encoding of this argument is 0 for the first argument, 1
10775       // for the second. Therefore, invert the condition.
10776       MaskValue |= !Lane1Cond << i;
10777     else if (Lane1Cond < 0)
10778       MaskValue |= !Lane2Cond << i;
10779     else
10780       return false;
10781   }
10782   return true;
10783 }
10784
10785 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10786 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10787                                            const X86Subtarget *Subtarget,
10788                                            SelectionDAG &DAG) {
10789   SDValue Cond = Op.getOperand(0);
10790   SDValue LHS = Op.getOperand(1);
10791   SDValue RHS = Op.getOperand(2);
10792   SDLoc dl(Op);
10793   MVT VT = Op.getSimpleValueType();
10794
10795   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10796     return SDValue();
10797   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10798
10799   // Only non-legal VSELECTs reach this lowering, convert those into generic
10800   // shuffles and re-use the shuffle lowering path for blends.
10801   SmallVector<int, 32> Mask;
10802   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10803     SDValue CondElt = CondBV->getOperand(i);
10804     Mask.push_back(
10805         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10806   }
10807   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10808 }
10809
10810 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10811   // A vselect where all conditions and data are constants can be optimized into
10812   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10813   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10814       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10815       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10816     return SDValue();
10817
10818   // Try to lower this to a blend-style vector shuffle. This can handle all
10819   // constant condition cases.
10820   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10821     return BlendOp;
10822
10823   // Variable blends are only legal from SSE4.1 onward.
10824   if (!Subtarget->hasSSE41())
10825     return SDValue();
10826
10827   // Only some types will be legal on some subtargets. If we can emit a legal
10828   // VSELECT-matching blend, return Op, and but if we need to expand, return
10829   // a null value.
10830   switch (Op.getSimpleValueType().SimpleTy) {
10831   default:
10832     // Most of the vector types have blends past SSE4.1.
10833     return Op;
10834
10835   case MVT::v32i8:
10836     // The byte blends for AVX vectors were introduced only in AVX2.
10837     if (Subtarget->hasAVX2())
10838       return Op;
10839
10840     return SDValue();
10841
10842   case MVT::v8i16:
10843   case MVT::v16i16:
10844     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10845     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10846       return Op;
10847
10848     // FIXME: We should custom lower this by fixing the condition and using i8
10849     // blends.
10850     return SDValue();
10851   }
10852 }
10853
10854 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10855   MVT VT = Op.getSimpleValueType();
10856   SDLoc dl(Op);
10857
10858   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10859     return SDValue();
10860
10861   if (VT.getSizeInBits() == 8) {
10862     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10863                                   Op.getOperand(0), Op.getOperand(1));
10864     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10865                                   DAG.getValueType(VT));
10866     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10867   }
10868
10869   if (VT.getSizeInBits() == 16) {
10870     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10871     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10872     if (Idx == 0)
10873       return DAG.getNode(
10874           ISD::TRUNCATE, dl, MVT::i16,
10875           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10876                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10877                       Op.getOperand(1)));
10878     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10879                                   Op.getOperand(0), Op.getOperand(1));
10880     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10881                                   DAG.getValueType(VT));
10882     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10883   }
10884
10885   if (VT == MVT::f32) {
10886     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10887     // the result back to FR32 register. It's only worth matching if the
10888     // result has a single use which is a store or a bitcast to i32.  And in
10889     // the case of a store, it's not worth it if the index is a constant 0,
10890     // because a MOVSSmr can be used instead, which is smaller and faster.
10891     if (!Op.hasOneUse())
10892       return SDValue();
10893     SDNode *User = *Op.getNode()->use_begin();
10894     if ((User->getOpcode() != ISD::STORE ||
10895          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10896           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10897         (User->getOpcode() != ISD::BITCAST ||
10898          User->getValueType(0) != MVT::i32))
10899       return SDValue();
10900     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10901                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10902                                   Op.getOperand(1));
10903     return DAG.getBitcast(MVT::f32, Extract);
10904   }
10905
10906   if (VT == MVT::i32 || VT == MVT::i64) {
10907     // ExtractPS/pextrq works with constant index.
10908     if (isa<ConstantSDNode>(Op.getOperand(1)))
10909       return Op;
10910   }
10911   return SDValue();
10912 }
10913
10914 /// Extract one bit from mask vector, like v16i1 or v8i1.
10915 /// AVX-512 feature.
10916 SDValue
10917 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10918   SDValue Vec = Op.getOperand(0);
10919   SDLoc dl(Vec);
10920   MVT VecVT = Vec.getSimpleValueType();
10921   SDValue Idx = Op.getOperand(1);
10922   MVT EltVT = Op.getSimpleValueType();
10923
10924   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10925   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10926          "Unexpected vector type in ExtractBitFromMaskVector");
10927
10928   // variable index can't be handled in mask registers,
10929   // extend vector to VR512
10930   if (!isa<ConstantSDNode>(Idx)) {
10931     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10932     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10933     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10934                               ExtVT.getVectorElementType(), Ext, Idx);
10935     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10936   }
10937
10938   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10939   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10940   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10941     rc = getRegClassFor(MVT::v16i1);
10942   unsigned MaxSift = rc->getSize()*8 - 1;
10943   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10944                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10945   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10946                     DAG.getConstant(MaxSift, dl, MVT::i8));
10947   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10948                        DAG.getIntPtrConstant(0, dl));
10949 }
10950
10951 SDValue
10952 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10953                                            SelectionDAG &DAG) const {
10954   SDLoc dl(Op);
10955   SDValue Vec = Op.getOperand(0);
10956   MVT VecVT = Vec.getSimpleValueType();
10957   SDValue Idx = Op.getOperand(1);
10958
10959   if (Op.getSimpleValueType() == MVT::i1)
10960     return ExtractBitFromMaskVector(Op, DAG);
10961
10962   if (!isa<ConstantSDNode>(Idx)) {
10963     if (VecVT.is512BitVector() ||
10964         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10965          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10966
10967       MVT MaskEltVT =
10968         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10969       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10970                                     MaskEltVT.getSizeInBits());
10971
10972       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10973       auto PtrVT = getPointerTy(DAG.getDataLayout());
10974       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10975                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10976                                  DAG.getConstant(0, dl, PtrVT));
10977       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10978       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10979                          DAG.getConstant(0, dl, PtrVT));
10980     }
10981     return SDValue();
10982   }
10983
10984   // If this is a 256-bit vector result, first extract the 128-bit vector and
10985   // then extract the element from the 128-bit vector.
10986   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10987
10988     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10989     // Get the 128-bit vector.
10990     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10991     MVT EltVT = VecVT.getVectorElementType();
10992
10993     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10994
10995     //if (IdxVal >= NumElems/2)
10996     //  IdxVal -= NumElems/2;
10997     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10998     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10999                        DAG.getConstant(IdxVal, dl, MVT::i32));
11000   }
11001
11002   assert(VecVT.is128BitVector() && "Unexpected vector length");
11003
11004   if (Subtarget->hasSSE41())
11005     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11006       return Res;
11007
11008   MVT VT = Op.getSimpleValueType();
11009   // TODO: handle v16i8.
11010   if (VT.getSizeInBits() == 16) {
11011     SDValue Vec = Op.getOperand(0);
11012     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11013     if (Idx == 0)
11014       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11015                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11016                                      DAG.getBitcast(MVT::v4i32, Vec),
11017                                      Op.getOperand(1)));
11018     // Transform it so it match pextrw which produces a 32-bit result.
11019     MVT EltVT = MVT::i32;
11020     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11021                                   Op.getOperand(0), Op.getOperand(1));
11022     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11023                                   DAG.getValueType(VT));
11024     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11025   }
11026
11027   if (VT.getSizeInBits() == 32) {
11028     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11029     if (Idx == 0)
11030       return Op;
11031
11032     // SHUFPS the element to the lowest double word, then movss.
11033     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11034     MVT VVT = Op.getOperand(0).getSimpleValueType();
11035     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11036                                        DAG.getUNDEF(VVT), Mask);
11037     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11038                        DAG.getIntPtrConstant(0, dl));
11039   }
11040
11041   if (VT.getSizeInBits() == 64) {
11042     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11043     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11044     //        to match extract_elt for f64.
11045     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11046     if (Idx == 0)
11047       return Op;
11048
11049     // UNPCKHPD the element to the lowest double word, then movsd.
11050     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11051     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11052     int Mask[2] = { 1, -1 };
11053     MVT VVT = Op.getOperand(0).getSimpleValueType();
11054     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11055                                        DAG.getUNDEF(VVT), Mask);
11056     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11057                        DAG.getIntPtrConstant(0, dl));
11058   }
11059
11060   return SDValue();
11061 }
11062
11063 /// Insert one bit to mask vector, like v16i1 or v8i1.
11064 /// AVX-512 feature.
11065 SDValue
11066 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11067   SDLoc dl(Op);
11068   SDValue Vec = Op.getOperand(0);
11069   SDValue Elt = Op.getOperand(1);
11070   SDValue Idx = Op.getOperand(2);
11071   MVT VecVT = Vec.getSimpleValueType();
11072
11073   if (!isa<ConstantSDNode>(Idx)) {
11074     // Non constant index. Extend source and destination,
11075     // insert element and then truncate the result.
11076     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11077     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11078     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11079       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11080       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11081     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11082   }
11083
11084   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11085   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11086   if (IdxVal)
11087     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11088                            DAG.getConstant(IdxVal, dl, MVT::i8));
11089   if (Vec.getOpcode() == ISD::UNDEF)
11090     return EltInVec;
11091   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11092 }
11093
11094 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11095                                                   SelectionDAG &DAG) const {
11096   MVT VT = Op.getSimpleValueType();
11097   MVT EltVT = VT.getVectorElementType();
11098
11099   if (EltVT == MVT::i1)
11100     return InsertBitToMaskVector(Op, DAG);
11101
11102   SDLoc dl(Op);
11103   SDValue N0 = Op.getOperand(0);
11104   SDValue N1 = Op.getOperand(1);
11105   SDValue N2 = Op.getOperand(2);
11106   if (!isa<ConstantSDNode>(N2))
11107     return SDValue();
11108   auto *N2C = cast<ConstantSDNode>(N2);
11109   unsigned IdxVal = N2C->getZExtValue();
11110
11111   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11112   // into that, and then insert the subvector back into the result.
11113   if (VT.is256BitVector() || VT.is512BitVector()) {
11114     // With a 256-bit vector, we can insert into the zero element efficiently
11115     // using a blend if we have AVX or AVX2 and the right data type.
11116     if (VT.is256BitVector() && IdxVal == 0) {
11117       // TODO: It is worthwhile to cast integer to floating point and back
11118       // and incur a domain crossing penalty if that's what we'll end up
11119       // doing anyway after extracting to a 128-bit vector.
11120       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11121           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11122         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11123         N2 = DAG.getIntPtrConstant(1, dl);
11124         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11125       }
11126     }
11127
11128     // Get the desired 128-bit vector chunk.
11129     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11130
11131     // Insert the element into the desired chunk.
11132     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11133     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11134
11135     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11136                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11137
11138     // Insert the changed part back into the bigger vector
11139     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11140   }
11141   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11142
11143   if (Subtarget->hasSSE41()) {
11144     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11145       unsigned Opc;
11146       if (VT == MVT::v8i16) {
11147         Opc = X86ISD::PINSRW;
11148       } else {
11149         assert(VT == MVT::v16i8);
11150         Opc = X86ISD::PINSRB;
11151       }
11152
11153       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11154       // argument.
11155       if (N1.getValueType() != MVT::i32)
11156         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11157       if (N2.getValueType() != MVT::i32)
11158         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11159       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11160     }
11161
11162     if (EltVT == MVT::f32) {
11163       // Bits [7:6] of the constant are the source select. This will always be
11164       //   zero here. The DAG Combiner may combine an extract_elt index into
11165       //   these bits. For example (insert (extract, 3), 2) could be matched by
11166       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11167       // Bits [5:4] of the constant are the destination select. This is the
11168       //   value of the incoming immediate.
11169       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11170       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11171
11172       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11173       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11174         // If this is an insertion of 32-bits into the low 32-bits of
11175         // a vector, we prefer to generate a blend with immediate rather
11176         // than an insertps. Blends are simpler operations in hardware and so
11177         // will always have equal or better performance than insertps.
11178         // But if optimizing for size and there's a load folding opportunity,
11179         // generate insertps because blendps does not have a 32-bit memory
11180         // operand form.
11181         N2 = DAG.getIntPtrConstant(1, dl);
11182         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11183         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11184       }
11185       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11186       // Create this as a scalar to vector..
11187       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11188       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11189     }
11190
11191     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11192       // PINSR* works with constant index.
11193       return Op;
11194     }
11195   }
11196
11197   if (EltVT == MVT::i8)
11198     return SDValue();
11199
11200   if (EltVT.getSizeInBits() == 16) {
11201     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11202     // as its second argument.
11203     if (N1.getValueType() != MVT::i32)
11204       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11205     if (N2.getValueType() != MVT::i32)
11206       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11207     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11208   }
11209   return SDValue();
11210 }
11211
11212 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11213   SDLoc dl(Op);
11214   MVT OpVT = Op.getSimpleValueType();
11215
11216   // If this is a 256-bit vector result, first insert into a 128-bit
11217   // vector and then insert into the 256-bit vector.
11218   if (!OpVT.is128BitVector()) {
11219     // Insert into a 128-bit vector.
11220     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11221     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11222                                  OpVT.getVectorNumElements() / SizeFactor);
11223
11224     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11225
11226     // Insert the 128-bit vector.
11227     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11228   }
11229
11230   if (OpVT == MVT::v1i64 &&
11231       Op.getOperand(0).getValueType() == MVT::i64)
11232     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11233
11234   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11235   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11236   return DAG.getBitcast(
11237       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11238 }
11239
11240 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11241 // a simple subregister reference or explicit instructions to grab
11242 // upper bits of a vector.
11243 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11244                                       SelectionDAG &DAG) {
11245   SDLoc dl(Op);
11246   SDValue In =  Op.getOperand(0);
11247   SDValue Idx = Op.getOperand(1);
11248   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11249   MVT ResVT   = Op.getSimpleValueType();
11250   MVT InVT    = In.getSimpleValueType();
11251
11252   if (Subtarget->hasFp256()) {
11253     if (ResVT.is128BitVector() &&
11254         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11255         isa<ConstantSDNode>(Idx)) {
11256       return Extract128BitVector(In, IdxVal, DAG, dl);
11257     }
11258     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11259         isa<ConstantSDNode>(Idx)) {
11260       return Extract256BitVector(In, IdxVal, DAG, dl);
11261     }
11262   }
11263   return SDValue();
11264 }
11265
11266 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11267 // simple superregister reference or explicit instructions to insert
11268 // the upper bits of a vector.
11269 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11270                                      SelectionDAG &DAG) {
11271   if (!Subtarget->hasAVX())
11272     return SDValue();
11273
11274   SDLoc dl(Op);
11275   SDValue Vec = Op.getOperand(0);
11276   SDValue SubVec = Op.getOperand(1);
11277   SDValue Idx = Op.getOperand(2);
11278
11279   if (!isa<ConstantSDNode>(Idx))
11280     return SDValue();
11281
11282   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11283   MVT OpVT = Op.getSimpleValueType();
11284   MVT SubVecVT = SubVec.getSimpleValueType();
11285
11286   // Fold two 16-byte subvector loads into one 32-byte load:
11287   // (insert_subvector (insert_subvector undef, (load addr), 0),
11288   //                   (load addr + 16), Elts/2)
11289   // --> load32 addr
11290   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11291       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11292       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11293     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11294     if (Idx2 && Idx2->getZExtValue() == 0) {
11295       SDValue SubVec2 = Vec.getOperand(1);
11296       // If needed, look through a bitcast to get to the load.
11297       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11298         SubVec2 = SubVec2.getOperand(0);
11299       
11300       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11301         bool Fast;
11302         unsigned Alignment = FirstLd->getAlignment();
11303         unsigned AS = FirstLd->getAddressSpace();
11304         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11305         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11306                                     OpVT, AS, Alignment, &Fast) && Fast) {
11307           SDValue Ops[] = { SubVec2, SubVec };
11308           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11309             return Ld;
11310         }
11311       }
11312     }
11313   }
11314
11315   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11316       SubVecVT.is128BitVector())
11317     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11318
11319   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11320     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11321
11322   if (OpVT.getVectorElementType() == MVT::i1) {
11323     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11324       return Op;
11325     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11326     SDValue Undef = DAG.getUNDEF(OpVT);
11327     unsigned NumElems = OpVT.getVectorNumElements();
11328     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11329
11330     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11331       // Zero upper bits of the Vec
11332       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11333       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11334
11335       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11336                                  SubVec, ZeroIdx);
11337       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11338       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11339     }
11340     if (IdxVal == 0) {
11341       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11342                                  SubVec, ZeroIdx);
11343       // Zero upper bits of the Vec2
11344       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11345       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11346       // Zero lower bits of the Vec
11347       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11348       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11349       // Merge them together
11350       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11351     }
11352   }
11353   return SDValue();
11354 }
11355
11356 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11357 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11358 // one of the above mentioned nodes. It has to be wrapped because otherwise
11359 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11360 // be used to form addressing mode. These wrapped nodes will be selected
11361 // into MOV32ri.
11362 SDValue
11363 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11364   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11365
11366   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11367   // global base reg.
11368   unsigned char OpFlag = 0;
11369   unsigned WrapperKind = X86ISD::Wrapper;
11370   CodeModel::Model M = DAG.getTarget().getCodeModel();
11371
11372   if (Subtarget->isPICStyleRIPRel() &&
11373       (M == CodeModel::Small || M == CodeModel::Kernel))
11374     WrapperKind = X86ISD::WrapperRIP;
11375   else if (Subtarget->isPICStyleGOT())
11376     OpFlag = X86II::MO_GOTOFF;
11377   else if (Subtarget->isPICStyleStubPIC())
11378     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11379
11380   auto PtrVT = getPointerTy(DAG.getDataLayout());
11381   SDValue Result = DAG.getTargetConstantPool(
11382       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11383   SDLoc DL(CP);
11384   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11385   // With PIC, the address is actually $g + Offset.
11386   if (OpFlag) {
11387     Result =
11388         DAG.getNode(ISD::ADD, DL, PtrVT,
11389                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11390   }
11391
11392   return Result;
11393 }
11394
11395 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11396   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11397
11398   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11399   // global base reg.
11400   unsigned char OpFlag = 0;
11401   unsigned WrapperKind = X86ISD::Wrapper;
11402   CodeModel::Model M = DAG.getTarget().getCodeModel();
11403
11404   if (Subtarget->isPICStyleRIPRel() &&
11405       (M == CodeModel::Small || M == CodeModel::Kernel))
11406     WrapperKind = X86ISD::WrapperRIP;
11407   else if (Subtarget->isPICStyleGOT())
11408     OpFlag = X86II::MO_GOTOFF;
11409   else if (Subtarget->isPICStyleStubPIC())
11410     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11411
11412   auto PtrVT = getPointerTy(DAG.getDataLayout());
11413   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11414   SDLoc DL(JT);
11415   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11416
11417   // With PIC, the address is actually $g + Offset.
11418   if (OpFlag)
11419     Result =
11420         DAG.getNode(ISD::ADD, DL, PtrVT,
11421                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11422
11423   return Result;
11424 }
11425
11426 SDValue
11427 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11428   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11429
11430   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11431   // global base reg.
11432   unsigned char OpFlag = 0;
11433   unsigned WrapperKind = X86ISD::Wrapper;
11434   CodeModel::Model M = DAG.getTarget().getCodeModel();
11435
11436   if (Subtarget->isPICStyleRIPRel() &&
11437       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11438     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11439       OpFlag = X86II::MO_GOTPCREL;
11440     WrapperKind = X86ISD::WrapperRIP;
11441   } else if (Subtarget->isPICStyleGOT()) {
11442     OpFlag = X86II::MO_GOT;
11443   } else if (Subtarget->isPICStyleStubPIC()) {
11444     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11445   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11446     OpFlag = X86II::MO_DARWIN_NONLAZY;
11447   }
11448
11449   auto PtrVT = getPointerTy(DAG.getDataLayout());
11450   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11451
11452   SDLoc DL(Op);
11453   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11454
11455   // With PIC, the address is actually $g + Offset.
11456   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11457       !Subtarget->is64Bit()) {
11458     Result =
11459         DAG.getNode(ISD::ADD, DL, PtrVT,
11460                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11461   }
11462
11463   // For symbols that require a load from a stub to get the address, emit the
11464   // load.
11465   if (isGlobalStubReference(OpFlag))
11466     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11467                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11468                          false, false, false, 0);
11469
11470   return Result;
11471 }
11472
11473 SDValue
11474 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11475   // Create the TargetBlockAddressAddress node.
11476   unsigned char OpFlags =
11477     Subtarget->ClassifyBlockAddressReference();
11478   CodeModel::Model M = DAG.getTarget().getCodeModel();
11479   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11480   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11481   SDLoc dl(Op);
11482   auto PtrVT = getPointerTy(DAG.getDataLayout());
11483   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11484
11485   if (Subtarget->isPICStyleRIPRel() &&
11486       (M == CodeModel::Small || M == CodeModel::Kernel))
11487     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11488   else
11489     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11490
11491   // With PIC, the address is actually $g + Offset.
11492   if (isGlobalRelativeToPICBase(OpFlags)) {
11493     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11494                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11495   }
11496
11497   return Result;
11498 }
11499
11500 SDValue
11501 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11502                                       int64_t Offset, SelectionDAG &DAG) const {
11503   // Create the TargetGlobalAddress node, folding in the constant
11504   // offset if it is legal.
11505   unsigned char OpFlags =
11506       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11507   CodeModel::Model M = DAG.getTarget().getCodeModel();
11508   auto PtrVT = getPointerTy(DAG.getDataLayout());
11509   SDValue Result;
11510   if (OpFlags == X86II::MO_NO_FLAG &&
11511       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11512     // A direct static reference to a global.
11513     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11514     Offset = 0;
11515   } else {
11516     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11517   }
11518
11519   if (Subtarget->isPICStyleRIPRel() &&
11520       (M == CodeModel::Small || M == CodeModel::Kernel))
11521     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11522   else
11523     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11524
11525   // With PIC, the address is actually $g + Offset.
11526   if (isGlobalRelativeToPICBase(OpFlags)) {
11527     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11528                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11529   }
11530
11531   // For globals that require a load from a stub to get the address, emit the
11532   // load.
11533   if (isGlobalStubReference(OpFlags))
11534     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11535                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11536                          false, false, false, 0);
11537
11538   // If there was a non-zero offset that we didn't fold, create an explicit
11539   // addition for it.
11540   if (Offset != 0)
11541     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11542                          DAG.getConstant(Offset, dl, PtrVT));
11543
11544   return Result;
11545 }
11546
11547 SDValue
11548 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11549   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11550   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11551   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11552 }
11553
11554 static SDValue
11555 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11556            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11557            unsigned char OperandFlags, bool LocalDynamic = false) {
11558   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11559   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11560   SDLoc dl(GA);
11561   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11562                                            GA->getValueType(0),
11563                                            GA->getOffset(),
11564                                            OperandFlags);
11565
11566   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11567                                            : X86ISD::TLSADDR;
11568
11569   if (InFlag) {
11570     SDValue Ops[] = { Chain,  TGA, *InFlag };
11571     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11572   } else {
11573     SDValue Ops[]  = { Chain, TGA };
11574     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11575   }
11576
11577   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11578   MFI->setAdjustsStack(true);
11579   MFI->setHasCalls(true);
11580
11581   SDValue Flag = Chain.getValue(1);
11582   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11583 }
11584
11585 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11586 static SDValue
11587 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11588                                 const EVT PtrVT) {
11589   SDValue InFlag;
11590   SDLoc dl(GA);  // ? function entry point might be better
11591   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11592                                    DAG.getNode(X86ISD::GlobalBaseReg,
11593                                                SDLoc(), PtrVT), InFlag);
11594   InFlag = Chain.getValue(1);
11595
11596   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11597 }
11598
11599 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11600 static SDValue
11601 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11602                                 const EVT PtrVT) {
11603   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11604                     X86::RAX, X86II::MO_TLSGD);
11605 }
11606
11607 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11608                                            SelectionDAG &DAG,
11609                                            const EVT PtrVT,
11610                                            bool is64Bit) {
11611   SDLoc dl(GA);
11612
11613   // Get the start address of the TLS block for this module.
11614   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11615       .getInfo<X86MachineFunctionInfo>();
11616   MFI->incNumLocalDynamicTLSAccesses();
11617
11618   SDValue Base;
11619   if (is64Bit) {
11620     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11621                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11622   } else {
11623     SDValue InFlag;
11624     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11625         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11626     InFlag = Chain.getValue(1);
11627     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11628                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11629   }
11630
11631   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11632   // of Base.
11633
11634   // Build x@dtpoff.
11635   unsigned char OperandFlags = X86II::MO_DTPOFF;
11636   unsigned WrapperKind = X86ISD::Wrapper;
11637   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11638                                            GA->getValueType(0),
11639                                            GA->getOffset(), OperandFlags);
11640   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11641
11642   // Add x@dtpoff with the base.
11643   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11644 }
11645
11646 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11647 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11648                                    const EVT PtrVT, TLSModel::Model model,
11649                                    bool is64Bit, bool isPIC) {
11650   SDLoc dl(GA);
11651
11652   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11653   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11654                                                          is64Bit ? 257 : 256));
11655
11656   SDValue ThreadPointer =
11657       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11658                   MachinePointerInfo(Ptr), false, false, false, 0);
11659
11660   unsigned char OperandFlags = 0;
11661   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11662   // initialexec.
11663   unsigned WrapperKind = X86ISD::Wrapper;
11664   if (model == TLSModel::LocalExec) {
11665     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11666   } else if (model == TLSModel::InitialExec) {
11667     if (is64Bit) {
11668       OperandFlags = X86II::MO_GOTTPOFF;
11669       WrapperKind = X86ISD::WrapperRIP;
11670     } else {
11671       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11672     }
11673   } else {
11674     llvm_unreachable("Unexpected model");
11675   }
11676
11677   // emit "addl x@ntpoff,%eax" (local exec)
11678   // or "addl x@indntpoff,%eax" (initial exec)
11679   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11680   SDValue TGA =
11681       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11682                                  GA->getOffset(), OperandFlags);
11683   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11684
11685   if (model == TLSModel::InitialExec) {
11686     if (isPIC && !is64Bit) {
11687       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11688                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11689                            Offset);
11690     }
11691
11692     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11693                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11694                          false, false, false, 0);
11695   }
11696
11697   // The address of the thread local variable is the add of the thread
11698   // pointer with the offset of the variable.
11699   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11700 }
11701
11702 SDValue
11703 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11704
11705   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11706   const GlobalValue *GV = GA->getGlobal();
11707   auto PtrVT = getPointerTy(DAG.getDataLayout());
11708
11709   if (Subtarget->isTargetELF()) {
11710     if (DAG.getTarget().Options.EmulatedTLS)
11711       return LowerToTLSEmulatedModel(GA, DAG);
11712     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11713     switch (model) {
11714       case TLSModel::GeneralDynamic:
11715         if (Subtarget->is64Bit())
11716           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11717         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11718       case TLSModel::LocalDynamic:
11719         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11720                                            Subtarget->is64Bit());
11721       case TLSModel::InitialExec:
11722       case TLSModel::LocalExec:
11723         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11724                                    DAG.getTarget().getRelocationModel() ==
11725                                        Reloc::PIC_);
11726     }
11727     llvm_unreachable("Unknown TLS model.");
11728   }
11729
11730   if (Subtarget->isTargetDarwin()) {
11731     // Darwin only has one model of TLS.  Lower to that.
11732     unsigned char OpFlag = 0;
11733     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11734                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11735
11736     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11737     // global base reg.
11738     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11739                  !Subtarget->is64Bit();
11740     if (PIC32)
11741       OpFlag = X86II::MO_TLVP_PIC_BASE;
11742     else
11743       OpFlag = X86II::MO_TLVP;
11744     SDLoc DL(Op);
11745     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11746                                                 GA->getValueType(0),
11747                                                 GA->getOffset(), OpFlag);
11748     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11749
11750     // With PIC32, the address is actually $g + Offset.
11751     if (PIC32)
11752       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11753                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11754                            Offset);
11755
11756     // Lowering the machine isd will make sure everything is in the right
11757     // location.
11758     SDValue Chain = DAG.getEntryNode();
11759     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11760     SDValue Args[] = { Chain, Offset };
11761     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11762
11763     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11764     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11765     MFI->setAdjustsStack(true);
11766
11767     // And our return value (tls address) is in the standard call return value
11768     // location.
11769     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11770     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11771   }
11772
11773   if (Subtarget->isTargetKnownWindowsMSVC() ||
11774       Subtarget->isTargetWindowsGNU()) {
11775     // Just use the implicit TLS architecture
11776     // Need to generate someting similar to:
11777     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11778     //                                  ; from TEB
11779     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11780     //   mov     rcx, qword [rdx+rcx*8]
11781     //   mov     eax, .tls$:tlsvar
11782     //   [rax+rcx] contains the address
11783     // Windows 64bit: gs:0x58
11784     // Windows 32bit: fs:__tls_array
11785
11786     SDLoc dl(GA);
11787     SDValue Chain = DAG.getEntryNode();
11788
11789     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11790     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11791     // use its literal value of 0x2C.
11792     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11793                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11794                                                              256)
11795                                         : Type::getInt32PtrTy(*DAG.getContext(),
11796                                                               257));
11797
11798     SDValue TlsArray = Subtarget->is64Bit()
11799                            ? DAG.getIntPtrConstant(0x58, dl)
11800                            : (Subtarget->isTargetWindowsGNU()
11801                                   ? DAG.getIntPtrConstant(0x2C, dl)
11802                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
11803
11804     SDValue ThreadPointer =
11805         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11806                     false, false, 0);
11807
11808     SDValue res;
11809     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11810       res = ThreadPointer;
11811     } else {
11812       // Load the _tls_index variable
11813       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11814       if (Subtarget->is64Bit())
11815         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11816                              MachinePointerInfo(), MVT::i32, false, false,
11817                              false, 0);
11818       else
11819         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11820                           false, false, 0);
11821
11822       auto &DL = DAG.getDataLayout();
11823       SDValue Scale =
11824           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11825       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11826
11827       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11828     }
11829
11830     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11831                       false, 0);
11832
11833     // Get the offset of start of .tls section
11834     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11835                                              GA->getValueType(0),
11836                                              GA->getOffset(), X86II::MO_SECREL);
11837     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11838
11839     // The address of the thread local variable is the add of the thread
11840     // pointer with the offset of the variable.
11841     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11842   }
11843
11844   llvm_unreachable("TLS not implemented for this target.");
11845 }
11846
11847 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11848 /// and take a 2 x i32 value to shift plus a shift amount.
11849 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11850   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11851   MVT VT = Op.getSimpleValueType();
11852   unsigned VTBits = VT.getSizeInBits();
11853   SDLoc dl(Op);
11854   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11855   SDValue ShOpLo = Op.getOperand(0);
11856   SDValue ShOpHi = Op.getOperand(1);
11857   SDValue ShAmt  = Op.getOperand(2);
11858   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11859   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11860   // during isel.
11861   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11862                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11863   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11864                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11865                        : DAG.getConstant(0, dl, VT);
11866
11867   SDValue Tmp2, Tmp3;
11868   if (Op.getOpcode() == ISD::SHL_PARTS) {
11869     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11870     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11871   } else {
11872     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11873     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11874   }
11875
11876   // If the shift amount is larger or equal than the width of a part we can't
11877   // rely on the results of shld/shrd. Insert a test and select the appropriate
11878   // values for large shift amounts.
11879   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11880                                 DAG.getConstant(VTBits, dl, MVT::i8));
11881   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11882                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11883
11884   SDValue Hi, Lo;
11885   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11886   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11887   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11888
11889   if (Op.getOpcode() == ISD::SHL_PARTS) {
11890     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11891     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11892   } else {
11893     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11894     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11895   }
11896
11897   SDValue Ops[2] = { Lo, Hi };
11898   return DAG.getMergeValues(Ops, dl);
11899 }
11900
11901 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11902                                            SelectionDAG &DAG) const {
11903   SDValue Src = Op.getOperand(0);
11904   MVT SrcVT = Src.getSimpleValueType();
11905   MVT VT = Op.getSimpleValueType();
11906   SDLoc dl(Op);
11907
11908   if (SrcVT.isVector()) {
11909     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11910       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11911                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11912                          DAG.getUNDEF(SrcVT)));
11913     }
11914     if (SrcVT.getVectorElementType() == MVT::i1) {
11915       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11916       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11917                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11918     }
11919     return SDValue();
11920   }
11921
11922   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11923          "Unknown SINT_TO_FP to lower!");
11924
11925   // These are really Legal; return the operand so the caller accepts it as
11926   // Legal.
11927   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11928     return Op;
11929   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11930       Subtarget->is64Bit()) {
11931     return Op;
11932   }
11933
11934   unsigned Size = SrcVT.getSizeInBits()/8;
11935   MachineFunction &MF = DAG.getMachineFunction();
11936   auto PtrVT = getPointerTy(MF.getDataLayout());
11937   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11938   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11939   SDValue Chain = DAG.getStore(
11940       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
11941       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
11942       false, 0);
11943   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11944 }
11945
11946 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11947                                      SDValue StackSlot,
11948                                      SelectionDAG &DAG) const {
11949   // Build the FILD
11950   SDLoc DL(Op);
11951   SDVTList Tys;
11952   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11953   if (useSSE)
11954     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11955   else
11956     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11957
11958   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11959
11960   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11961   MachineMemOperand *MMO;
11962   if (FI) {
11963     int SSFI = FI->getIndex();
11964     MMO = DAG.getMachineFunction().getMachineMemOperand(
11965         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11966         MachineMemOperand::MOLoad, ByteSize, ByteSize);
11967   } else {
11968     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11969     StackSlot = StackSlot.getOperand(1);
11970   }
11971   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11972   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11973                                            X86ISD::FILD, DL,
11974                                            Tys, Ops, SrcVT, MMO);
11975
11976   if (useSSE) {
11977     Chain = Result.getValue(1);
11978     SDValue InFlag = Result.getValue(2);
11979
11980     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11981     // shouldn't be necessary except that RFP cannot be live across
11982     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11983     MachineFunction &MF = DAG.getMachineFunction();
11984     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11985     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11986     auto PtrVT = getPointerTy(MF.getDataLayout());
11987     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11988     Tys = DAG.getVTList(MVT::Other);
11989     SDValue Ops[] = {
11990       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11991     };
11992     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
11993         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11994         MachineMemOperand::MOStore, SSFISize, SSFISize);
11995
11996     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11997                                     Ops, Op.getValueType(), MMO);
11998     Result = DAG.getLoad(
11999         Op.getValueType(), DL, Chain, StackSlot,
12000         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12001         false, false, false, 0);
12002   }
12003
12004   return Result;
12005 }
12006
12007 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12008 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12009                                                SelectionDAG &DAG) const {
12010   // This algorithm is not obvious. Here it is what we're trying to output:
12011   /*
12012      movq       %rax,  %xmm0
12013      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12014      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12015      #ifdef __SSE3__
12016        haddpd   %xmm0, %xmm0
12017      #else
12018        pshufd   $0x4e, %xmm0, %xmm1
12019        addpd    %xmm1, %xmm0
12020      #endif
12021   */
12022
12023   SDLoc dl(Op);
12024   LLVMContext *Context = DAG.getContext();
12025
12026   // Build some magic constants.
12027   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12028   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12029   auto PtrVT = getPointerTy(DAG.getDataLayout());
12030   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12031
12032   SmallVector<Constant*,2> CV1;
12033   CV1.push_back(
12034     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12035                                       APInt(64, 0x4330000000000000ULL))));
12036   CV1.push_back(
12037     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12038                                       APInt(64, 0x4530000000000000ULL))));
12039   Constant *C1 = ConstantVector::get(CV1);
12040   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12041
12042   // Load the 64-bit value into an XMM register.
12043   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12044                             Op.getOperand(0));
12045   SDValue CLod0 =
12046       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12047                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12048                   false, false, false, 16);
12049   SDValue Unpck1 =
12050       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12051
12052   SDValue CLod1 =
12053       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12054                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12055                   false, false, false, 16);
12056   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12057   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12058   SDValue Result;
12059
12060   if (Subtarget->hasSSE3()) {
12061     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12062     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12063   } else {
12064     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12065     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12066                                            S2F, 0x4E, DAG);
12067     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12068                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12069   }
12070
12071   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12072                      DAG.getIntPtrConstant(0, dl));
12073 }
12074
12075 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12076 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12077                                                SelectionDAG &DAG) const {
12078   SDLoc dl(Op);
12079   // FP constant to bias correct the final result.
12080   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12081                                    MVT::f64);
12082
12083   // Load the 32-bit value into an XMM register.
12084   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12085                              Op.getOperand(0));
12086
12087   // Zero out the upper parts of the register.
12088   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12089
12090   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12091                      DAG.getBitcast(MVT::v2f64, Load),
12092                      DAG.getIntPtrConstant(0, dl));
12093
12094   // Or the load with the bias.
12095   SDValue Or = DAG.getNode(
12096       ISD::OR, dl, MVT::v2i64,
12097       DAG.getBitcast(MVT::v2i64,
12098                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12099       DAG.getBitcast(MVT::v2i64,
12100                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12101   Or =
12102       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12103                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12104
12105   // Subtract the bias.
12106   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12107
12108   // Handle final rounding.
12109   EVT DestVT = Op.getValueType();
12110
12111   if (DestVT.bitsLT(MVT::f64))
12112     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12113                        DAG.getIntPtrConstant(0, dl));
12114   if (DestVT.bitsGT(MVT::f64))
12115     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12116
12117   // Handle final rounding.
12118   return Sub;
12119 }
12120
12121 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12122                                      const X86Subtarget &Subtarget) {
12123   // The algorithm is the following:
12124   // #ifdef __SSE4_1__
12125   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12126   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12127   //                                 (uint4) 0x53000000, 0xaa);
12128   // #else
12129   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12130   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12131   // #endif
12132   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12133   //     return (float4) lo + fhi;
12134
12135   SDLoc DL(Op);
12136   SDValue V = Op->getOperand(0);
12137   EVT VecIntVT = V.getValueType();
12138   bool Is128 = VecIntVT == MVT::v4i32;
12139   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12140   // If we convert to something else than the supported type, e.g., to v4f64,
12141   // abort early.
12142   if (VecFloatVT != Op->getValueType(0))
12143     return SDValue();
12144
12145   unsigned NumElts = VecIntVT.getVectorNumElements();
12146   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12147          "Unsupported custom type");
12148   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12149
12150   // In the #idef/#else code, we have in common:
12151   // - The vector of constants:
12152   // -- 0x4b000000
12153   // -- 0x53000000
12154   // - A shift:
12155   // -- v >> 16
12156
12157   // Create the splat vector for 0x4b000000.
12158   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12159   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12160                            CstLow, CstLow, CstLow, CstLow};
12161   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12162                                   makeArrayRef(&CstLowArray[0], NumElts));
12163   // Create the splat vector for 0x53000000.
12164   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12165   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12166                             CstHigh, CstHigh, CstHigh, CstHigh};
12167   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12168                                    makeArrayRef(&CstHighArray[0], NumElts));
12169
12170   // Create the right shift.
12171   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12172   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12173                              CstShift, CstShift, CstShift, CstShift};
12174   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12175                                     makeArrayRef(&CstShiftArray[0], NumElts));
12176   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12177
12178   SDValue Low, High;
12179   if (Subtarget.hasSSE41()) {
12180     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12181     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12182     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12183     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12184     // Low will be bitcasted right away, so do not bother bitcasting back to its
12185     // original type.
12186     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12187                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12188     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12189     //                                 (uint4) 0x53000000, 0xaa);
12190     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12191     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12192     // High will be bitcasted right away, so do not bother bitcasting back to
12193     // its original type.
12194     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12195                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12196   } else {
12197     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12198     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12199                                      CstMask, CstMask, CstMask);
12200     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12201     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12202     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12203
12204     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12205     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12206   }
12207
12208   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12209   SDValue CstFAdd = DAG.getConstantFP(
12210       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12211   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12212                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12213   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12214                                    makeArrayRef(&CstFAddArray[0], NumElts));
12215
12216   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12217   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12218   SDValue FHigh =
12219       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12220   //     return (float4) lo + fhi;
12221   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12222   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12223 }
12224
12225 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12226                                                SelectionDAG &DAG) const {
12227   SDValue N0 = Op.getOperand(0);
12228   MVT SVT = N0.getSimpleValueType();
12229   SDLoc dl(Op);
12230
12231   switch (SVT.SimpleTy) {
12232   default:
12233     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12234   case MVT::v4i8:
12235   case MVT::v4i16:
12236   case MVT::v8i8:
12237   case MVT::v8i16: {
12238     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12239     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12240                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12241   }
12242   case MVT::v4i32:
12243   case MVT::v8i32:
12244     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12245   case MVT::v16i8:
12246   case MVT::v16i16:
12247     if (Subtarget->hasAVX512())
12248       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12249                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12250   }
12251   llvm_unreachable(nullptr);
12252 }
12253
12254 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12255                                            SelectionDAG &DAG) const {
12256   SDValue N0 = Op.getOperand(0);
12257   SDLoc dl(Op);
12258   auto PtrVT = getPointerTy(DAG.getDataLayout());
12259
12260   if (Op.getValueType().isVector())
12261     return lowerUINT_TO_FP_vec(Op, DAG);
12262
12263   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12264   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12265   // the optimization here.
12266   if (DAG.SignBitIsZero(N0))
12267     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12268
12269   MVT SrcVT = N0.getSimpleValueType();
12270   MVT DstVT = Op.getSimpleValueType();
12271   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12272     return LowerUINT_TO_FP_i64(Op, DAG);
12273   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12274     return LowerUINT_TO_FP_i32(Op, DAG);
12275   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12276     return SDValue();
12277
12278   // Make a 64-bit buffer, and use it to build an FILD.
12279   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12280   if (SrcVT == MVT::i32) {
12281     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12282     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12283     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12284                                   StackSlot, MachinePointerInfo(),
12285                                   false, false, 0);
12286     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12287                                   OffsetSlot, MachinePointerInfo(),
12288                                   false, false, 0);
12289     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12290     return Fild;
12291   }
12292
12293   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12294   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12295                                StackSlot, MachinePointerInfo(),
12296                                false, false, 0);
12297   // For i64 source, we need to add the appropriate power of 2 if the input
12298   // was negative.  This is the same as the optimization in
12299   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12300   // we must be careful to do the computation in x87 extended precision, not
12301   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12302   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12303   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12304       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12305       MachineMemOperand::MOLoad, 8, 8);
12306
12307   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12308   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12309   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12310                                          MVT::i64, MMO);
12311
12312   APInt FF(32, 0x5F800000ULL);
12313
12314   // Check whether the sign bit is set.
12315   SDValue SignSet = DAG.getSetCC(
12316       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12317       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12318
12319   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12320   SDValue FudgePtr = DAG.getConstantPool(
12321       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12322
12323   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12324   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12325   SDValue Four = DAG.getIntPtrConstant(4, dl);
12326   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12327                                Zero, Four);
12328   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12329
12330   // Load the value out, extending it from f32 to f80.
12331   // FIXME: Avoid the extend by constructing the right constant pool?
12332   SDValue Fudge = DAG.getExtLoad(
12333       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12334       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12335       false, false, false, 4);
12336   // Extend everything to 80 bits to force it to be done on x87.
12337   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12338   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12339                      DAG.getIntPtrConstant(0, dl));
12340 }
12341
12342 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12343 // is legal, or has an f16 source (which needs to be promoted to f32),
12344 // just return an <SDValue(), SDValue()> pair.
12345 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12346 // to i16, i32 or i64, and we lower it to a legal sequence.
12347 // If lowered to the final integer result we return a <result, SDValue()> pair.
12348 // Otherwise we lower it to a sequence ending with a FIST, return a
12349 // <FIST, StackSlot> pair, and the caller is responsible for loading
12350 // the final integer result from StackSlot.
12351 std::pair<SDValue,SDValue>
12352 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12353                                    bool IsSigned, bool IsReplace) const {
12354   SDLoc DL(Op);
12355
12356   EVT DstTy = Op.getValueType();
12357   EVT TheVT = Op.getOperand(0).getValueType();
12358   auto PtrVT = getPointerTy(DAG.getDataLayout());
12359
12360   if (TheVT == MVT::f16)
12361     // We need to promote the f16 to f32 before using the lowering
12362     // in this routine.
12363     return std::make_pair(SDValue(), SDValue());
12364
12365   assert((TheVT == MVT::f32 ||
12366           TheVT == MVT::f64 ||
12367           TheVT == MVT::f80) &&
12368          "Unexpected FP operand type in FP_TO_INTHelper");
12369
12370   // If using FIST to compute an unsigned i64, we'll need some fixup
12371   // to handle values above the maximum signed i64.  A FIST is always
12372   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12373   bool UnsignedFixup = !IsSigned &&
12374                        DstTy == MVT::i64 &&
12375                        (!Subtarget->is64Bit() ||
12376                         !isScalarFPTypeInSSEReg(TheVT));
12377
12378   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12379     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12380     // The low 32 bits of the fist result will have the correct uint32 result.
12381     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12382     DstTy = MVT::i64;
12383   }
12384
12385   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12386          DstTy.getSimpleVT() >= MVT::i16 &&
12387          "Unknown FP_TO_INT to lower!");
12388
12389   // These are really Legal.
12390   if (DstTy == MVT::i32 &&
12391       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12392     return std::make_pair(SDValue(), SDValue());
12393   if (Subtarget->is64Bit() &&
12394       DstTy == MVT::i64 &&
12395       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12396     return std::make_pair(SDValue(), SDValue());
12397
12398   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12399   // stack slot.
12400   MachineFunction &MF = DAG.getMachineFunction();
12401   unsigned MemSize = DstTy.getSizeInBits()/8;
12402   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12403   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12404
12405   unsigned Opc;
12406   switch (DstTy.getSimpleVT().SimpleTy) {
12407   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12408   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12409   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12410   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12411   }
12412
12413   SDValue Chain = DAG.getEntryNode();
12414   SDValue Value = Op.getOperand(0);
12415   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12416
12417   if (UnsignedFixup) {
12418     //
12419     // Conversion to unsigned i64 is implemented with a select,
12420     // depending on whether the source value fits in the range
12421     // of a signed i64.  Let Thresh be the FP equivalent of
12422     // 0x8000000000000000ULL.
12423     //
12424     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12425     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12426     //  Fist-to-mem64 FistSrc
12427     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12428     //  to XOR'ing the high 32 bits with Adjust.
12429     //
12430     // Being a power of 2, Thresh is exactly representable in all FP formats.
12431     // For X87 we'd like to use the smallest FP type for this constant, but
12432     // for DAG type consistency we have to match the FP operand type.
12433
12434     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12435     APFloat::opStatus Status = APFloat::opOK;
12436     bool LosesInfo = false;
12437     if (TheVT == MVT::f64)
12438       // The rounding mode is irrelevant as the conversion should be exact.
12439       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12440                               &LosesInfo);
12441     else if (TheVT == MVT::f80)
12442       Status = Thresh.convert(APFloat::x87DoubleExtended,
12443                               APFloat::rmNearestTiesToEven, &LosesInfo);
12444
12445     assert(Status == APFloat::opOK && !LosesInfo &&
12446            "FP conversion should have been exact");
12447
12448     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12449
12450     SDValue Cmp = DAG.getSetCC(DL,
12451                                getSetCCResultType(DAG.getDataLayout(),
12452                                                   *DAG.getContext(), TheVT),
12453                                Value, ThreshVal, ISD::SETLT);
12454     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12455                            DAG.getConstant(0, DL, MVT::i32),
12456                            DAG.getConstant(0x80000000, DL, MVT::i32));
12457     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12458     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12459                                               *DAG.getContext(), TheVT),
12460                        Value, ThreshVal, ISD::SETLT);
12461     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12462   }
12463
12464   // FIXME This causes a redundant load/store if the SSE-class value is already
12465   // in memory, such as if it is on the callstack.
12466   if (isScalarFPTypeInSSEReg(TheVT)) {
12467     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12468     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12469                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12470                          false, 0);
12471     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12472     SDValue Ops[] = {
12473       Chain, StackSlot, DAG.getValueType(TheVT)
12474     };
12475
12476     MachineMemOperand *MMO =
12477         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12478                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12479     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12480     Chain = Value.getValue(1);
12481     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12482     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12483   }
12484
12485   MachineMemOperand *MMO =
12486       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12487                               MachineMemOperand::MOStore, MemSize, MemSize);
12488
12489   if (UnsignedFixup) {
12490
12491     // Insert the FIST, load its result as two i32's,
12492     // and XOR the high i32 with Adjust.
12493
12494     SDValue FistOps[] = { Chain, Value, StackSlot };
12495     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12496                                            FistOps, DstTy, MMO);
12497
12498     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12499                                 MachinePointerInfo(),
12500                                 false, false, false, 0);
12501     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12502                                    DAG.getConstant(4, DL, PtrVT));
12503
12504     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12505                                  MachinePointerInfo(),
12506                                  false, false, false, 0);
12507     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12508
12509     if (Subtarget->is64Bit()) {
12510       // Join High32 and Low32 into a 64-bit result.
12511       // (High32 << 32) | Low32
12512       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12513       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12514       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12515                            DAG.getConstant(32, DL, MVT::i8));
12516       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12517       return std::make_pair(Result, SDValue());
12518     }
12519
12520     SDValue ResultOps[] = { Low32, High32 };
12521
12522     SDValue pair = IsReplace
12523       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12524       : DAG.getMergeValues(ResultOps, DL);
12525     return std::make_pair(pair, SDValue());
12526   } else {
12527     // Build the FP_TO_INT*_IN_MEM
12528     SDValue Ops[] = { Chain, Value, StackSlot };
12529     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12530                                            Ops, DstTy, MMO);
12531     return std::make_pair(FIST, StackSlot);
12532   }
12533 }
12534
12535 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12536                               const X86Subtarget *Subtarget) {
12537   MVT VT = Op->getSimpleValueType(0);
12538   SDValue In = Op->getOperand(0);
12539   MVT InVT = In.getSimpleValueType();
12540   SDLoc dl(Op);
12541
12542   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12543     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12544
12545   // Optimize vectors in AVX mode:
12546   //
12547   //   v8i16 -> v8i32
12548   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12549   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12550   //   Concat upper and lower parts.
12551   //
12552   //   v4i32 -> v4i64
12553   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12554   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12555   //   Concat upper and lower parts.
12556   //
12557
12558   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12559       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12560       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12561     return SDValue();
12562
12563   if (Subtarget->hasInt256())
12564     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12565
12566   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12567   SDValue Undef = DAG.getUNDEF(InVT);
12568   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12569   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12570   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12571
12572   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12573                              VT.getVectorNumElements()/2);
12574
12575   OpLo = DAG.getBitcast(HVT, OpLo);
12576   OpHi = DAG.getBitcast(HVT, OpHi);
12577
12578   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12579 }
12580
12581 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12582                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12583   MVT VT = Op->getSimpleValueType(0);
12584   SDValue In = Op->getOperand(0);
12585   MVT InVT = In.getSimpleValueType();
12586   SDLoc DL(Op);
12587   unsigned int NumElts = VT.getVectorNumElements();
12588   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12589     return SDValue();
12590
12591   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12592     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12593
12594   assert(InVT.getVectorElementType() == MVT::i1);
12595   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12596   SDValue One =
12597    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12598   SDValue Zero =
12599    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12600
12601   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12602   if (VT.is512BitVector())
12603     return V;
12604   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12605 }
12606
12607 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12608                                SelectionDAG &DAG) {
12609   if (Subtarget->hasFp256())
12610     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12611       return Res;
12612
12613   return SDValue();
12614 }
12615
12616 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12617                                 SelectionDAG &DAG) {
12618   SDLoc DL(Op);
12619   MVT VT = Op.getSimpleValueType();
12620   SDValue In = Op.getOperand(0);
12621   MVT SVT = In.getSimpleValueType();
12622
12623   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12624     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12625
12626   if (Subtarget->hasFp256())
12627     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12628       return Res;
12629
12630   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12631          VT.getVectorNumElements() != SVT.getVectorNumElements());
12632   return SDValue();
12633 }
12634
12635 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12636   SDLoc DL(Op);
12637   MVT VT = Op.getSimpleValueType();
12638   SDValue In = Op.getOperand(0);
12639   MVT InVT = In.getSimpleValueType();
12640
12641   if (VT == MVT::i1) {
12642     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12643            "Invalid scalar TRUNCATE operation");
12644     if (InVT.getSizeInBits() >= 32)
12645       return SDValue();
12646     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12647     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12648   }
12649   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12650          "Invalid TRUNCATE operation");
12651
12652   // move vector to mask - truncate solution for SKX
12653   if (VT.getVectorElementType() == MVT::i1) {
12654     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12655         Subtarget->hasBWI())
12656       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12657     if ((InVT.is256BitVector() || InVT.is128BitVector())
12658         && InVT.getScalarSizeInBits() <= 16 &&
12659         Subtarget->hasBWI() && Subtarget->hasVLX())
12660       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12661     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12662         Subtarget->hasDQI())
12663       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12664     if ((InVT.is256BitVector() || InVT.is128BitVector())
12665         && InVT.getScalarSizeInBits() >= 32 &&
12666         Subtarget->hasDQI() && Subtarget->hasVLX())
12667       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12668   }
12669
12670   if (VT.getVectorElementType() == MVT::i1) {
12671     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12672     unsigned NumElts = InVT.getVectorNumElements();
12673     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12674     if (InVT.getSizeInBits() < 512) {
12675       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12676       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12677       InVT = ExtVT;
12678     }
12679
12680     SDValue OneV =
12681      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12682     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12683     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12684   }
12685
12686   // vpmovqb/w/d, vpmovdb/w, vpmovwb
12687   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12688       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12689     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12690
12691   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12692     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12693     if (Subtarget->hasInt256()) {
12694       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12695       In = DAG.getBitcast(MVT::v8i32, In);
12696       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12697                                 ShufMask);
12698       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12699                          DAG.getIntPtrConstant(0, DL));
12700     }
12701
12702     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12703                                DAG.getIntPtrConstant(0, DL));
12704     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12705                                DAG.getIntPtrConstant(2, DL));
12706     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12707     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12708     static const int ShufMask[] = {0, 2, 4, 6};
12709     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12710   }
12711
12712   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12713     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12714     if (Subtarget->hasInt256()) {
12715       In = DAG.getBitcast(MVT::v32i8, In);
12716
12717       SmallVector<SDValue,32> pshufbMask;
12718       for (unsigned i = 0; i < 2; ++i) {
12719         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12720         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12721         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12722         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12723         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12724         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12725         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12726         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12727         for (unsigned j = 0; j < 8; ++j)
12728           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12729       }
12730       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12731       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12732       In = DAG.getBitcast(MVT::v4i64, In);
12733
12734       static const int ShufMask[] = {0,  2,  -1,  -1};
12735       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12736                                 &ShufMask[0]);
12737       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12738                        DAG.getIntPtrConstant(0, DL));
12739       return DAG.getBitcast(VT, In);
12740     }
12741
12742     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12743                                DAG.getIntPtrConstant(0, DL));
12744
12745     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12746                                DAG.getIntPtrConstant(4, DL));
12747
12748     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12749     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12750
12751     // The PSHUFB mask:
12752     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12753                                    -1, -1, -1, -1, -1, -1, -1, -1};
12754
12755     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12756     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12757     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12758
12759     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12760     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12761
12762     // The MOVLHPS Mask:
12763     static const int ShufMask2[] = {0, 1, 4, 5};
12764     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12765     return DAG.getBitcast(MVT::v8i16, res);
12766   }
12767
12768   // Handle truncation of V256 to V128 using shuffles.
12769   if (!VT.is128BitVector() || !InVT.is256BitVector())
12770     return SDValue();
12771
12772   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12773
12774   unsigned NumElems = VT.getVectorNumElements();
12775   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12776
12777   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12778   // Prepare truncation shuffle mask
12779   for (unsigned i = 0; i != NumElems; ++i)
12780     MaskVec[i] = i * 2;
12781   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12782                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12783   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12784                      DAG.getIntPtrConstant(0, DL));
12785 }
12786
12787 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12788                                            SelectionDAG &DAG) const {
12789   assert(!Op.getSimpleValueType().isVector());
12790
12791   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12792     /*IsSigned=*/ true, /*IsReplace=*/ false);
12793   SDValue FIST = Vals.first, StackSlot = Vals.second;
12794   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12795   if (!FIST.getNode())
12796     return Op;
12797
12798   if (StackSlot.getNode())
12799     // Load the result.
12800     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12801                        FIST, StackSlot, MachinePointerInfo(),
12802                        false, false, false, 0);
12803
12804   // The node is the result.
12805   return FIST;
12806 }
12807
12808 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12809                                            SelectionDAG &DAG) const {
12810   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12811     /*IsSigned=*/ false, /*IsReplace=*/ false);
12812   SDValue FIST = Vals.first, StackSlot = Vals.second;
12813   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12814   if (!FIST.getNode())
12815     return Op;
12816
12817   if (StackSlot.getNode())
12818     // Load the result.
12819     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12820                        FIST, StackSlot, MachinePointerInfo(),
12821                        false, false, false, 0);
12822
12823   // The node is the result.
12824   return FIST;
12825 }
12826
12827 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12828   SDLoc DL(Op);
12829   MVT VT = Op.getSimpleValueType();
12830   SDValue In = Op.getOperand(0);
12831   MVT SVT = In.getSimpleValueType();
12832
12833   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12834
12835   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12836                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12837                                  In, DAG.getUNDEF(SVT)));
12838 }
12839
12840 /// The only differences between FABS and FNEG are the mask and the logic op.
12841 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12842 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12843   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12844          "Wrong opcode for lowering FABS or FNEG.");
12845
12846   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12847
12848   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12849   // into an FNABS. We'll lower the FABS after that if it is still in use.
12850   if (IsFABS)
12851     for (SDNode *User : Op->uses())
12852       if (User->getOpcode() == ISD::FNEG)
12853         return Op;
12854
12855   SDLoc dl(Op);
12856   MVT VT = Op.getSimpleValueType();
12857
12858   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12859   // decide if we should generate a 16-byte constant mask when we only need 4 or
12860   // 8 bytes for the scalar case.
12861
12862   MVT LogicVT;
12863   MVT EltVT;
12864   unsigned NumElts;
12865
12866   if (VT.isVector()) {
12867     LogicVT = VT;
12868     EltVT = VT.getVectorElementType();
12869     NumElts = VT.getVectorNumElements();
12870   } else {
12871     // There are no scalar bitwise logical SSE/AVX instructions, so we
12872     // generate a 16-byte vector constant and logic op even for the scalar case.
12873     // Using a 16-byte mask allows folding the load of the mask with
12874     // the logic op, so it can save (~4 bytes) on code size.
12875     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12876     EltVT = VT;
12877     NumElts = (VT == MVT::f64) ? 2 : 4;
12878   }
12879
12880   unsigned EltBits = EltVT.getSizeInBits();
12881   LLVMContext *Context = DAG.getContext();
12882   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12883   APInt MaskElt =
12884     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12885   Constant *C = ConstantInt::get(*Context, MaskElt);
12886   C = ConstantVector::getSplat(NumElts, C);
12887   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12888   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12889   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12890   SDValue Mask =
12891       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12892                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12893                   false, false, false, Alignment);
12894
12895   SDValue Op0 = Op.getOperand(0);
12896   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12897   unsigned LogicOp =
12898     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12899   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12900
12901   if (VT.isVector())
12902     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12903
12904   // For the scalar case extend to a 128-bit vector, perform the logic op,
12905   // and extract the scalar result back out.
12906   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
12907   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12908   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
12909                      DAG.getIntPtrConstant(0, dl));
12910 }
12911
12912 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12913   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12914   LLVMContext *Context = DAG.getContext();
12915   SDValue Op0 = Op.getOperand(0);
12916   SDValue Op1 = Op.getOperand(1);
12917   SDLoc dl(Op);
12918   MVT VT = Op.getSimpleValueType();
12919   MVT SrcVT = Op1.getSimpleValueType();
12920
12921   // If second operand is smaller, extend it first.
12922   if (SrcVT.bitsLT(VT)) {
12923     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12924     SrcVT = VT;
12925   }
12926   // And if it is bigger, shrink it first.
12927   if (SrcVT.bitsGT(VT)) {
12928     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12929     SrcVT = VT;
12930   }
12931
12932   // At this point the operands and the result should have the same
12933   // type, and that won't be f80 since that is not custom lowered.
12934
12935   const fltSemantics &Sem =
12936       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12937   const unsigned SizeInBits = VT.getSizeInBits();
12938
12939   SmallVector<Constant *, 4> CV(
12940       VT == MVT::f64 ? 2 : 4,
12941       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12942
12943   // First, clear all bits but the sign bit from the second operand (sign).
12944   CV[0] = ConstantFP::get(*Context,
12945                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12946   Constant *C = ConstantVector::get(CV);
12947   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12948   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12949
12950   // Perform all logic operations as 16-byte vectors because there are no
12951   // scalar FP logic instructions in SSE. This allows load folding of the
12952   // constants into the logic instructions.
12953   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12954   SDValue Mask1 =
12955       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12956                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12957                   false, false, false, 16);
12958   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
12959   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
12960
12961   // Next, clear the sign bit from the first operand (magnitude).
12962   // If it's a constant, we can clear it here.
12963   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12964     APFloat APF = Op0CN->getValueAPF();
12965     // If the magnitude is a positive zero, the sign bit alone is enough.
12966     if (APF.isPosZero())
12967       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
12968                          DAG.getIntPtrConstant(0, dl));
12969     APF.clearSign();
12970     CV[0] = ConstantFP::get(*Context, APF);
12971   } else {
12972     CV[0] = ConstantFP::get(
12973         *Context,
12974         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12975   }
12976   C = ConstantVector::get(CV);
12977   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12978   SDValue Val =
12979       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12980                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12981                   false, false, false, 16);
12982   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12983   if (!isa<ConstantFPSDNode>(Op0)) {
12984     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
12985     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
12986   }
12987   // OR the magnitude value with the sign bit.
12988   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
12989   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
12990                      DAG.getIntPtrConstant(0, dl));
12991 }
12992
12993 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12994   SDValue N0 = Op.getOperand(0);
12995   SDLoc dl(Op);
12996   MVT VT = Op.getSimpleValueType();
12997
12998   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12999   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13000                                   DAG.getConstant(1, dl, VT));
13001   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13002 }
13003
13004 // Check whether an OR'd tree is PTEST-able.
13005 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13006                                       SelectionDAG &DAG) {
13007   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13008
13009   if (!Subtarget->hasSSE41())
13010     return SDValue();
13011
13012   if (!Op->hasOneUse())
13013     return SDValue();
13014
13015   SDNode *N = Op.getNode();
13016   SDLoc DL(N);
13017
13018   SmallVector<SDValue, 8> Opnds;
13019   DenseMap<SDValue, unsigned> VecInMap;
13020   SmallVector<SDValue, 8> VecIns;
13021   EVT VT = MVT::Other;
13022
13023   // Recognize a special case where a vector is casted into wide integer to
13024   // test all 0s.
13025   Opnds.push_back(N->getOperand(0));
13026   Opnds.push_back(N->getOperand(1));
13027
13028   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13029     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13030     // BFS traverse all OR'd operands.
13031     if (I->getOpcode() == ISD::OR) {
13032       Opnds.push_back(I->getOperand(0));
13033       Opnds.push_back(I->getOperand(1));
13034       // Re-evaluate the number of nodes to be traversed.
13035       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13036       continue;
13037     }
13038
13039     // Quit if a non-EXTRACT_VECTOR_ELT
13040     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13041       return SDValue();
13042
13043     // Quit if without a constant index.
13044     SDValue Idx = I->getOperand(1);
13045     if (!isa<ConstantSDNode>(Idx))
13046       return SDValue();
13047
13048     SDValue ExtractedFromVec = I->getOperand(0);
13049     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13050     if (M == VecInMap.end()) {
13051       VT = ExtractedFromVec.getValueType();
13052       // Quit if not 128/256-bit vector.
13053       if (!VT.is128BitVector() && !VT.is256BitVector())
13054         return SDValue();
13055       // Quit if not the same type.
13056       if (VecInMap.begin() != VecInMap.end() &&
13057           VT != VecInMap.begin()->first.getValueType())
13058         return SDValue();
13059       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13060       VecIns.push_back(ExtractedFromVec);
13061     }
13062     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13063   }
13064
13065   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13066          "Not extracted from 128-/256-bit vector.");
13067
13068   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13069
13070   for (DenseMap<SDValue, unsigned>::const_iterator
13071         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13072     // Quit if not all elements are used.
13073     if (I->second != FullMask)
13074       return SDValue();
13075   }
13076
13077   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13078
13079   // Cast all vectors into TestVT for PTEST.
13080   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13081     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13082
13083   // If more than one full vectors are evaluated, OR them first before PTEST.
13084   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13085     // Each iteration will OR 2 nodes and append the result until there is only
13086     // 1 node left, i.e. the final OR'd value of all vectors.
13087     SDValue LHS = VecIns[Slot];
13088     SDValue RHS = VecIns[Slot + 1];
13089     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13090   }
13091
13092   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13093                      VecIns.back(), VecIns.back());
13094 }
13095
13096 /// \brief return true if \c Op has a use that doesn't just read flags.
13097 static bool hasNonFlagsUse(SDValue Op) {
13098   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13099        ++UI) {
13100     SDNode *User = *UI;
13101     unsigned UOpNo = UI.getOperandNo();
13102     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13103       // Look pass truncate.
13104       UOpNo = User->use_begin().getOperandNo();
13105       User = *User->use_begin();
13106     }
13107
13108     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13109         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13110       return true;
13111   }
13112   return false;
13113 }
13114
13115 /// Emit nodes that will be selected as "test Op0,Op0", or something
13116 /// equivalent.
13117 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13118                                     SelectionDAG &DAG) const {
13119   if (Op.getValueType() == MVT::i1) {
13120     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13121     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13122                        DAG.getConstant(0, dl, MVT::i8));
13123   }
13124   // CF and OF aren't always set the way we want. Determine which
13125   // of these we need.
13126   bool NeedCF = false;
13127   bool NeedOF = false;
13128   switch (X86CC) {
13129   default: break;
13130   case X86::COND_A: case X86::COND_AE:
13131   case X86::COND_B: case X86::COND_BE:
13132     NeedCF = true;
13133     break;
13134   case X86::COND_G: case X86::COND_GE:
13135   case X86::COND_L: case X86::COND_LE:
13136   case X86::COND_O: case X86::COND_NO: {
13137     // Check if we really need to set the
13138     // Overflow flag. If NoSignedWrap is present
13139     // that is not actually needed.
13140     switch (Op->getOpcode()) {
13141     case ISD::ADD:
13142     case ISD::SUB:
13143     case ISD::MUL:
13144     case ISD::SHL: {
13145       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13146       if (BinNode->Flags.hasNoSignedWrap())
13147         break;
13148     }
13149     default:
13150       NeedOF = true;
13151       break;
13152     }
13153     break;
13154   }
13155   }
13156   // See if we can use the EFLAGS value from the operand instead of
13157   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13158   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13159   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13160     // Emit a CMP with 0, which is the TEST pattern.
13161     //if (Op.getValueType() == MVT::i1)
13162     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13163     //                     DAG.getConstant(0, MVT::i1));
13164     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13165                        DAG.getConstant(0, dl, Op.getValueType()));
13166   }
13167   unsigned Opcode = 0;
13168   unsigned NumOperands = 0;
13169
13170   // Truncate operations may prevent the merge of the SETCC instruction
13171   // and the arithmetic instruction before it. Attempt to truncate the operands
13172   // of the arithmetic instruction and use a reduced bit-width instruction.
13173   bool NeedTruncation = false;
13174   SDValue ArithOp = Op;
13175   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13176     SDValue Arith = Op->getOperand(0);
13177     // Both the trunc and the arithmetic op need to have one user each.
13178     if (Arith->hasOneUse())
13179       switch (Arith.getOpcode()) {
13180         default: break;
13181         case ISD::ADD:
13182         case ISD::SUB:
13183         case ISD::AND:
13184         case ISD::OR:
13185         case ISD::XOR: {
13186           NeedTruncation = true;
13187           ArithOp = Arith;
13188         }
13189       }
13190   }
13191
13192   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13193   // which may be the result of a CAST.  We use the variable 'Op', which is the
13194   // non-casted variable when we check for possible users.
13195   switch (ArithOp.getOpcode()) {
13196   case ISD::ADD:
13197     // Due to an isel shortcoming, be conservative if this add is likely to be
13198     // selected as part of a load-modify-store instruction. When the root node
13199     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13200     // uses of other nodes in the match, such as the ADD in this case. This
13201     // leads to the ADD being left around and reselected, with the result being
13202     // two adds in the output.  Alas, even if none our users are stores, that
13203     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13204     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13205     // climbing the DAG back to the root, and it doesn't seem to be worth the
13206     // effort.
13207     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13208          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13209       if (UI->getOpcode() != ISD::CopyToReg &&
13210           UI->getOpcode() != ISD::SETCC &&
13211           UI->getOpcode() != ISD::STORE)
13212         goto default_case;
13213
13214     if (ConstantSDNode *C =
13215         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13216       // An add of one will be selected as an INC.
13217       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13218         Opcode = X86ISD::INC;
13219         NumOperands = 1;
13220         break;
13221       }
13222
13223       // An add of negative one (subtract of one) will be selected as a DEC.
13224       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13225         Opcode = X86ISD::DEC;
13226         NumOperands = 1;
13227         break;
13228       }
13229     }
13230
13231     // Otherwise use a regular EFLAGS-setting add.
13232     Opcode = X86ISD::ADD;
13233     NumOperands = 2;
13234     break;
13235   case ISD::SHL:
13236   case ISD::SRL:
13237     // If we have a constant logical shift that's only used in a comparison
13238     // against zero turn it into an equivalent AND. This allows turning it into
13239     // a TEST instruction later.
13240     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13241         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13242       EVT VT = Op.getValueType();
13243       unsigned BitWidth = VT.getSizeInBits();
13244       unsigned ShAmt = Op->getConstantOperandVal(1);
13245       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13246         break;
13247       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13248                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13249                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13250       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13251         break;
13252       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13253                                 DAG.getConstant(Mask, dl, VT));
13254       DAG.ReplaceAllUsesWith(Op, New);
13255       Op = New;
13256     }
13257     break;
13258
13259   case ISD::AND:
13260     // If the primary and result isn't used, don't bother using X86ISD::AND,
13261     // because a TEST instruction will be better.
13262     if (!hasNonFlagsUse(Op))
13263       break;
13264     // FALL THROUGH
13265   case ISD::SUB:
13266   case ISD::OR:
13267   case ISD::XOR:
13268     // Due to the ISEL shortcoming noted above, be conservative if this op is
13269     // likely to be selected as part of a load-modify-store instruction.
13270     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13271            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13272       if (UI->getOpcode() == ISD::STORE)
13273         goto default_case;
13274
13275     // Otherwise use a regular EFLAGS-setting instruction.
13276     switch (ArithOp.getOpcode()) {
13277     default: llvm_unreachable("unexpected operator!");
13278     case ISD::SUB: Opcode = X86ISD::SUB; break;
13279     case ISD::XOR: Opcode = X86ISD::XOR; break;
13280     case ISD::AND: Opcode = X86ISD::AND; break;
13281     case ISD::OR: {
13282       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13283         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13284         if (EFLAGS.getNode())
13285           return EFLAGS;
13286       }
13287       Opcode = X86ISD::OR;
13288       break;
13289     }
13290     }
13291
13292     NumOperands = 2;
13293     break;
13294   case X86ISD::ADD:
13295   case X86ISD::SUB:
13296   case X86ISD::INC:
13297   case X86ISD::DEC:
13298   case X86ISD::OR:
13299   case X86ISD::XOR:
13300   case X86ISD::AND:
13301     return SDValue(Op.getNode(), 1);
13302   default:
13303   default_case:
13304     break;
13305   }
13306
13307   // If we found that truncation is beneficial, perform the truncation and
13308   // update 'Op'.
13309   if (NeedTruncation) {
13310     EVT VT = Op.getValueType();
13311     SDValue WideVal = Op->getOperand(0);
13312     EVT WideVT = WideVal.getValueType();
13313     unsigned ConvertedOp = 0;
13314     // Use a target machine opcode to prevent further DAGCombine
13315     // optimizations that may separate the arithmetic operations
13316     // from the setcc node.
13317     switch (WideVal.getOpcode()) {
13318       default: break;
13319       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13320       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13321       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13322       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13323       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13324     }
13325
13326     if (ConvertedOp) {
13327       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13328       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13329         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13330         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13331         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13332       }
13333     }
13334   }
13335
13336   if (Opcode == 0)
13337     // Emit a CMP with 0, which is the TEST pattern.
13338     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13339                        DAG.getConstant(0, dl, Op.getValueType()));
13340
13341   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13342   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13343
13344   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13345   DAG.ReplaceAllUsesWith(Op, New);
13346   return SDValue(New.getNode(), 1);
13347 }
13348
13349 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13350 /// equivalent.
13351 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13352                                    SDLoc dl, SelectionDAG &DAG) const {
13353   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13354     if (C->getAPIntValue() == 0)
13355       return EmitTest(Op0, X86CC, dl, DAG);
13356
13357      if (Op0.getValueType() == MVT::i1)
13358        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13359   }
13360
13361   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13362        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13363     // Do the comparison at i32 if it's smaller, besides the Atom case.
13364     // This avoids subregister aliasing issues. Keep the smaller reference
13365     // if we're optimizing for size, however, as that'll allow better folding
13366     // of memory operations.
13367     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13368         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13369         !Subtarget->isAtom()) {
13370       unsigned ExtendOp =
13371           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13372       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13373       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13374     }
13375     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13376     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13377     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13378                               Op0, Op1);
13379     return SDValue(Sub.getNode(), 1);
13380   }
13381   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13382 }
13383
13384 /// Convert a comparison if required by the subtarget.
13385 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13386                                                  SelectionDAG &DAG) const {
13387   // If the subtarget does not support the FUCOMI instruction, floating-point
13388   // comparisons have to be converted.
13389   if (Subtarget->hasCMov() ||
13390       Cmp.getOpcode() != X86ISD::CMP ||
13391       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13392       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13393     return Cmp;
13394
13395   // The instruction selector will select an FUCOM instruction instead of
13396   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13397   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13398   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13399   SDLoc dl(Cmp);
13400   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13401   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13402   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13403                             DAG.getConstant(8, dl, MVT::i8));
13404   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13405   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13406 }
13407
13408 /// The minimum architected relative accuracy is 2^-12. We need one
13409 /// Newton-Raphson step to have a good float result (24 bits of precision).
13410 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13411                                             DAGCombinerInfo &DCI,
13412                                             unsigned &RefinementSteps,
13413                                             bool &UseOneConstNR) const {
13414   EVT VT = Op.getValueType();
13415   const char *RecipOp;
13416
13417   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13418   // TODO: Add support for AVX512 (v16f32).
13419   // It is likely not profitable to do this for f64 because a double-precision
13420   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13421   // instructions: convert to single, rsqrtss, convert back to double, refine
13422   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13423   // along with FMA, this could be a throughput win.
13424   if (VT == MVT::f32 && Subtarget->hasSSE1())
13425     RecipOp = "sqrtf";
13426   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13427            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13428     RecipOp = "vec-sqrtf";
13429   else
13430     return SDValue();
13431
13432   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13433   if (!Recips.isEnabled(RecipOp))
13434     return SDValue();
13435
13436   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13437   UseOneConstNR = false;
13438   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13439 }
13440
13441 /// The minimum architected relative accuracy is 2^-12. We need one
13442 /// Newton-Raphson step to have a good float result (24 bits of precision).
13443 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13444                                             DAGCombinerInfo &DCI,
13445                                             unsigned &RefinementSteps) const {
13446   EVT VT = Op.getValueType();
13447   const char *RecipOp;
13448
13449   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13450   // TODO: Add support for AVX512 (v16f32).
13451   // It is likely not profitable to do this for f64 because a double-precision
13452   // reciprocal estimate with refinement on x86 prior to FMA requires
13453   // 15 instructions: convert to single, rcpss, convert back to double, refine
13454   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13455   // along with FMA, this could be a throughput win.
13456   if (VT == MVT::f32 && Subtarget->hasSSE1())
13457     RecipOp = "divf";
13458   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13459            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13460     RecipOp = "vec-divf";
13461   else
13462     return SDValue();
13463
13464   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13465   if (!Recips.isEnabled(RecipOp))
13466     return SDValue();
13467
13468   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13469   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13470 }
13471
13472 /// If we have at least two divisions that use the same divisor, convert to
13473 /// multplication by a reciprocal. This may need to be adjusted for a given
13474 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13475 /// This is because we still need one division to calculate the reciprocal and
13476 /// then we need two multiplies by that reciprocal as replacements for the
13477 /// original divisions.
13478 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13479   return 2;
13480 }
13481
13482 static bool isAllOnes(SDValue V) {
13483   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13484   return C && C->isAllOnesValue();
13485 }
13486
13487 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13488 /// if it's possible.
13489 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13490                                      SDLoc dl, SelectionDAG &DAG) const {
13491   SDValue Op0 = And.getOperand(0);
13492   SDValue Op1 = And.getOperand(1);
13493   if (Op0.getOpcode() == ISD::TRUNCATE)
13494     Op0 = Op0.getOperand(0);
13495   if (Op1.getOpcode() == ISD::TRUNCATE)
13496     Op1 = Op1.getOperand(0);
13497
13498   SDValue LHS, RHS;
13499   if (Op1.getOpcode() == ISD::SHL)
13500     std::swap(Op0, Op1);
13501   if (Op0.getOpcode() == ISD::SHL) {
13502     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13503       if (And00C->getZExtValue() == 1) {
13504         // If we looked past a truncate, check that it's only truncating away
13505         // known zeros.
13506         unsigned BitWidth = Op0.getValueSizeInBits();
13507         unsigned AndBitWidth = And.getValueSizeInBits();
13508         if (BitWidth > AndBitWidth) {
13509           APInt Zeros, Ones;
13510           DAG.computeKnownBits(Op0, Zeros, Ones);
13511           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13512             return SDValue();
13513         }
13514         LHS = Op1;
13515         RHS = Op0.getOperand(1);
13516       }
13517   } else if (Op1.getOpcode() == ISD::Constant) {
13518     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13519     uint64_t AndRHSVal = AndRHS->getZExtValue();
13520     SDValue AndLHS = Op0;
13521
13522     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13523       LHS = AndLHS.getOperand(0);
13524       RHS = AndLHS.getOperand(1);
13525     }
13526
13527     // Use BT if the immediate can't be encoded in a TEST instruction.
13528     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13529       LHS = AndLHS;
13530       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13531     }
13532   }
13533
13534   if (LHS.getNode()) {
13535     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13536     // instruction.  Since the shift amount is in-range-or-undefined, we know
13537     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13538     // the encoding for the i16 version is larger than the i32 version.
13539     // Also promote i16 to i32 for performance / code size reason.
13540     if (LHS.getValueType() == MVT::i8 ||
13541         LHS.getValueType() == MVT::i16)
13542       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13543
13544     // If the operand types disagree, extend the shift amount to match.  Since
13545     // BT ignores high bits (like shifts) we can use anyextend.
13546     if (LHS.getValueType() != RHS.getValueType())
13547       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13548
13549     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13550     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13551     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13552                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13553   }
13554
13555   return SDValue();
13556 }
13557
13558 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13559 /// mask CMPs.
13560 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13561                               SDValue &Op1) {
13562   unsigned SSECC;
13563   bool Swap = false;
13564
13565   // SSE Condition code mapping:
13566   //  0 - EQ
13567   //  1 - LT
13568   //  2 - LE
13569   //  3 - UNORD
13570   //  4 - NEQ
13571   //  5 - NLT
13572   //  6 - NLE
13573   //  7 - ORD
13574   switch (SetCCOpcode) {
13575   default: llvm_unreachable("Unexpected SETCC condition");
13576   case ISD::SETOEQ:
13577   case ISD::SETEQ:  SSECC = 0; break;
13578   case ISD::SETOGT:
13579   case ISD::SETGT:  Swap = true; // Fallthrough
13580   case ISD::SETLT:
13581   case ISD::SETOLT: SSECC = 1; break;
13582   case ISD::SETOGE:
13583   case ISD::SETGE:  Swap = true; // Fallthrough
13584   case ISD::SETLE:
13585   case ISD::SETOLE: SSECC = 2; break;
13586   case ISD::SETUO:  SSECC = 3; break;
13587   case ISD::SETUNE:
13588   case ISD::SETNE:  SSECC = 4; break;
13589   case ISD::SETULE: Swap = true; // Fallthrough
13590   case ISD::SETUGE: SSECC = 5; break;
13591   case ISD::SETULT: Swap = true; // Fallthrough
13592   case ISD::SETUGT: SSECC = 6; break;
13593   case ISD::SETO:   SSECC = 7; break;
13594   case ISD::SETUEQ:
13595   case ISD::SETONE: SSECC = 8; break;
13596   }
13597   if (Swap)
13598     std::swap(Op0, Op1);
13599
13600   return SSECC;
13601 }
13602
13603 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13604 // ones, and then concatenate the result back.
13605 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13606   MVT VT = Op.getSimpleValueType();
13607
13608   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13609          "Unsupported value type for operation");
13610
13611   unsigned NumElems = VT.getVectorNumElements();
13612   SDLoc dl(Op);
13613   SDValue CC = Op.getOperand(2);
13614
13615   // Extract the LHS vectors
13616   SDValue LHS = Op.getOperand(0);
13617   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13618   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13619
13620   // Extract the RHS vectors
13621   SDValue RHS = Op.getOperand(1);
13622   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13623   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13624
13625   // Issue the operation on the smaller types and concatenate the result back
13626   MVT EltVT = VT.getVectorElementType();
13627   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13628   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13629                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13630                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13631 }
13632
13633 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13634   SDValue Op0 = Op.getOperand(0);
13635   SDValue Op1 = Op.getOperand(1);
13636   SDValue CC = Op.getOperand(2);
13637   MVT VT = Op.getSimpleValueType();
13638   SDLoc dl(Op);
13639
13640   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13641          "Unexpected type for boolean compare operation");
13642   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13643   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13644                                DAG.getConstant(-1, dl, VT));
13645   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13646                                DAG.getConstant(-1, dl, VT));
13647   switch (SetCCOpcode) {
13648   default: llvm_unreachable("Unexpected SETCC condition");
13649   case ISD::SETEQ:
13650     // (x == y) -> ~(x ^ y)
13651     return DAG.getNode(ISD::XOR, dl, VT,
13652                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13653                        DAG.getConstant(-1, dl, VT));
13654   case ISD::SETNE:
13655     // (x != y) -> (x ^ y)
13656     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13657   case ISD::SETUGT:
13658   case ISD::SETGT:
13659     // (x > y) -> (x & ~y)
13660     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13661   case ISD::SETULT:
13662   case ISD::SETLT:
13663     // (x < y) -> (~x & y)
13664     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13665   case ISD::SETULE:
13666   case ISD::SETLE:
13667     // (x <= y) -> (~x | y)
13668     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13669   case ISD::SETUGE:
13670   case ISD::SETGE:
13671     // (x >=y) -> (x | ~y)
13672     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13673   }
13674 }
13675
13676 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13677                                      const X86Subtarget *Subtarget) {
13678   SDValue Op0 = Op.getOperand(0);
13679   SDValue Op1 = Op.getOperand(1);
13680   SDValue CC = Op.getOperand(2);
13681   MVT VT = Op.getSimpleValueType();
13682   SDLoc dl(Op);
13683
13684   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13685          Op.getValueType().getScalarType() == MVT::i1 &&
13686          "Cannot set masked compare for this operation");
13687
13688   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13689   unsigned  Opc = 0;
13690   bool Unsigned = false;
13691   bool Swap = false;
13692   unsigned SSECC;
13693   switch (SetCCOpcode) {
13694   default: llvm_unreachable("Unexpected SETCC condition");
13695   case ISD::SETNE:  SSECC = 4; break;
13696   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13697   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13698   case ISD::SETLT:  Swap = true; //fall-through
13699   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13700   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13701   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13702   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13703   case ISD::SETULE: Unsigned = true; //fall-through
13704   case ISD::SETLE:  SSECC = 2; break;
13705   }
13706
13707   if (Swap)
13708     std::swap(Op0, Op1);
13709   if (Opc)
13710     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13711   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13712   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13713                      DAG.getConstant(SSECC, dl, MVT::i8));
13714 }
13715
13716 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13717 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13718 /// return an empty value.
13719 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13720 {
13721   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13722   if (!BV)
13723     return SDValue();
13724
13725   MVT VT = Op1.getSimpleValueType();
13726   MVT EVT = VT.getVectorElementType();
13727   unsigned n = VT.getVectorNumElements();
13728   SmallVector<SDValue, 8> ULTOp1;
13729
13730   for (unsigned i = 0; i < n; ++i) {
13731     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13732     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13733       return SDValue();
13734
13735     // Avoid underflow.
13736     APInt Val = Elt->getAPIntValue();
13737     if (Val == 0)
13738       return SDValue();
13739
13740     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13741   }
13742
13743   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13744 }
13745
13746 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13747                            SelectionDAG &DAG) {
13748   SDValue Op0 = Op.getOperand(0);
13749   SDValue Op1 = Op.getOperand(1);
13750   SDValue CC = Op.getOperand(2);
13751   MVT VT = Op.getSimpleValueType();
13752   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13753   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13754   SDLoc dl(Op);
13755
13756   if (isFP) {
13757 #ifndef NDEBUG
13758     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13759     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13760 #endif
13761
13762     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13763     unsigned Opc = X86ISD::CMPP;
13764     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13765       assert(VT.getVectorNumElements() <= 16);
13766       Opc = X86ISD::CMPM;
13767     }
13768     // In the two special cases we can't handle, emit two comparisons.
13769     if (SSECC == 8) {
13770       unsigned CC0, CC1;
13771       unsigned CombineOpc;
13772       if (SetCCOpcode == ISD::SETUEQ) {
13773         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13774       } else {
13775         assert(SetCCOpcode == ISD::SETONE);
13776         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13777       }
13778
13779       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13780                                  DAG.getConstant(CC0, dl, MVT::i8));
13781       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13782                                  DAG.getConstant(CC1, dl, MVT::i8));
13783       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13784     }
13785     // Handle all other FP comparisons here.
13786     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13787                        DAG.getConstant(SSECC, dl, MVT::i8));
13788   }
13789
13790   // Break 256-bit integer vector compare into smaller ones.
13791   if (VT.is256BitVector() && !Subtarget->hasInt256())
13792     return Lower256IntVSETCC(Op, DAG);
13793
13794   EVT OpVT = Op1.getValueType();
13795   if (OpVT.getVectorElementType() == MVT::i1)
13796     return LowerBoolVSETCC_AVX512(Op, DAG);
13797
13798   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13799   if (Subtarget->hasAVX512()) {
13800     if (Op1.getValueType().is512BitVector() ||
13801         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13802         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13803       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13804
13805     // In AVX-512 architecture setcc returns mask with i1 elements,
13806     // But there is no compare instruction for i8 and i16 elements in KNL.
13807     // We are not talking about 512-bit operands in this case, these
13808     // types are illegal.
13809     if (MaskResult &&
13810         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13811          OpVT.getVectorElementType().getSizeInBits() >= 8))
13812       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13813                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13814   }
13815
13816   // We are handling one of the integer comparisons here.  Since SSE only has
13817   // GT and EQ comparisons for integer, swapping operands and multiple
13818   // operations may be required for some comparisons.
13819   unsigned Opc;
13820   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13821   bool Subus = false;
13822
13823   switch (SetCCOpcode) {
13824   default: llvm_unreachable("Unexpected SETCC condition");
13825   case ISD::SETNE:  Invert = true;
13826   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13827   case ISD::SETLT:  Swap = true;
13828   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13829   case ISD::SETGE:  Swap = true;
13830   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13831                     Invert = true; break;
13832   case ISD::SETULT: Swap = true;
13833   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13834                     FlipSigns = true; break;
13835   case ISD::SETUGE: Swap = true;
13836   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13837                     FlipSigns = true; Invert = true; break;
13838   }
13839
13840   // Special case: Use min/max operations for SETULE/SETUGE
13841   MVT VET = VT.getVectorElementType();
13842   bool hasMinMax =
13843        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13844     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13845
13846   if (hasMinMax) {
13847     switch (SetCCOpcode) {
13848     default: break;
13849     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13850     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13851     }
13852
13853     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13854   }
13855
13856   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13857   if (!MinMax && hasSubus) {
13858     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13859     // Op0 u<= Op1:
13860     //   t = psubus Op0, Op1
13861     //   pcmpeq t, <0..0>
13862     switch (SetCCOpcode) {
13863     default: break;
13864     case ISD::SETULT: {
13865       // If the comparison is against a constant we can turn this into a
13866       // setule.  With psubus, setule does not require a swap.  This is
13867       // beneficial because the constant in the register is no longer
13868       // destructed as the destination so it can be hoisted out of a loop.
13869       // Only do this pre-AVX since vpcmp* is no longer destructive.
13870       if (Subtarget->hasAVX())
13871         break;
13872       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13873       if (ULEOp1.getNode()) {
13874         Op1 = ULEOp1;
13875         Subus = true; Invert = false; Swap = false;
13876       }
13877       break;
13878     }
13879     // Psubus is better than flip-sign because it requires no inversion.
13880     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13881     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13882     }
13883
13884     if (Subus) {
13885       Opc = X86ISD::SUBUS;
13886       FlipSigns = false;
13887     }
13888   }
13889
13890   if (Swap)
13891     std::swap(Op0, Op1);
13892
13893   // Check that the operation in question is available (most are plain SSE2,
13894   // but PCMPGTQ and PCMPEQQ have different requirements).
13895   if (VT == MVT::v2i64) {
13896     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13897       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13898
13899       // First cast everything to the right type.
13900       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13901       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13902
13903       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13904       // bits of the inputs before performing those operations. The lower
13905       // compare is always unsigned.
13906       SDValue SB;
13907       if (FlipSigns) {
13908         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13909       } else {
13910         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13911         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13912         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13913                          Sign, Zero, Sign, Zero);
13914       }
13915       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13916       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13917
13918       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13919       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13920       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13921
13922       // Create masks for only the low parts/high parts of the 64 bit integers.
13923       static const int MaskHi[] = { 1, 1, 3, 3 };
13924       static const int MaskLo[] = { 0, 0, 2, 2 };
13925       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13926       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13927       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13928
13929       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13930       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13931
13932       if (Invert)
13933         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13934
13935       return DAG.getBitcast(VT, Result);
13936     }
13937
13938     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13939       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13940       // pcmpeqd + pshufd + pand.
13941       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13942
13943       // First cast everything to the right type.
13944       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13945       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13946
13947       // Do the compare.
13948       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13949
13950       // Make sure the lower and upper halves are both all-ones.
13951       static const int Mask[] = { 1, 0, 3, 2 };
13952       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13953       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13954
13955       if (Invert)
13956         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13957
13958       return DAG.getBitcast(VT, Result);
13959     }
13960   }
13961
13962   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13963   // bits of the inputs before performing those operations.
13964   if (FlipSigns) {
13965     EVT EltVT = VT.getVectorElementType();
13966     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13967                                  VT);
13968     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13969     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13970   }
13971
13972   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13973
13974   // If the logical-not of the result is required, perform that now.
13975   if (Invert)
13976     Result = DAG.getNOT(dl, Result, VT);
13977
13978   if (MinMax)
13979     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13980
13981   if (Subus)
13982     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13983                          getZeroVector(VT, Subtarget, DAG, dl));
13984
13985   return Result;
13986 }
13987
13988 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13989
13990   MVT VT = Op.getSimpleValueType();
13991
13992   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13993
13994   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13995          && "SetCC type must be 8-bit or 1-bit integer");
13996   SDValue Op0 = Op.getOperand(0);
13997   SDValue Op1 = Op.getOperand(1);
13998   SDLoc dl(Op);
13999   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14000
14001   // Optimize to BT if possible.
14002   // Lower (X & (1 << N)) == 0 to BT(X, N).
14003   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14004   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14005   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14006       Op1.getOpcode() == ISD::Constant &&
14007       cast<ConstantSDNode>(Op1)->isNullValue() &&
14008       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14009     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14010     if (NewSetCC.getNode()) {
14011       if (VT == MVT::i1)
14012         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14013       return NewSetCC;
14014     }
14015   }
14016
14017   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14018   // these.
14019   if (Op1.getOpcode() == ISD::Constant &&
14020       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14021        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14022       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14023
14024     // If the input is a setcc, then reuse the input setcc or use a new one with
14025     // the inverted condition.
14026     if (Op0.getOpcode() == X86ISD::SETCC) {
14027       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14028       bool Invert = (CC == ISD::SETNE) ^
14029         cast<ConstantSDNode>(Op1)->isNullValue();
14030       if (!Invert)
14031         return Op0;
14032
14033       CCode = X86::GetOppositeBranchCondition(CCode);
14034       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14035                                   DAG.getConstant(CCode, dl, MVT::i8),
14036                                   Op0.getOperand(1));
14037       if (VT == MVT::i1)
14038         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14039       return SetCC;
14040     }
14041   }
14042   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14043       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14044       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14045
14046     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14047     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14048   }
14049
14050   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14051   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14052   if (X86CC == X86::COND_INVALID)
14053     return SDValue();
14054
14055   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14056   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14057   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14058                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14059   if (VT == MVT::i1)
14060     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14061   return SetCC;
14062 }
14063
14064 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14065 static bool isX86LogicalCmp(SDValue Op) {
14066   unsigned Opc = Op.getNode()->getOpcode();
14067   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14068       Opc == X86ISD::SAHF)
14069     return true;
14070   if (Op.getResNo() == 1 &&
14071       (Opc == X86ISD::ADD ||
14072        Opc == X86ISD::SUB ||
14073        Opc == X86ISD::ADC ||
14074        Opc == X86ISD::SBB ||
14075        Opc == X86ISD::SMUL ||
14076        Opc == X86ISD::UMUL ||
14077        Opc == X86ISD::INC ||
14078        Opc == X86ISD::DEC ||
14079        Opc == X86ISD::OR ||
14080        Opc == X86ISD::XOR ||
14081        Opc == X86ISD::AND))
14082     return true;
14083
14084   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14085     return true;
14086
14087   return false;
14088 }
14089
14090 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14091   if (V.getOpcode() != ISD::TRUNCATE)
14092     return false;
14093
14094   SDValue VOp0 = V.getOperand(0);
14095   unsigned InBits = VOp0.getValueSizeInBits();
14096   unsigned Bits = V.getValueSizeInBits();
14097   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14098 }
14099
14100 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14101   bool addTest = true;
14102   SDValue Cond  = Op.getOperand(0);
14103   SDValue Op1 = Op.getOperand(1);
14104   SDValue Op2 = Op.getOperand(2);
14105   SDLoc DL(Op);
14106   EVT VT = Op1.getValueType();
14107   SDValue CC;
14108
14109   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14110   // are available or VBLENDV if AVX is available.
14111   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14112   if (Cond.getOpcode() == ISD::SETCC &&
14113       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14114        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14115       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14116     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14117     int SSECC = translateX86FSETCC(
14118         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14119
14120     if (SSECC != 8) {
14121       if (Subtarget->hasAVX512()) {
14122         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14123                                   DAG.getConstant(SSECC, DL, MVT::i8));
14124         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14125       }
14126
14127       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14128                                 DAG.getConstant(SSECC, DL, MVT::i8));
14129
14130       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14131       // of 3 logic instructions for size savings and potentially speed.
14132       // Unfortunately, there is no scalar form of VBLENDV.
14133
14134       // If either operand is a constant, don't try this. We can expect to
14135       // optimize away at least one of the logic instructions later in that
14136       // case, so that sequence would be faster than a variable blend.
14137
14138       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14139       // uses XMM0 as the selection register. That may need just as many
14140       // instructions as the AND/ANDN/OR sequence due to register moves, so
14141       // don't bother.
14142
14143       if (Subtarget->hasAVX() &&
14144           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14145
14146         // Convert to vectors, do a VSELECT, and convert back to scalar.
14147         // All of the conversions should be optimized away.
14148
14149         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14150         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14151         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14152         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14153
14154         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14155         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14156
14157         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14158
14159         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14160                            VSel, DAG.getIntPtrConstant(0, DL));
14161       }
14162       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14163       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14164       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14165     }
14166   }
14167
14168   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14169     SDValue Op1Scalar;
14170     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14171       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14172     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14173       Op1Scalar = Op1.getOperand(0);
14174     SDValue Op2Scalar;
14175     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14176       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14177     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14178       Op2Scalar = Op2.getOperand(0);
14179     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14180       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14181                                       Op1Scalar.getValueType(),
14182                                       Cond, Op1Scalar, Op2Scalar);
14183       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14184         return DAG.getBitcast(VT, newSelect);
14185       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14186       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14187                          DAG.getIntPtrConstant(0, DL));
14188     }
14189   }
14190
14191   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14192     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14193     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14194                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14195     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14196                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14197     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14198                                     Cond, Op1, Op2);
14199     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14200   }
14201
14202   if (Cond.getOpcode() == ISD::SETCC) {
14203     SDValue NewCond = LowerSETCC(Cond, DAG);
14204     if (NewCond.getNode())
14205       Cond = NewCond;
14206   }
14207
14208   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14209   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14210   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14211   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14212   if (Cond.getOpcode() == X86ISD::SETCC &&
14213       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14214       isZero(Cond.getOperand(1).getOperand(1))) {
14215     SDValue Cmp = Cond.getOperand(1);
14216
14217     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14218
14219     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14220         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14221       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14222
14223       SDValue CmpOp0 = Cmp.getOperand(0);
14224       // Apply further optimizations for special cases
14225       // (select (x != 0), -1, 0) -> neg & sbb
14226       // (select (x == 0), 0, -1) -> neg & sbb
14227       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14228         if (YC->isNullValue() &&
14229             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14230           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14231           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14232                                     DAG.getConstant(0, DL,
14233                                                     CmpOp0.getValueType()),
14234                                     CmpOp0);
14235           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14236                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14237                                     SDValue(Neg.getNode(), 1));
14238           return Res;
14239         }
14240
14241       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14242                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14243       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14244
14245       SDValue Res =   // Res = 0 or -1.
14246         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14247                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14248
14249       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14250         Res = DAG.getNOT(DL, Res, Res.getValueType());
14251
14252       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14253       if (!N2C || !N2C->isNullValue())
14254         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14255       return Res;
14256     }
14257   }
14258
14259   // Look past (and (setcc_carry (cmp ...)), 1).
14260   if (Cond.getOpcode() == ISD::AND &&
14261       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14262     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14263     if (C && C->getAPIntValue() == 1)
14264       Cond = Cond.getOperand(0);
14265   }
14266
14267   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14268   // setting operand in place of the X86ISD::SETCC.
14269   unsigned CondOpcode = Cond.getOpcode();
14270   if (CondOpcode == X86ISD::SETCC ||
14271       CondOpcode == X86ISD::SETCC_CARRY) {
14272     CC = Cond.getOperand(0);
14273
14274     SDValue Cmp = Cond.getOperand(1);
14275     unsigned Opc = Cmp.getOpcode();
14276     MVT VT = Op.getSimpleValueType();
14277
14278     bool IllegalFPCMov = false;
14279     if (VT.isFloatingPoint() && !VT.isVector() &&
14280         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14281       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14282
14283     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14284         Opc == X86ISD::BT) { // FIXME
14285       Cond = Cmp;
14286       addTest = false;
14287     }
14288   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14289              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14290              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14291               Cond.getOperand(0).getValueType() != MVT::i8)) {
14292     SDValue LHS = Cond.getOperand(0);
14293     SDValue RHS = Cond.getOperand(1);
14294     unsigned X86Opcode;
14295     unsigned X86Cond;
14296     SDVTList VTs;
14297     switch (CondOpcode) {
14298     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14299     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14300     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14301     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14302     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14303     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14304     default: llvm_unreachable("unexpected overflowing operator");
14305     }
14306     if (CondOpcode == ISD::UMULO)
14307       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14308                           MVT::i32);
14309     else
14310       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14311
14312     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14313
14314     if (CondOpcode == ISD::UMULO)
14315       Cond = X86Op.getValue(2);
14316     else
14317       Cond = X86Op.getValue(1);
14318
14319     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14320     addTest = false;
14321   }
14322
14323   if (addTest) {
14324     // Look past the truncate if the high bits are known zero.
14325     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14326       Cond = Cond.getOperand(0);
14327
14328     // We know the result of AND is compared against zero. Try to match
14329     // it to BT.
14330     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14331       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14332       if (NewSetCC.getNode()) {
14333         CC = NewSetCC.getOperand(0);
14334         Cond = NewSetCC.getOperand(1);
14335         addTest = false;
14336       }
14337     }
14338   }
14339
14340   if (addTest) {
14341     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14342     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14343   }
14344
14345   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14346   // a <  b ?  0 : -1 -> RES = setcc_carry
14347   // a >= b ? -1 :  0 -> RES = setcc_carry
14348   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14349   if (Cond.getOpcode() == X86ISD::SUB) {
14350     Cond = ConvertCmpIfNecessary(Cond, DAG);
14351     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14352
14353     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14354         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14355       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14356                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14357                                 Cond);
14358       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14359         return DAG.getNOT(DL, Res, Res.getValueType());
14360       return Res;
14361     }
14362   }
14363
14364   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14365   // widen the cmov and push the truncate through. This avoids introducing a new
14366   // branch during isel and doesn't add any extensions.
14367   if (Op.getValueType() == MVT::i8 &&
14368       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14369     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14370     if (T1.getValueType() == T2.getValueType() &&
14371         // Blacklist CopyFromReg to avoid partial register stalls.
14372         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14373       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14374       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14375       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14376     }
14377   }
14378
14379   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14380   // condition is true.
14381   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14382   SDValue Ops[] = { Op2, Op1, CC, Cond };
14383   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14384 }
14385
14386 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14387                                        const X86Subtarget *Subtarget,
14388                                        SelectionDAG &DAG) {
14389   MVT VT = Op->getSimpleValueType(0);
14390   SDValue In = Op->getOperand(0);
14391   MVT InVT = In.getSimpleValueType();
14392   MVT VTElt = VT.getVectorElementType();
14393   MVT InVTElt = InVT.getVectorElementType();
14394   SDLoc dl(Op);
14395
14396   // SKX processor
14397   if ((InVTElt == MVT::i1) &&
14398       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14399         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14400
14401        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14402         VTElt.getSizeInBits() <= 16)) ||
14403
14404        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14405         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14406
14407        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14408         VTElt.getSizeInBits() >= 32))))
14409     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14410
14411   unsigned int NumElts = VT.getVectorNumElements();
14412
14413   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14414     return SDValue();
14415
14416   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14417     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14418       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14419     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14420   }
14421
14422   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14423   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14424   SDValue NegOne =
14425    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14426                    ExtVT);
14427   SDValue Zero =
14428    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14429
14430   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14431   if (VT.is512BitVector())
14432     return V;
14433   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14434 }
14435
14436 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14437                                              const X86Subtarget *Subtarget,
14438                                              SelectionDAG &DAG) {
14439   SDValue In = Op->getOperand(0);
14440   MVT VT = Op->getSimpleValueType(0);
14441   MVT InVT = In.getSimpleValueType();
14442   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14443
14444   MVT InSVT = InVT.getScalarType();
14445   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14446
14447   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14448     return SDValue();
14449   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14450     return SDValue();
14451
14452   SDLoc dl(Op);
14453
14454   // SSE41 targets can use the pmovsx* instructions directly.
14455   if (Subtarget->hasSSE41())
14456     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14457
14458   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14459   SDValue Curr = In;
14460   MVT CurrVT = InVT;
14461
14462   // As SRAI is only available on i16/i32 types, we expand only up to i32
14463   // and handle i64 separately.
14464   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14465     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14466     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14467     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14468     Curr = DAG.getBitcast(CurrVT, Curr);
14469   }
14470
14471   SDValue SignExt = Curr;
14472   if (CurrVT != InVT) {
14473     unsigned SignExtShift =
14474         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14475     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14476                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14477   }
14478
14479   if (CurrVT == VT)
14480     return SignExt;
14481
14482   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14483     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14484                                DAG.getConstant(31, dl, MVT::i8));
14485     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14486     return DAG.getBitcast(VT, Ext);
14487   }
14488
14489   return SDValue();
14490 }
14491
14492 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14493                                 SelectionDAG &DAG) {
14494   MVT VT = Op->getSimpleValueType(0);
14495   SDValue In = Op->getOperand(0);
14496   MVT InVT = In.getSimpleValueType();
14497   SDLoc dl(Op);
14498
14499   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14500     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14501
14502   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14503       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14504       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14505     return SDValue();
14506
14507   if (Subtarget->hasInt256())
14508     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14509
14510   // Optimize vectors in AVX mode
14511   // Sign extend  v8i16 to v8i32 and
14512   //              v4i32 to v4i64
14513   //
14514   // Divide input vector into two parts
14515   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14516   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14517   // concat the vectors to original VT
14518
14519   unsigned NumElems = InVT.getVectorNumElements();
14520   SDValue Undef = DAG.getUNDEF(InVT);
14521
14522   SmallVector<int,8> ShufMask1(NumElems, -1);
14523   for (unsigned i = 0; i != NumElems/2; ++i)
14524     ShufMask1[i] = i;
14525
14526   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14527
14528   SmallVector<int,8> ShufMask2(NumElems, -1);
14529   for (unsigned i = 0; i != NumElems/2; ++i)
14530     ShufMask2[i] = i + NumElems/2;
14531
14532   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14533
14534   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14535                                 VT.getVectorNumElements()/2);
14536
14537   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14538   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14539
14540   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14541 }
14542
14543 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14544 // may emit an illegal shuffle but the expansion is still better than scalar
14545 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14546 // we'll emit a shuffle and a arithmetic shift.
14547 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14548 // TODO: It is possible to support ZExt by zeroing the undef values during
14549 // the shuffle phase or after the shuffle.
14550 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14551                                  SelectionDAG &DAG) {
14552   MVT RegVT = Op.getSimpleValueType();
14553   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14554   assert(RegVT.isInteger() &&
14555          "We only custom lower integer vector sext loads.");
14556
14557   // Nothing useful we can do without SSE2 shuffles.
14558   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14559
14560   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14561   SDLoc dl(Ld);
14562   EVT MemVT = Ld->getMemoryVT();
14563   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14564   unsigned RegSz = RegVT.getSizeInBits();
14565
14566   ISD::LoadExtType Ext = Ld->getExtensionType();
14567
14568   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14569          && "Only anyext and sext are currently implemented.");
14570   assert(MemVT != RegVT && "Cannot extend to the same type");
14571   assert(MemVT.isVector() && "Must load a vector from memory");
14572
14573   unsigned NumElems = RegVT.getVectorNumElements();
14574   unsigned MemSz = MemVT.getSizeInBits();
14575   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14576
14577   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14578     // The only way in which we have a legal 256-bit vector result but not the
14579     // integer 256-bit operations needed to directly lower a sextload is if we
14580     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14581     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14582     // correctly legalized. We do this late to allow the canonical form of
14583     // sextload to persist throughout the rest of the DAG combiner -- it wants
14584     // to fold together any extensions it can, and so will fuse a sign_extend
14585     // of an sextload into a sextload targeting a wider value.
14586     SDValue Load;
14587     if (MemSz == 128) {
14588       // Just switch this to a normal load.
14589       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14590                                        "it must be a legal 128-bit vector "
14591                                        "type!");
14592       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14593                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14594                   Ld->isInvariant(), Ld->getAlignment());
14595     } else {
14596       assert(MemSz < 128 &&
14597              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14598       // Do an sext load to a 128-bit vector type. We want to use the same
14599       // number of elements, but elements half as wide. This will end up being
14600       // recursively lowered by this routine, but will succeed as we definitely
14601       // have all the necessary features if we're using AVX1.
14602       EVT HalfEltVT =
14603           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14604       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14605       Load =
14606           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14607                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14608                          Ld->isNonTemporal(), Ld->isInvariant(),
14609                          Ld->getAlignment());
14610     }
14611
14612     // Replace chain users with the new chain.
14613     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14614     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14615
14616     // Finally, do a normal sign-extend to the desired register.
14617     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14618   }
14619
14620   // All sizes must be a power of two.
14621   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14622          "Non-power-of-two elements are not custom lowered!");
14623
14624   // Attempt to load the original value using scalar loads.
14625   // Find the largest scalar type that divides the total loaded size.
14626   MVT SclrLoadTy = MVT::i8;
14627   for (MVT Tp : MVT::integer_valuetypes()) {
14628     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14629       SclrLoadTy = Tp;
14630     }
14631   }
14632
14633   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14634   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14635       (64 <= MemSz))
14636     SclrLoadTy = MVT::f64;
14637
14638   // Calculate the number of scalar loads that we need to perform
14639   // in order to load our vector from memory.
14640   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14641
14642   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14643          "Can only lower sext loads with a single scalar load!");
14644
14645   unsigned loadRegZize = RegSz;
14646   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14647     loadRegZize = 128;
14648
14649   // Represent our vector as a sequence of elements which are the
14650   // largest scalar that we can load.
14651   EVT LoadUnitVecVT = EVT::getVectorVT(
14652       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14653
14654   // Represent the data using the same element type that is stored in
14655   // memory. In practice, we ''widen'' MemVT.
14656   EVT WideVecVT =
14657       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14658                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14659
14660   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14661          "Invalid vector type");
14662
14663   // We can't shuffle using an illegal type.
14664   assert(TLI.isTypeLegal(WideVecVT) &&
14665          "We only lower types that form legal widened vector types");
14666
14667   SmallVector<SDValue, 8> Chains;
14668   SDValue Ptr = Ld->getBasePtr();
14669   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14670                                       TLI.getPointerTy(DAG.getDataLayout()));
14671   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14672
14673   for (unsigned i = 0; i < NumLoads; ++i) {
14674     // Perform a single load.
14675     SDValue ScalarLoad =
14676         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14677                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14678                     Ld->getAlignment());
14679     Chains.push_back(ScalarLoad.getValue(1));
14680     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14681     // another round of DAGCombining.
14682     if (i == 0)
14683       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14684     else
14685       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14686                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14687
14688     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14689   }
14690
14691   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14692
14693   // Bitcast the loaded value to a vector of the original element type, in
14694   // the size of the target vector type.
14695   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14696   unsigned SizeRatio = RegSz / MemSz;
14697
14698   if (Ext == ISD::SEXTLOAD) {
14699     // If we have SSE4.1, we can directly emit a VSEXT node.
14700     if (Subtarget->hasSSE41()) {
14701       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14702       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14703       return Sext;
14704     }
14705
14706     // Otherwise we'll shuffle the small elements in the high bits of the
14707     // larger type and perform an arithmetic shift. If the shift is not legal
14708     // it's better to scalarize.
14709     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14710            "We can't implement a sext load without an arithmetic right shift!");
14711
14712     // Redistribute the loaded elements into the different locations.
14713     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14714     for (unsigned i = 0; i != NumElems; ++i)
14715       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14716
14717     SDValue Shuff = DAG.getVectorShuffle(
14718         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14719
14720     Shuff = DAG.getBitcast(RegVT, Shuff);
14721
14722     // Build the arithmetic shift.
14723     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14724                    MemVT.getVectorElementType().getSizeInBits();
14725     Shuff =
14726         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14727                     DAG.getConstant(Amt, dl, RegVT));
14728
14729     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14730     return Shuff;
14731   }
14732
14733   // Redistribute the loaded elements into the different locations.
14734   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14735   for (unsigned i = 0; i != NumElems; ++i)
14736     ShuffleVec[i * SizeRatio] = i;
14737
14738   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14739                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14740
14741   // Bitcast to the requested type.
14742   Shuff = DAG.getBitcast(RegVT, Shuff);
14743   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14744   return Shuff;
14745 }
14746
14747 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14748 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14749 // from the AND / OR.
14750 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14751   Opc = Op.getOpcode();
14752   if (Opc != ISD::OR && Opc != ISD::AND)
14753     return false;
14754   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14755           Op.getOperand(0).hasOneUse() &&
14756           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14757           Op.getOperand(1).hasOneUse());
14758 }
14759
14760 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14761 // 1 and that the SETCC node has a single use.
14762 static bool isXor1OfSetCC(SDValue Op) {
14763   if (Op.getOpcode() != ISD::XOR)
14764     return false;
14765   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14766   if (N1C && N1C->getAPIntValue() == 1) {
14767     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14768       Op.getOperand(0).hasOneUse();
14769   }
14770   return false;
14771 }
14772
14773 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14774   bool addTest = true;
14775   SDValue Chain = Op.getOperand(0);
14776   SDValue Cond  = Op.getOperand(1);
14777   SDValue Dest  = Op.getOperand(2);
14778   SDLoc dl(Op);
14779   SDValue CC;
14780   bool Inverted = false;
14781
14782   if (Cond.getOpcode() == ISD::SETCC) {
14783     // Check for setcc([su]{add,sub,mul}o == 0).
14784     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14785         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14786         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14787         Cond.getOperand(0).getResNo() == 1 &&
14788         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14789          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14790          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14791          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14792          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14793          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14794       Inverted = true;
14795       Cond = Cond.getOperand(0);
14796     } else {
14797       SDValue NewCond = LowerSETCC(Cond, DAG);
14798       if (NewCond.getNode())
14799         Cond = NewCond;
14800     }
14801   }
14802 #if 0
14803   // FIXME: LowerXALUO doesn't handle these!!
14804   else if (Cond.getOpcode() == X86ISD::ADD  ||
14805            Cond.getOpcode() == X86ISD::SUB  ||
14806            Cond.getOpcode() == X86ISD::SMUL ||
14807            Cond.getOpcode() == X86ISD::UMUL)
14808     Cond = LowerXALUO(Cond, DAG);
14809 #endif
14810
14811   // Look pass (and (setcc_carry (cmp ...)), 1).
14812   if (Cond.getOpcode() == ISD::AND &&
14813       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14814     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14815     if (C && C->getAPIntValue() == 1)
14816       Cond = Cond.getOperand(0);
14817   }
14818
14819   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14820   // setting operand in place of the X86ISD::SETCC.
14821   unsigned CondOpcode = Cond.getOpcode();
14822   if (CondOpcode == X86ISD::SETCC ||
14823       CondOpcode == X86ISD::SETCC_CARRY) {
14824     CC = Cond.getOperand(0);
14825
14826     SDValue Cmp = Cond.getOperand(1);
14827     unsigned Opc = Cmp.getOpcode();
14828     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14829     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14830       Cond = Cmp;
14831       addTest = false;
14832     } else {
14833       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14834       default: break;
14835       case X86::COND_O:
14836       case X86::COND_B:
14837         // These can only come from an arithmetic instruction with overflow,
14838         // e.g. SADDO, UADDO.
14839         Cond = Cond.getNode()->getOperand(1);
14840         addTest = false;
14841         break;
14842       }
14843     }
14844   }
14845   CondOpcode = Cond.getOpcode();
14846   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14847       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14848       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14849        Cond.getOperand(0).getValueType() != MVT::i8)) {
14850     SDValue LHS = Cond.getOperand(0);
14851     SDValue RHS = Cond.getOperand(1);
14852     unsigned X86Opcode;
14853     unsigned X86Cond;
14854     SDVTList VTs;
14855     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14856     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14857     // X86ISD::INC).
14858     switch (CondOpcode) {
14859     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14860     case ISD::SADDO:
14861       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14862         if (C->isOne()) {
14863           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14864           break;
14865         }
14866       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14867     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14868     case ISD::SSUBO:
14869       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14870         if (C->isOne()) {
14871           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14872           break;
14873         }
14874       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14875     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14876     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14877     default: llvm_unreachable("unexpected overflowing operator");
14878     }
14879     if (Inverted)
14880       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14881     if (CondOpcode == ISD::UMULO)
14882       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14883                           MVT::i32);
14884     else
14885       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14886
14887     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14888
14889     if (CondOpcode == ISD::UMULO)
14890       Cond = X86Op.getValue(2);
14891     else
14892       Cond = X86Op.getValue(1);
14893
14894     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14895     addTest = false;
14896   } else {
14897     unsigned CondOpc;
14898     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14899       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14900       if (CondOpc == ISD::OR) {
14901         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14902         // two branches instead of an explicit OR instruction with a
14903         // separate test.
14904         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14905             isX86LogicalCmp(Cmp)) {
14906           CC = Cond.getOperand(0).getOperand(0);
14907           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14908                               Chain, Dest, CC, Cmp);
14909           CC = Cond.getOperand(1).getOperand(0);
14910           Cond = Cmp;
14911           addTest = false;
14912         }
14913       } else { // ISD::AND
14914         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14915         // two branches instead of an explicit AND instruction with a
14916         // separate test. However, we only do this if this block doesn't
14917         // have a fall-through edge, because this requires an explicit
14918         // jmp when the condition is false.
14919         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14920             isX86LogicalCmp(Cmp) &&
14921             Op.getNode()->hasOneUse()) {
14922           X86::CondCode CCode =
14923             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14924           CCode = X86::GetOppositeBranchCondition(CCode);
14925           CC = DAG.getConstant(CCode, dl, MVT::i8);
14926           SDNode *User = *Op.getNode()->use_begin();
14927           // Look for an unconditional branch following this conditional branch.
14928           // We need this because we need to reverse the successors in order
14929           // to implement FCMP_OEQ.
14930           if (User->getOpcode() == ISD::BR) {
14931             SDValue FalseBB = User->getOperand(1);
14932             SDNode *NewBR =
14933               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14934             assert(NewBR == User);
14935             (void)NewBR;
14936             Dest = FalseBB;
14937
14938             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14939                                 Chain, Dest, CC, Cmp);
14940             X86::CondCode CCode =
14941               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14942             CCode = X86::GetOppositeBranchCondition(CCode);
14943             CC = DAG.getConstant(CCode, dl, MVT::i8);
14944             Cond = Cmp;
14945             addTest = false;
14946           }
14947         }
14948       }
14949     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14950       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14951       // It should be transformed during dag combiner except when the condition
14952       // is set by a arithmetics with overflow node.
14953       X86::CondCode CCode =
14954         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14955       CCode = X86::GetOppositeBranchCondition(CCode);
14956       CC = DAG.getConstant(CCode, dl, MVT::i8);
14957       Cond = Cond.getOperand(0).getOperand(1);
14958       addTest = false;
14959     } else if (Cond.getOpcode() == ISD::SETCC &&
14960                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14961       // For FCMP_OEQ, we can emit
14962       // two branches instead of an explicit AND instruction with a
14963       // separate test. However, we only do this if this block doesn't
14964       // have a fall-through edge, because this requires an explicit
14965       // jmp when the condition is false.
14966       if (Op.getNode()->hasOneUse()) {
14967         SDNode *User = *Op.getNode()->use_begin();
14968         // Look for an unconditional branch following this conditional branch.
14969         // We need this because we need to reverse the successors in order
14970         // to implement FCMP_OEQ.
14971         if (User->getOpcode() == ISD::BR) {
14972           SDValue FalseBB = User->getOperand(1);
14973           SDNode *NewBR =
14974             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14975           assert(NewBR == User);
14976           (void)NewBR;
14977           Dest = FalseBB;
14978
14979           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14980                                     Cond.getOperand(0), Cond.getOperand(1));
14981           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14982           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14983           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14984                               Chain, Dest, CC, Cmp);
14985           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14986           Cond = Cmp;
14987           addTest = false;
14988         }
14989       }
14990     } else if (Cond.getOpcode() == ISD::SETCC &&
14991                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14992       // For FCMP_UNE, we can emit
14993       // two branches instead of an explicit AND instruction with a
14994       // separate test. However, we only do this if this block doesn't
14995       // have a fall-through edge, because this requires an explicit
14996       // jmp when the condition is false.
14997       if (Op.getNode()->hasOneUse()) {
14998         SDNode *User = *Op.getNode()->use_begin();
14999         // Look for an unconditional branch following this conditional branch.
15000         // We need this because we need to reverse the successors in order
15001         // to implement FCMP_UNE.
15002         if (User->getOpcode() == ISD::BR) {
15003           SDValue FalseBB = User->getOperand(1);
15004           SDNode *NewBR =
15005             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15006           assert(NewBR == User);
15007           (void)NewBR;
15008
15009           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15010                                     Cond.getOperand(0), Cond.getOperand(1));
15011           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15012           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15013           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15014                               Chain, Dest, CC, Cmp);
15015           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15016           Cond = Cmp;
15017           addTest = false;
15018           Dest = FalseBB;
15019         }
15020       }
15021     }
15022   }
15023
15024   if (addTest) {
15025     // Look pass the truncate if the high bits are known zero.
15026     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15027         Cond = Cond.getOperand(0);
15028
15029     // We know the result of AND is compared against zero. Try to match
15030     // it to BT.
15031     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15032       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15033       if (NewSetCC.getNode()) {
15034         CC = NewSetCC.getOperand(0);
15035         Cond = NewSetCC.getOperand(1);
15036         addTest = false;
15037       }
15038     }
15039   }
15040
15041   if (addTest) {
15042     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15043     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15044     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15045   }
15046   Cond = ConvertCmpIfNecessary(Cond, DAG);
15047   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15048                      Chain, Dest, CC, Cond);
15049 }
15050
15051 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15052 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15053 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15054 // that the guard pages used by the OS virtual memory manager are allocated in
15055 // correct sequence.
15056 SDValue
15057 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15058                                            SelectionDAG &DAG) const {
15059   MachineFunction &MF = DAG.getMachineFunction();
15060   bool SplitStack = MF.shouldSplitStack();
15061   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15062                SplitStack;
15063   SDLoc dl(Op);
15064
15065   if (!Lower) {
15066     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15067     SDNode* Node = Op.getNode();
15068
15069     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15070     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15071         " not tell us which reg is the stack pointer!");
15072     EVT VT = Node->getValueType(0);
15073     SDValue Tmp1 = SDValue(Node, 0);
15074     SDValue Tmp2 = SDValue(Node, 1);
15075     SDValue Tmp3 = Node->getOperand(2);
15076     SDValue Chain = Tmp1.getOperand(0);
15077
15078     // Chain the dynamic stack allocation so that it doesn't modify the stack
15079     // pointer when other instructions are using the stack.
15080     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15081         SDLoc(Node));
15082
15083     SDValue Size = Tmp2.getOperand(1);
15084     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15085     Chain = SP.getValue(1);
15086     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15087     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15088     unsigned StackAlign = TFI.getStackAlignment();
15089     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15090     if (Align > StackAlign)
15091       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15092           DAG.getConstant(-(uint64_t)Align, dl, VT));
15093     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15094
15095     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15096         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15097         SDLoc(Node));
15098
15099     SDValue Ops[2] = { Tmp1, Tmp2 };
15100     return DAG.getMergeValues(Ops, dl);
15101   }
15102
15103   // Get the inputs.
15104   SDValue Chain = Op.getOperand(0);
15105   SDValue Size  = Op.getOperand(1);
15106   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15107   EVT VT = Op.getNode()->getValueType(0);
15108
15109   bool Is64Bit = Subtarget->is64Bit();
15110   MVT SPTy = getPointerTy(DAG.getDataLayout());
15111
15112   if (SplitStack) {
15113     MachineRegisterInfo &MRI = MF.getRegInfo();
15114
15115     if (Is64Bit) {
15116       // The 64 bit implementation of segmented stacks needs to clobber both r10
15117       // r11. This makes it impossible to use it along with nested parameters.
15118       const Function *F = MF.getFunction();
15119
15120       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15121            I != E; ++I)
15122         if (I->hasNestAttr())
15123           report_fatal_error("Cannot use segmented stacks with functions that "
15124                              "have nested arguments.");
15125     }
15126
15127     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15128     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15129     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15130     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15131                                 DAG.getRegister(Vreg, SPTy));
15132     SDValue Ops1[2] = { Value, Chain };
15133     return DAG.getMergeValues(Ops1, dl);
15134   } else {
15135     SDValue Flag;
15136     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15137
15138     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15139     Flag = Chain.getValue(1);
15140     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15141
15142     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15143
15144     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15145     unsigned SPReg = RegInfo->getStackRegister();
15146     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15147     Chain = SP.getValue(1);
15148
15149     if (Align) {
15150       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15151                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15152       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15153     }
15154
15155     SDValue Ops1[2] = { SP, Chain };
15156     return DAG.getMergeValues(Ops1, dl);
15157   }
15158 }
15159
15160 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15161   MachineFunction &MF = DAG.getMachineFunction();
15162   auto PtrVT = getPointerTy(MF.getDataLayout());
15163   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15164
15165   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15166   SDLoc DL(Op);
15167
15168   if (!Subtarget->is64Bit() ||
15169       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15170     // vastart just stores the address of the VarArgsFrameIndex slot into the
15171     // memory location argument.
15172     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15173     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15174                         MachinePointerInfo(SV), false, false, 0);
15175   }
15176
15177   // __va_list_tag:
15178   //   gp_offset         (0 - 6 * 8)
15179   //   fp_offset         (48 - 48 + 8 * 16)
15180   //   overflow_arg_area (point to parameters coming in memory).
15181   //   reg_save_area
15182   SmallVector<SDValue, 8> MemOps;
15183   SDValue FIN = Op.getOperand(1);
15184   // Store gp_offset
15185   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15186                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15187                                                DL, MVT::i32),
15188                                FIN, MachinePointerInfo(SV), false, false, 0);
15189   MemOps.push_back(Store);
15190
15191   // Store fp_offset
15192   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15193   Store = DAG.getStore(Op.getOperand(0), DL,
15194                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15195                                        MVT::i32),
15196                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15197   MemOps.push_back(Store);
15198
15199   // Store ptr to overflow_arg_area
15200   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15201   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15202   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15203                        MachinePointerInfo(SV, 8),
15204                        false, false, 0);
15205   MemOps.push_back(Store);
15206
15207   // Store ptr to reg_save_area.
15208   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15209   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15210   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15211                        MachinePointerInfo(SV, 16), false, false, 0);
15212   MemOps.push_back(Store);
15213   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15214 }
15215
15216 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15217   assert(Subtarget->is64Bit() &&
15218          "LowerVAARG only handles 64-bit va_arg!");
15219   assert(Op.getNode()->getNumOperands() == 4);
15220
15221   MachineFunction &MF = DAG.getMachineFunction();
15222   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15223     // The Win64 ABI uses char* instead of a structure.
15224     return DAG.expandVAArg(Op.getNode());
15225
15226   SDValue Chain = Op.getOperand(0);
15227   SDValue SrcPtr = Op.getOperand(1);
15228   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15229   unsigned Align = Op.getConstantOperandVal(3);
15230   SDLoc dl(Op);
15231
15232   EVT ArgVT = Op.getNode()->getValueType(0);
15233   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15234   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15235   uint8_t ArgMode;
15236
15237   // Decide which area this value should be read from.
15238   // TODO: Implement the AMD64 ABI in its entirety. This simple
15239   // selection mechanism works only for the basic types.
15240   if (ArgVT == MVT::f80) {
15241     llvm_unreachable("va_arg for f80 not yet implemented");
15242   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15243     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15244   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15245     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15246   } else {
15247     llvm_unreachable("Unhandled argument type in LowerVAARG");
15248   }
15249
15250   if (ArgMode == 2) {
15251     // Sanity Check: Make sure using fp_offset makes sense.
15252     assert(!Subtarget->useSoftFloat() &&
15253            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15254            Subtarget->hasSSE1());
15255   }
15256
15257   // Insert VAARG_64 node into the DAG
15258   // VAARG_64 returns two values: Variable Argument Address, Chain
15259   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15260                        DAG.getConstant(ArgMode, dl, MVT::i8),
15261                        DAG.getConstant(Align, dl, MVT::i32)};
15262   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15263   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15264                                           VTs, InstOps, MVT::i64,
15265                                           MachinePointerInfo(SV),
15266                                           /*Align=*/0,
15267                                           /*Volatile=*/false,
15268                                           /*ReadMem=*/true,
15269                                           /*WriteMem=*/true);
15270   Chain = VAARG.getValue(1);
15271
15272   // Load the next argument and return it
15273   return DAG.getLoad(ArgVT, dl,
15274                      Chain,
15275                      VAARG,
15276                      MachinePointerInfo(),
15277                      false, false, false, 0);
15278 }
15279
15280 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15281                            SelectionDAG &DAG) {
15282   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15283   // where a va_list is still an i8*.
15284   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15285   if (Subtarget->isCallingConvWin64(
15286         DAG.getMachineFunction().getFunction()->getCallingConv()))
15287     // Probably a Win64 va_copy.
15288     return DAG.expandVACopy(Op.getNode());
15289
15290   SDValue Chain = Op.getOperand(0);
15291   SDValue DstPtr = Op.getOperand(1);
15292   SDValue SrcPtr = Op.getOperand(2);
15293   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15294   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15295   SDLoc DL(Op);
15296
15297   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15298                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15299                        false, false,
15300                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15301 }
15302
15303 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15304 // amount is a constant. Takes immediate version of shift as input.
15305 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15306                                           SDValue SrcOp, uint64_t ShiftAmt,
15307                                           SelectionDAG &DAG) {
15308   MVT ElementType = VT.getVectorElementType();
15309
15310   // Fold this packed shift into its first operand if ShiftAmt is 0.
15311   if (ShiftAmt == 0)
15312     return SrcOp;
15313
15314   // Check for ShiftAmt >= element width
15315   if (ShiftAmt >= ElementType.getSizeInBits()) {
15316     if (Opc == X86ISD::VSRAI)
15317       ShiftAmt = ElementType.getSizeInBits() - 1;
15318     else
15319       return DAG.getConstant(0, dl, VT);
15320   }
15321
15322   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15323          && "Unknown target vector shift-by-constant node");
15324
15325   // Fold this packed vector shift into a build vector if SrcOp is a
15326   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15327   if (VT == SrcOp.getSimpleValueType() &&
15328       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15329     SmallVector<SDValue, 8> Elts;
15330     unsigned NumElts = SrcOp->getNumOperands();
15331     ConstantSDNode *ND;
15332
15333     switch(Opc) {
15334     default: llvm_unreachable(nullptr);
15335     case X86ISD::VSHLI:
15336       for (unsigned i=0; i!=NumElts; ++i) {
15337         SDValue CurrentOp = SrcOp->getOperand(i);
15338         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15339           Elts.push_back(CurrentOp);
15340           continue;
15341         }
15342         ND = cast<ConstantSDNode>(CurrentOp);
15343         const APInt &C = ND->getAPIntValue();
15344         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15345       }
15346       break;
15347     case X86ISD::VSRLI:
15348       for (unsigned i=0; i!=NumElts; ++i) {
15349         SDValue CurrentOp = SrcOp->getOperand(i);
15350         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15351           Elts.push_back(CurrentOp);
15352           continue;
15353         }
15354         ND = cast<ConstantSDNode>(CurrentOp);
15355         const APInt &C = ND->getAPIntValue();
15356         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15357       }
15358       break;
15359     case X86ISD::VSRAI:
15360       for (unsigned i=0; i!=NumElts; ++i) {
15361         SDValue CurrentOp = SrcOp->getOperand(i);
15362         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15363           Elts.push_back(CurrentOp);
15364           continue;
15365         }
15366         ND = cast<ConstantSDNode>(CurrentOp);
15367         const APInt &C = ND->getAPIntValue();
15368         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15369       }
15370       break;
15371     }
15372
15373     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15374   }
15375
15376   return DAG.getNode(Opc, dl, VT, SrcOp,
15377                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15378 }
15379
15380 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15381 // may or may not be a constant. Takes immediate version of shift as input.
15382 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15383                                    SDValue SrcOp, SDValue ShAmt,
15384                                    SelectionDAG &DAG) {
15385   MVT SVT = ShAmt.getSimpleValueType();
15386   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15387
15388   // Catch shift-by-constant.
15389   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15390     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15391                                       CShAmt->getZExtValue(), DAG);
15392
15393   // Change opcode to non-immediate version
15394   switch (Opc) {
15395     default: llvm_unreachable("Unknown target vector shift node");
15396     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15397     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15398     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15399   }
15400
15401   const X86Subtarget &Subtarget =
15402       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15403   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15404       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15405     // Let the shuffle legalizer expand this shift amount node.
15406     SDValue Op0 = ShAmt.getOperand(0);
15407     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15408     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15409   } else {
15410     // Need to build a vector containing shift amount.
15411     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15412     SmallVector<SDValue, 4> ShOps;
15413     ShOps.push_back(ShAmt);
15414     if (SVT == MVT::i32) {
15415       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15416       ShOps.push_back(DAG.getUNDEF(SVT));
15417     }
15418     ShOps.push_back(DAG.getUNDEF(SVT));
15419
15420     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15421     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15422   }
15423
15424   // The return type has to be a 128-bit type with the same element
15425   // type as the input type.
15426   MVT EltVT = VT.getVectorElementType();
15427   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15428
15429   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15430   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15431 }
15432
15433 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15434 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15435 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15436 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15437                                     SDValue PreservedSrc,
15438                                     const X86Subtarget *Subtarget,
15439                                     SelectionDAG &DAG) {
15440     EVT VT = Op.getValueType();
15441     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15442                                   MVT::i1, VT.getVectorNumElements());
15443     SDValue VMask = SDValue();
15444     unsigned OpcodeSelect = ISD::VSELECT;
15445     SDLoc dl(Op);
15446
15447     assert(MaskVT.isSimple() && "invalid mask type");
15448
15449     if (isAllOnes(Mask))
15450       return Op;
15451
15452     if (MaskVT.bitsGT(Mask.getValueType())) {
15453       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15454                                          MaskVT.getSizeInBits());
15455       VMask = DAG.getBitcast(MaskVT,
15456                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15457     } else {
15458       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15459                                        Mask.getValueType().getSizeInBits());
15460       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15461       // are extracted by EXTRACT_SUBVECTOR.
15462       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15463                           DAG.getBitcast(BitcastVT, Mask),
15464                           DAG.getIntPtrConstant(0, dl));
15465     }
15466
15467     switch (Op.getOpcode()) {
15468       default: break;
15469       case X86ISD::PCMPEQM:
15470       case X86ISD::PCMPGTM:
15471       case X86ISD::CMPM:
15472       case X86ISD::CMPMU:
15473         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15474       case X86ISD::VTRUNC:
15475       case X86ISD::VTRUNCS:
15476       case X86ISD::VTRUNCUS:
15477         // We can't use ISD::VSELECT here because it is not always "Legal"
15478         // for the destination type. For example vpmovqb require only AVX512
15479         // and vselect that can operate on byte element type require BWI
15480         OpcodeSelect = X86ISD::SELECT;
15481         break;
15482     }
15483     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15484       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15485     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15486 }
15487
15488 /// \brief Creates an SDNode for a predicated scalar operation.
15489 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15490 /// The mask is coming as MVT::i8 and it should be truncated
15491 /// to MVT::i1 while lowering masking intrinsics.
15492 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15493 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15494 /// for a scalar instruction.
15495 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15496                                     SDValue PreservedSrc,
15497                                     const X86Subtarget *Subtarget,
15498                                     SelectionDAG &DAG) {
15499     if (isAllOnes(Mask))
15500       return Op;
15501
15502     EVT VT = Op.getValueType();
15503     SDLoc dl(Op);
15504     // The mask should be of type MVT::i1
15505     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15506
15507     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15508       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15509     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15510 }
15511
15512 static int getSEHRegistrationNodeSize(const Function *Fn) {
15513   if (!Fn->hasPersonalityFn())
15514     report_fatal_error(
15515         "querying registration node size for function without personality");
15516   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15517   // WinEHStatePass for the full struct definition.
15518   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15519   case EHPersonality::MSVC_X86SEH: return 24;
15520   case EHPersonality::MSVC_CXX: return 16;
15521   default: break;
15522   }
15523   report_fatal_error("can only recover FP for MSVC EH personality functions");
15524 }
15525
15526 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15527 /// function or when returning to a parent frame after catching an exception, we
15528 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15529 /// Here's the math:
15530 ///   RegNodeBase = EntryEBP - RegNodeSize
15531 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15532 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15533 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15534 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15535                                    SDValue EntryEBP) {
15536   MachineFunction &MF = DAG.getMachineFunction();
15537   SDLoc dl;
15538
15539   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15540   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15541
15542   // It's possible that the parent function no longer has a personality function
15543   // if the exceptional code was optimized away, in which case we just return
15544   // the incoming EBP.
15545   if (!Fn->hasPersonalityFn())
15546     return EntryEBP;
15547
15548   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15549
15550   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15551   // registration.
15552   MCSymbol *OffsetSym =
15553       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15554           GlobalValue::getRealLinkageName(Fn->getName()));
15555   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15556   SDValue RegNodeFrameOffset =
15557       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15558
15559   // RegNodeBase = EntryEBP - RegNodeSize
15560   // ParentFP = RegNodeBase - RegNodeFrameOffset
15561   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15562                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15563   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15564 }
15565
15566 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15567                                        SelectionDAG &DAG) {
15568   SDLoc dl(Op);
15569   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15570   EVT VT = Op.getValueType();
15571   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15572   if (IntrData) {
15573     switch(IntrData->Type) {
15574     case INTR_TYPE_1OP:
15575       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15576     case INTR_TYPE_2OP:
15577       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15578         Op.getOperand(2));
15579     case INTR_TYPE_3OP:
15580       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15581         Op.getOperand(2), Op.getOperand(3));
15582     case INTR_TYPE_4OP:
15583       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15584         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15585     case INTR_TYPE_1OP_MASK_RM: {
15586       SDValue Src = Op.getOperand(1);
15587       SDValue PassThru = Op.getOperand(2);
15588       SDValue Mask = Op.getOperand(3);
15589       SDValue RoundingMode;
15590       // We allways add rounding mode to the Node.
15591       // If the rounding mode is not specified, we add the
15592       // "current direction" mode.
15593       if (Op.getNumOperands() == 4)
15594         RoundingMode =
15595           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15596       else
15597         RoundingMode = Op.getOperand(4);
15598       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15599       if (IntrWithRoundingModeOpcode != 0)
15600         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15601             X86::STATIC_ROUNDING::CUR_DIRECTION)
15602           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15603                                       dl, Op.getValueType(), Src, RoundingMode),
15604                                       Mask, PassThru, Subtarget, DAG);
15605       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15606                                               RoundingMode),
15607                                   Mask, PassThru, Subtarget, DAG);
15608     }
15609     case INTR_TYPE_1OP_MASK: {
15610       SDValue Src = Op.getOperand(1);
15611       SDValue PassThru = Op.getOperand(2);
15612       SDValue Mask = Op.getOperand(3);
15613       // We add rounding mode to the Node when
15614       //   - RM Opcode is specified and
15615       //   - RM is not "current direction".
15616       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15617       if (IntrWithRoundingModeOpcode != 0) {
15618         SDValue Rnd = Op.getOperand(4);
15619         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15620         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15621           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15622                                       dl, Op.getValueType(),
15623                                       Src, Rnd),
15624                                       Mask, PassThru, Subtarget, DAG);
15625         }
15626       }
15627       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15628                                   Mask, PassThru, Subtarget, DAG);
15629     }
15630     case INTR_TYPE_SCALAR_MASK_RM: {
15631       SDValue Src1 = Op.getOperand(1);
15632       SDValue Src2 = Op.getOperand(2);
15633       SDValue Src0 = Op.getOperand(3);
15634       SDValue Mask = Op.getOperand(4);
15635       // There are 2 kinds of intrinsics in this group:
15636       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15637       // (2) With rounding mode and sae - 7 operands.
15638       if (Op.getNumOperands() == 6) {
15639         SDValue Sae  = Op.getOperand(5);
15640         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15641         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15642                                                 Sae),
15643                                     Mask, Src0, Subtarget, DAG);
15644       }
15645       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15646       SDValue RoundingMode  = Op.getOperand(5);
15647       SDValue Sae  = Op.getOperand(6);
15648       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15649                                               RoundingMode, Sae),
15650                                   Mask, Src0, Subtarget, DAG);
15651     }
15652     case INTR_TYPE_2OP_MASK: {
15653       SDValue Src1 = Op.getOperand(1);
15654       SDValue Src2 = Op.getOperand(2);
15655       SDValue PassThru = Op.getOperand(3);
15656       SDValue Mask = Op.getOperand(4);
15657       // We specify 2 possible opcodes for intrinsics with rounding modes.
15658       // First, we check if the intrinsic may have non-default rounding mode,
15659       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15660       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15661       if (IntrWithRoundingModeOpcode != 0) {
15662         SDValue Rnd = Op.getOperand(5);
15663         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15664         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15665           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15666                                       dl, Op.getValueType(),
15667                                       Src1, Src2, Rnd),
15668                                       Mask, PassThru, Subtarget, DAG);
15669         }
15670       }
15671       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15672                                               Src1,Src2),
15673                                   Mask, PassThru, Subtarget, DAG);
15674     }
15675     case INTR_TYPE_2OP_MASK_RM: {
15676       SDValue Src1 = Op.getOperand(1);
15677       SDValue Src2 = Op.getOperand(2);
15678       SDValue PassThru = Op.getOperand(3);
15679       SDValue Mask = Op.getOperand(4);
15680       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15681       // First, we check if the intrinsic have rounding mode (6 operands),
15682       // if not, we set rounding mode to "current".
15683       SDValue Rnd;
15684       if (Op.getNumOperands() == 6)
15685         Rnd = Op.getOperand(5);
15686       else
15687         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15688       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15689                                               Src1, Src2, Rnd),
15690                                   Mask, PassThru, Subtarget, DAG);
15691     }
15692     case INTR_TYPE_3OP_MASK_RM: {
15693       SDValue Src1 = Op.getOperand(1);
15694       SDValue Src2 = Op.getOperand(2);
15695       SDValue Imm = Op.getOperand(3);
15696       SDValue PassThru = Op.getOperand(4);
15697       SDValue Mask = Op.getOperand(5);
15698       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15699       // First, we check if the intrinsic have rounding mode (7 operands),
15700       // if not, we set rounding mode to "current".
15701       SDValue Rnd;
15702       if (Op.getNumOperands() == 7)
15703         Rnd = Op.getOperand(6);
15704       else
15705         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15706       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15707         Src1, Src2, Imm, Rnd),
15708         Mask, PassThru, Subtarget, DAG);
15709     }
15710     case INTR_TYPE_3OP_IMM8_MASK:
15711     case INTR_TYPE_3OP_MASK: {
15712       SDValue Src1 = Op.getOperand(1);
15713       SDValue Src2 = Op.getOperand(2);
15714       SDValue Src3 = Op.getOperand(3);
15715       SDValue PassThru = Op.getOperand(4);
15716       SDValue Mask = Op.getOperand(5);
15717
15718       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
15719         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
15720       // We specify 2 possible opcodes for intrinsics with rounding modes.
15721       // First, we check if the intrinsic may have non-default rounding mode,
15722       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15723       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15724       if (IntrWithRoundingModeOpcode != 0) {
15725         SDValue Rnd = Op.getOperand(6);
15726         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15727         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15728           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15729                                       dl, Op.getValueType(),
15730                                       Src1, Src2, Src3, Rnd),
15731                                       Mask, PassThru, Subtarget, DAG);
15732         }
15733       }
15734       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15735                                               Src1, Src2, Src3),
15736                                   Mask, PassThru, Subtarget, DAG);
15737     }
15738     case VPERM_3OP_MASKZ:
15739     case VPERM_3OP_MASK:
15740     case FMA_OP_MASK3:
15741     case FMA_OP_MASKZ:
15742     case FMA_OP_MASK: {
15743       SDValue Src1 = Op.getOperand(1);
15744       SDValue Src2 = Op.getOperand(2);
15745       SDValue Src3 = Op.getOperand(3);
15746       SDValue Mask = Op.getOperand(4);
15747       EVT VT = Op.getValueType();
15748       SDValue PassThru = SDValue();
15749
15750       // set PassThru element
15751       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15752         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15753       else if (IntrData->Type == FMA_OP_MASK3)
15754         PassThru = Src3;
15755       else
15756         PassThru = Src1;
15757
15758       // We specify 2 possible opcodes for intrinsics with rounding modes.
15759       // First, we check if the intrinsic may have non-default rounding mode,
15760       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15761       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15762       if (IntrWithRoundingModeOpcode != 0) {
15763         SDValue Rnd = Op.getOperand(5);
15764         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15765             X86::STATIC_ROUNDING::CUR_DIRECTION)
15766           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15767                                                   dl, Op.getValueType(),
15768                                                   Src1, Src2, Src3, Rnd),
15769                                       Mask, PassThru, Subtarget, DAG);
15770       }
15771       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15772                                               dl, Op.getValueType(),
15773                                               Src1, Src2, Src3),
15774                                   Mask, PassThru, Subtarget, DAG);
15775     }
15776     case CMP_MASK:
15777     case CMP_MASK_CC: {
15778       // Comparison intrinsics with masks.
15779       // Example of transformation:
15780       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15781       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15782       // (i8 (bitcast
15783       //   (v8i1 (insert_subvector undef,
15784       //           (v2i1 (and (PCMPEQM %a, %b),
15785       //                      (extract_subvector
15786       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15787       EVT VT = Op.getOperand(1).getValueType();
15788       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15789                                     VT.getVectorNumElements());
15790       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15791       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15792                                        Mask.getValueType().getSizeInBits());
15793       SDValue Cmp;
15794       if (IntrData->Type == CMP_MASK_CC) {
15795         SDValue CC = Op.getOperand(3);
15796         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15797         // We specify 2 possible opcodes for intrinsics with rounding modes.
15798         // First, we check if the intrinsic may have non-default rounding mode,
15799         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15800         if (IntrData->Opc1 != 0) {
15801           SDValue Rnd = Op.getOperand(5);
15802           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15803               X86::STATIC_ROUNDING::CUR_DIRECTION)
15804             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15805                               Op.getOperand(2), CC, Rnd);
15806         }
15807         //default rounding mode
15808         if(!Cmp.getNode())
15809             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15810                               Op.getOperand(2), CC);
15811
15812       } else {
15813         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15814         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15815                           Op.getOperand(2));
15816       }
15817       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15818                                              DAG.getTargetConstant(0, dl,
15819                                                                    MaskVT),
15820                                              Subtarget, DAG);
15821       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15822                                 DAG.getUNDEF(BitcastVT), CmpMask,
15823                                 DAG.getIntPtrConstant(0, dl));
15824       return DAG.getBitcast(Op.getValueType(), Res);
15825     }
15826     case COMI: { // Comparison intrinsics
15827       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15828       SDValue LHS = Op.getOperand(1);
15829       SDValue RHS = Op.getOperand(2);
15830       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15831       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15832       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15833       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15834                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15835       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15836     }
15837     case VSHIFT:
15838       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15839                                  Op.getOperand(1), Op.getOperand(2), DAG);
15840     case VSHIFT_MASK:
15841       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15842                                                       Op.getSimpleValueType(),
15843                                                       Op.getOperand(1),
15844                                                       Op.getOperand(2), DAG),
15845                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15846                                   DAG);
15847     case COMPRESS_EXPAND_IN_REG: {
15848       SDValue Mask = Op.getOperand(3);
15849       SDValue DataToCompress = Op.getOperand(1);
15850       SDValue PassThru = Op.getOperand(2);
15851       if (isAllOnes(Mask)) // return data as is
15852         return Op.getOperand(1);
15853
15854       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15855                                               DataToCompress),
15856                                   Mask, PassThru, Subtarget, DAG);
15857     }
15858     case BLEND: {
15859       SDValue Mask = Op.getOperand(3);
15860       EVT VT = Op.getValueType();
15861       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15862                                     VT.getVectorNumElements());
15863       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15864                                        Mask.getValueType().getSizeInBits());
15865       SDLoc dl(Op);
15866       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15867                                   DAG.getBitcast(BitcastVT, Mask),
15868                                   DAG.getIntPtrConstant(0, dl));
15869       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15870                          Op.getOperand(2));
15871     }
15872     default:
15873       break;
15874     }
15875   }
15876
15877   switch (IntNo) {
15878   default: return SDValue();    // Don't custom lower most intrinsics.
15879
15880   case Intrinsic::x86_avx2_permd:
15881   case Intrinsic::x86_avx2_permps:
15882     // Operands intentionally swapped. Mask is last operand to intrinsic,
15883     // but second operand for node/instruction.
15884     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15885                        Op.getOperand(2), Op.getOperand(1));
15886
15887   // ptest and testp intrinsics. The intrinsic these come from are designed to
15888   // return an integer value, not just an instruction so lower it to the ptest
15889   // or testp pattern and a setcc for the result.
15890   case Intrinsic::x86_sse41_ptestz:
15891   case Intrinsic::x86_sse41_ptestc:
15892   case Intrinsic::x86_sse41_ptestnzc:
15893   case Intrinsic::x86_avx_ptestz_256:
15894   case Intrinsic::x86_avx_ptestc_256:
15895   case Intrinsic::x86_avx_ptestnzc_256:
15896   case Intrinsic::x86_avx_vtestz_ps:
15897   case Intrinsic::x86_avx_vtestc_ps:
15898   case Intrinsic::x86_avx_vtestnzc_ps:
15899   case Intrinsic::x86_avx_vtestz_pd:
15900   case Intrinsic::x86_avx_vtestc_pd:
15901   case Intrinsic::x86_avx_vtestnzc_pd:
15902   case Intrinsic::x86_avx_vtestz_ps_256:
15903   case Intrinsic::x86_avx_vtestc_ps_256:
15904   case Intrinsic::x86_avx_vtestnzc_ps_256:
15905   case Intrinsic::x86_avx_vtestz_pd_256:
15906   case Intrinsic::x86_avx_vtestc_pd_256:
15907   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15908     bool IsTestPacked = false;
15909     unsigned X86CC;
15910     switch (IntNo) {
15911     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15912     case Intrinsic::x86_avx_vtestz_ps:
15913     case Intrinsic::x86_avx_vtestz_pd:
15914     case Intrinsic::x86_avx_vtestz_ps_256:
15915     case Intrinsic::x86_avx_vtestz_pd_256:
15916       IsTestPacked = true; // Fallthrough
15917     case Intrinsic::x86_sse41_ptestz:
15918     case Intrinsic::x86_avx_ptestz_256:
15919       // ZF = 1
15920       X86CC = X86::COND_E;
15921       break;
15922     case Intrinsic::x86_avx_vtestc_ps:
15923     case Intrinsic::x86_avx_vtestc_pd:
15924     case Intrinsic::x86_avx_vtestc_ps_256:
15925     case Intrinsic::x86_avx_vtestc_pd_256:
15926       IsTestPacked = true; // Fallthrough
15927     case Intrinsic::x86_sse41_ptestc:
15928     case Intrinsic::x86_avx_ptestc_256:
15929       // CF = 1
15930       X86CC = X86::COND_B;
15931       break;
15932     case Intrinsic::x86_avx_vtestnzc_ps:
15933     case Intrinsic::x86_avx_vtestnzc_pd:
15934     case Intrinsic::x86_avx_vtestnzc_ps_256:
15935     case Intrinsic::x86_avx_vtestnzc_pd_256:
15936       IsTestPacked = true; // Fallthrough
15937     case Intrinsic::x86_sse41_ptestnzc:
15938     case Intrinsic::x86_avx_ptestnzc_256:
15939       // ZF and CF = 0
15940       X86CC = X86::COND_A;
15941       break;
15942     }
15943
15944     SDValue LHS = Op.getOperand(1);
15945     SDValue RHS = Op.getOperand(2);
15946     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15947     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15948     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15949     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15950     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15951   }
15952   case Intrinsic::x86_avx512_kortestz_w:
15953   case Intrinsic::x86_avx512_kortestc_w: {
15954     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15955     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15956     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15957     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15958     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15959     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15960     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15961   }
15962
15963   case Intrinsic::x86_sse42_pcmpistria128:
15964   case Intrinsic::x86_sse42_pcmpestria128:
15965   case Intrinsic::x86_sse42_pcmpistric128:
15966   case Intrinsic::x86_sse42_pcmpestric128:
15967   case Intrinsic::x86_sse42_pcmpistrio128:
15968   case Intrinsic::x86_sse42_pcmpestrio128:
15969   case Intrinsic::x86_sse42_pcmpistris128:
15970   case Intrinsic::x86_sse42_pcmpestris128:
15971   case Intrinsic::x86_sse42_pcmpistriz128:
15972   case Intrinsic::x86_sse42_pcmpestriz128: {
15973     unsigned Opcode;
15974     unsigned X86CC;
15975     switch (IntNo) {
15976     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15977     case Intrinsic::x86_sse42_pcmpistria128:
15978       Opcode = X86ISD::PCMPISTRI;
15979       X86CC = X86::COND_A;
15980       break;
15981     case Intrinsic::x86_sse42_pcmpestria128:
15982       Opcode = X86ISD::PCMPESTRI;
15983       X86CC = X86::COND_A;
15984       break;
15985     case Intrinsic::x86_sse42_pcmpistric128:
15986       Opcode = X86ISD::PCMPISTRI;
15987       X86CC = X86::COND_B;
15988       break;
15989     case Intrinsic::x86_sse42_pcmpestric128:
15990       Opcode = X86ISD::PCMPESTRI;
15991       X86CC = X86::COND_B;
15992       break;
15993     case Intrinsic::x86_sse42_pcmpistrio128:
15994       Opcode = X86ISD::PCMPISTRI;
15995       X86CC = X86::COND_O;
15996       break;
15997     case Intrinsic::x86_sse42_pcmpestrio128:
15998       Opcode = X86ISD::PCMPESTRI;
15999       X86CC = X86::COND_O;
16000       break;
16001     case Intrinsic::x86_sse42_pcmpistris128:
16002       Opcode = X86ISD::PCMPISTRI;
16003       X86CC = X86::COND_S;
16004       break;
16005     case Intrinsic::x86_sse42_pcmpestris128:
16006       Opcode = X86ISD::PCMPESTRI;
16007       X86CC = X86::COND_S;
16008       break;
16009     case Intrinsic::x86_sse42_pcmpistriz128:
16010       Opcode = X86ISD::PCMPISTRI;
16011       X86CC = X86::COND_E;
16012       break;
16013     case Intrinsic::x86_sse42_pcmpestriz128:
16014       Opcode = X86ISD::PCMPESTRI;
16015       X86CC = X86::COND_E;
16016       break;
16017     }
16018     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16019     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16020     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16021     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16022                                 DAG.getConstant(X86CC, dl, MVT::i8),
16023                                 SDValue(PCMP.getNode(), 1));
16024     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16025   }
16026
16027   case Intrinsic::x86_sse42_pcmpistri128:
16028   case Intrinsic::x86_sse42_pcmpestri128: {
16029     unsigned Opcode;
16030     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16031       Opcode = X86ISD::PCMPISTRI;
16032     else
16033       Opcode = X86ISD::PCMPESTRI;
16034
16035     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16036     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16037     return DAG.getNode(Opcode, dl, VTs, NewOps);
16038   }
16039
16040   case Intrinsic::x86_seh_lsda: {
16041     // Compute the symbol for the LSDA. We know it'll get emitted later.
16042     MachineFunction &MF = DAG.getMachineFunction();
16043     SDValue Op1 = Op.getOperand(1);
16044     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16045     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16046         GlobalValue::getRealLinkageName(Fn->getName()));
16047
16048     // Generate a simple absolute symbol reference. This intrinsic is only
16049     // supported on 32-bit Windows, which isn't PIC.
16050     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16051     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16052   }
16053
16054   case Intrinsic::x86_seh_recoverfp: {
16055     SDValue FnOp = Op.getOperand(1);
16056     SDValue IncomingFPOp = Op.getOperand(2);
16057     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16058     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16059     if (!Fn)
16060       report_fatal_error(
16061           "llvm.x86.seh.recoverfp must take a function as the first argument");
16062     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16063   }
16064
16065   case Intrinsic::localaddress: {
16066     // Returns one of the stack, base, or frame pointer registers, depending on
16067     // which is used to reference local variables.
16068     MachineFunction &MF = DAG.getMachineFunction();
16069     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16070     unsigned Reg;
16071     if (RegInfo->hasBasePointer(MF))
16072       Reg = RegInfo->getBaseRegister();
16073     else // This function handles the SP or FP case.
16074       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16075     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16076   }
16077   }
16078 }
16079
16080 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16081                               SDValue Src, SDValue Mask, SDValue Base,
16082                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16083                               const X86Subtarget * Subtarget) {
16084   SDLoc dl(Op);
16085   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16086   if (!C)
16087     llvm_unreachable("Invalid scale type");
16088   unsigned ScaleVal = C->getZExtValue();
16089   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16090     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16091
16092   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16093   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16094                              Index.getSimpleValueType().getVectorNumElements());
16095   SDValue MaskInReg;
16096   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16097   if (MaskC)
16098     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16099   else {
16100     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16101                                      Mask.getValueType().getSizeInBits());
16102
16103     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16104     // are extracted by EXTRACT_SUBVECTOR.
16105     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16106                             DAG.getBitcast(BitcastVT, Mask),
16107                             DAG.getIntPtrConstant(0, dl));
16108   }
16109   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16110   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16111   SDValue Segment = DAG.getRegister(0, MVT::i32);
16112   if (Src.getOpcode() == ISD::UNDEF)
16113     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16114   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16115   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16116   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16117   return DAG.getMergeValues(RetOps, dl);
16118 }
16119
16120 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16121                                SDValue Src, SDValue Mask, SDValue Base,
16122                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16123   SDLoc dl(Op);
16124   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16125   if (!C)
16126     llvm_unreachable("Invalid scale type");
16127   unsigned ScaleVal = C->getZExtValue();
16128   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16129     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16130
16131   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16132   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16133   SDValue Segment = DAG.getRegister(0, MVT::i32);
16134   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16135                              Index.getSimpleValueType().getVectorNumElements());
16136   SDValue MaskInReg;
16137   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16138   if (MaskC)
16139     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16140   else {
16141     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16142                                      Mask.getValueType().getSizeInBits());
16143
16144     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16145     // are extracted by EXTRACT_SUBVECTOR.
16146     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16147                             DAG.getBitcast(BitcastVT, Mask),
16148                             DAG.getIntPtrConstant(0, dl));
16149   }
16150   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16151   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16152   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16153   return SDValue(Res, 1);
16154 }
16155
16156 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16157                                SDValue Mask, SDValue Base, SDValue Index,
16158                                SDValue ScaleOp, SDValue Chain) {
16159   SDLoc dl(Op);
16160   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16161   assert(C && "Invalid scale type");
16162   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16163   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16164   SDValue Segment = DAG.getRegister(0, MVT::i32);
16165   EVT MaskVT =
16166     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16167   SDValue MaskInReg;
16168   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16169   if (MaskC)
16170     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16171   else
16172     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16173   //SDVTList VTs = DAG.getVTList(MVT::Other);
16174   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16175   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16176   return SDValue(Res, 0);
16177 }
16178
16179 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16180 // read performance monitor counters (x86_rdpmc).
16181 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16182                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16183                               SmallVectorImpl<SDValue> &Results) {
16184   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16185   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16186   SDValue LO, HI;
16187
16188   // The ECX register is used to select the index of the performance counter
16189   // to read.
16190   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16191                                    N->getOperand(2));
16192   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16193
16194   // Reads the content of a 64-bit performance counter and returns it in the
16195   // registers EDX:EAX.
16196   if (Subtarget->is64Bit()) {
16197     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16198     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16199                             LO.getValue(2));
16200   } else {
16201     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16202     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16203                             LO.getValue(2));
16204   }
16205   Chain = HI.getValue(1);
16206
16207   if (Subtarget->is64Bit()) {
16208     // The EAX register is loaded with the low-order 32 bits. The EDX register
16209     // is loaded with the supported high-order bits of the counter.
16210     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16211                               DAG.getConstant(32, DL, MVT::i8));
16212     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16213     Results.push_back(Chain);
16214     return;
16215   }
16216
16217   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16218   SDValue Ops[] = { LO, HI };
16219   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16220   Results.push_back(Pair);
16221   Results.push_back(Chain);
16222 }
16223
16224 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16225 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16226 // also used to custom lower READCYCLECOUNTER nodes.
16227 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16228                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16229                               SmallVectorImpl<SDValue> &Results) {
16230   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16231   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16232   SDValue LO, HI;
16233
16234   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16235   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16236   // and the EAX register is loaded with the low-order 32 bits.
16237   if (Subtarget->is64Bit()) {
16238     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16239     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16240                             LO.getValue(2));
16241   } else {
16242     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16243     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16244                             LO.getValue(2));
16245   }
16246   SDValue Chain = HI.getValue(1);
16247
16248   if (Opcode == X86ISD::RDTSCP_DAG) {
16249     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16250
16251     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16252     // the ECX register. Add 'ecx' explicitly to the chain.
16253     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16254                                      HI.getValue(2));
16255     // Explicitly store the content of ECX at the location passed in input
16256     // to the 'rdtscp' intrinsic.
16257     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16258                          MachinePointerInfo(), false, false, 0);
16259   }
16260
16261   if (Subtarget->is64Bit()) {
16262     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16263     // the EAX register is loaded with the low-order 32 bits.
16264     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16265                               DAG.getConstant(32, DL, MVT::i8));
16266     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16267     Results.push_back(Chain);
16268     return;
16269   }
16270
16271   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16272   SDValue Ops[] = { LO, HI };
16273   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16274   Results.push_back(Pair);
16275   Results.push_back(Chain);
16276 }
16277
16278 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16279                                      SelectionDAG &DAG) {
16280   SmallVector<SDValue, 2> Results;
16281   SDLoc DL(Op);
16282   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16283                           Results);
16284   return DAG.getMergeValues(Results, DL);
16285 }
16286
16287 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16288                                     SelectionDAG &DAG) {
16289   MachineFunction &MF = DAG.getMachineFunction();
16290   const Function *Fn = MF.getFunction();
16291   SDLoc dl(Op);
16292   SDValue Chain = Op.getOperand(0);
16293
16294   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16295          "using llvm.x86.seh.restoreframe requires a frame pointer");
16296
16297   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16298   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16299
16300   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16301   unsigned FrameReg =
16302       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16303   unsigned SPReg = RegInfo->getStackRegister();
16304   unsigned SlotSize = RegInfo->getSlotSize();
16305
16306   // Get incoming EBP.
16307   SDValue IncomingEBP =
16308       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16309
16310   // SP is saved in the first field of every registration node, so load
16311   // [EBP-RegNodeSize] into SP.
16312   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16313   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16314                                DAG.getConstant(-RegNodeSize, dl, VT));
16315   SDValue NewSP =
16316       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16317                   false, VT.getScalarSizeInBits() / 8);
16318   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16319
16320   if (!RegInfo->needsStackRealignment(MF)) {
16321     // Adjust EBP to point back to the original frame position.
16322     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16323     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16324   } else {
16325     assert(RegInfo->hasBasePointer(MF) &&
16326            "functions with Win32 EH must use frame or base pointer register");
16327
16328     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16329     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16330     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16331
16332     // Reload the spilled EBP value, now that the stack and base pointers are
16333     // set up.
16334     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16335     X86FI->setHasSEHFramePtrSave(true);
16336     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16337     X86FI->setSEHFramePtrSaveIndex(FI);
16338     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16339                                 MachinePointerInfo(), false, false, false,
16340                                 VT.getScalarSizeInBits() / 8);
16341     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16342   }
16343
16344   return Chain;
16345 }
16346
16347 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16348 /// return truncate Store/MaskedStore Node
16349 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16350                                                SelectionDAG &DAG,
16351                                                MVT ElementType) {
16352   SDLoc dl(Op);
16353   SDValue Mask = Op.getOperand(4);
16354   SDValue DataToTruncate = Op.getOperand(3);
16355   SDValue Addr = Op.getOperand(2);
16356   SDValue Chain = Op.getOperand(0);
16357
16358   EVT VT  = DataToTruncate.getValueType();
16359   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16360                              ElementType, VT.getVectorNumElements());
16361
16362   if (isAllOnes(Mask)) // return just a truncate store
16363     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16364                              MachinePointerInfo(), SVT, false, false,
16365                              SVT.getScalarSizeInBits()/8);
16366
16367   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16368                                 MVT::i1, VT.getVectorNumElements());
16369   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16370                                    Mask.getValueType().getSizeInBits());
16371   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16372   // are extracted by EXTRACT_SUBVECTOR.
16373   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16374                               DAG.getBitcast(BitcastVT, Mask),
16375                               DAG.getIntPtrConstant(0, dl));
16376
16377   MachineMemOperand *MMO = DAG.getMachineFunction().
16378     getMachineMemOperand(MachinePointerInfo(),
16379                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16380                          SVT.getScalarSizeInBits()/8);
16381
16382   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16383                             VMask, SVT, MMO, true);
16384 }
16385
16386 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16387                                       SelectionDAG &DAG) {
16388   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16389
16390   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16391   if (!IntrData) {
16392     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16393       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16394     return SDValue();
16395   }
16396
16397   SDLoc dl(Op);
16398   switch(IntrData->Type) {
16399   default:
16400     llvm_unreachable("Unknown Intrinsic Type");
16401     break;
16402   case RDSEED:
16403   case RDRAND: {
16404     // Emit the node with the right value type.
16405     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16406     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16407
16408     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16409     // Otherwise return the value from Rand, which is always 0, casted to i32.
16410     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16411                       DAG.getConstant(1, dl, Op->getValueType(1)),
16412                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16413                       SDValue(Result.getNode(), 1) };
16414     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16415                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16416                                   Ops);
16417
16418     // Return { result, isValid, chain }.
16419     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16420                        SDValue(Result.getNode(), 2));
16421   }
16422   case GATHER: {
16423   //gather(v1, mask, index, base, scale);
16424     SDValue Chain = Op.getOperand(0);
16425     SDValue Src   = Op.getOperand(2);
16426     SDValue Base  = Op.getOperand(3);
16427     SDValue Index = Op.getOperand(4);
16428     SDValue Mask  = Op.getOperand(5);
16429     SDValue Scale = Op.getOperand(6);
16430     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16431                          Chain, Subtarget);
16432   }
16433   case SCATTER: {
16434   //scatter(base, mask, index, v1, scale);
16435     SDValue Chain = Op.getOperand(0);
16436     SDValue Base  = Op.getOperand(2);
16437     SDValue Mask  = Op.getOperand(3);
16438     SDValue Index = Op.getOperand(4);
16439     SDValue Src   = Op.getOperand(5);
16440     SDValue Scale = Op.getOperand(6);
16441     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16442                           Scale, Chain);
16443   }
16444   case PREFETCH: {
16445     SDValue Hint = Op.getOperand(6);
16446     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16447     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16448     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16449     SDValue Chain = Op.getOperand(0);
16450     SDValue Mask  = Op.getOperand(2);
16451     SDValue Index = Op.getOperand(3);
16452     SDValue Base  = Op.getOperand(4);
16453     SDValue Scale = Op.getOperand(5);
16454     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16455   }
16456   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16457   case RDTSC: {
16458     SmallVector<SDValue, 2> Results;
16459     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16460                             Results);
16461     return DAG.getMergeValues(Results, dl);
16462   }
16463   // Read Performance Monitoring Counters.
16464   case RDPMC: {
16465     SmallVector<SDValue, 2> Results;
16466     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16467     return DAG.getMergeValues(Results, dl);
16468   }
16469   // XTEST intrinsics.
16470   case XTEST: {
16471     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16472     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16473     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16474                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16475                                 InTrans);
16476     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16477     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16478                        Ret, SDValue(InTrans.getNode(), 1));
16479   }
16480   // ADC/ADCX/SBB
16481   case ADX: {
16482     SmallVector<SDValue, 2> Results;
16483     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16484     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16485     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16486                                 DAG.getConstant(-1, dl, MVT::i8));
16487     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16488                               Op.getOperand(4), GenCF.getValue(1));
16489     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16490                                  Op.getOperand(5), MachinePointerInfo(),
16491                                  false, false, 0);
16492     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16493                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16494                                 Res.getValue(1));
16495     Results.push_back(SetCC);
16496     Results.push_back(Store);
16497     return DAG.getMergeValues(Results, dl);
16498   }
16499   case COMPRESS_TO_MEM: {
16500     SDLoc dl(Op);
16501     SDValue Mask = Op.getOperand(4);
16502     SDValue DataToCompress = Op.getOperand(3);
16503     SDValue Addr = Op.getOperand(2);
16504     SDValue Chain = Op.getOperand(0);
16505
16506     EVT VT = DataToCompress.getValueType();
16507     if (isAllOnes(Mask)) // return just a store
16508       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16509                           MachinePointerInfo(), false, false,
16510                           VT.getScalarSizeInBits()/8);
16511
16512     SDValue Compressed =
16513       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16514                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16515     return DAG.getStore(Chain, dl, Compressed, Addr,
16516                         MachinePointerInfo(), false, false,
16517                         VT.getScalarSizeInBits()/8);
16518   }
16519   case TRUNCATE_TO_MEM_VI8:
16520     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16521   case TRUNCATE_TO_MEM_VI16:
16522     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16523   case TRUNCATE_TO_MEM_VI32:
16524     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16525   case EXPAND_FROM_MEM: {
16526     SDLoc dl(Op);
16527     SDValue Mask = Op.getOperand(4);
16528     SDValue PassThru = Op.getOperand(3);
16529     SDValue Addr = Op.getOperand(2);
16530     SDValue Chain = Op.getOperand(0);
16531     EVT VT = Op.getValueType();
16532
16533     if (isAllOnes(Mask)) // return just a load
16534       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16535                          false, VT.getScalarSizeInBits()/8);
16536
16537     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16538                                        false, false, false,
16539                                        VT.getScalarSizeInBits()/8);
16540
16541     SDValue Results[] = {
16542       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16543                            Mask, PassThru, Subtarget, DAG), Chain};
16544     return DAG.getMergeValues(Results, dl);
16545   }
16546   }
16547 }
16548
16549 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16550                                            SelectionDAG &DAG) const {
16551   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16552   MFI->setReturnAddressIsTaken(true);
16553
16554   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16555     return SDValue();
16556
16557   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16558   SDLoc dl(Op);
16559   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16560
16561   if (Depth > 0) {
16562     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16563     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16564     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16565     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16566                        DAG.getNode(ISD::ADD, dl, PtrVT,
16567                                    FrameAddr, Offset),
16568                        MachinePointerInfo(), false, false, false, 0);
16569   }
16570
16571   // Just load the return address.
16572   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16573   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16574                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16575 }
16576
16577 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16578   MachineFunction &MF = DAG.getMachineFunction();
16579   MachineFrameInfo *MFI = MF.getFrameInfo();
16580   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16581   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16582   EVT VT = Op.getValueType();
16583
16584   MFI->setFrameAddressIsTaken(true);
16585
16586   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16587     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16588     // is not possible to crawl up the stack without looking at the unwind codes
16589     // simultaneously.
16590     int FrameAddrIndex = FuncInfo->getFAIndex();
16591     if (!FrameAddrIndex) {
16592       // Set up a frame object for the return address.
16593       unsigned SlotSize = RegInfo->getSlotSize();
16594       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16595           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16596       FuncInfo->setFAIndex(FrameAddrIndex);
16597     }
16598     return DAG.getFrameIndex(FrameAddrIndex, VT);
16599   }
16600
16601   unsigned FrameReg =
16602       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16603   SDLoc dl(Op);  // FIXME probably not meaningful
16604   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16605   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16606           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16607          "Invalid Frame Register!");
16608   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16609   while (Depth--)
16610     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16611                             MachinePointerInfo(),
16612                             false, false, false, 0);
16613   return FrameAddr;
16614 }
16615
16616 // FIXME? Maybe this could be a TableGen attribute on some registers and
16617 // this table could be generated automatically from RegInfo.
16618 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16619                                               SelectionDAG &DAG) const {
16620   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16621   const MachineFunction &MF = DAG.getMachineFunction();
16622
16623   unsigned Reg = StringSwitch<unsigned>(RegName)
16624                        .Case("esp", X86::ESP)
16625                        .Case("rsp", X86::RSP)
16626                        .Case("ebp", X86::EBP)
16627                        .Case("rbp", X86::RBP)
16628                        .Default(0);
16629
16630   if (Reg == X86::EBP || Reg == X86::RBP) {
16631     if (!TFI.hasFP(MF))
16632       report_fatal_error("register " + StringRef(RegName) +
16633                          " is allocatable: function has no frame pointer");
16634 #ifndef NDEBUG
16635     else {
16636       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16637       unsigned FrameReg =
16638           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16639       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16640              "Invalid Frame Register!");
16641     }
16642 #endif
16643   }
16644
16645   if (Reg)
16646     return Reg;
16647
16648   report_fatal_error("Invalid register name global variable");
16649 }
16650
16651 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16652                                                      SelectionDAG &DAG) const {
16653   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16654   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16655 }
16656
16657 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16658   SDValue Chain     = Op.getOperand(0);
16659   SDValue Offset    = Op.getOperand(1);
16660   SDValue Handler   = Op.getOperand(2);
16661   SDLoc dl      (Op);
16662
16663   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16664   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16665   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16666   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16667           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16668          "Invalid Frame Register!");
16669   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16670   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16671
16672   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16673                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16674                                                        dl));
16675   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16676   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16677                        false, false, 0);
16678   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16679
16680   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16681                      DAG.getRegister(StoreAddrReg, PtrVT));
16682 }
16683
16684 SDValue X86TargetLowering::LowerCATCHRET(SDValue Op, SelectionDAG &DAG) const {
16685   SDValue Chain = Op.getOperand(0);
16686   SDValue Dest = Op.getOperand(1);
16687   SDLoc DL(Op);
16688
16689   MVT PtrVT = getPointerTy(DAG.getDataLayout());
16690   unsigned ReturnReg = (PtrVT == MVT::i64 ? X86::RAX : X86::EAX);
16691
16692   // Load the address of the destination block.
16693   MachineBasicBlock *DestMBB = cast<BasicBlockSDNode>(Dest)->getBasicBlock();
16694   SDValue BlockPtr = DAG.getMCSymbol(DestMBB->getSymbol(), PtrVT);
16695   unsigned WrapperKind =
16696       Subtarget->isPICStyleRIPRel() ? X86ISD::WrapperRIP : X86ISD::Wrapper;
16697   SDValue WrappedPtr = DAG.getNode(WrapperKind, DL, PtrVT, BlockPtr);
16698   Chain = DAG.getCopyToReg(Chain, DL, ReturnReg, WrappedPtr);
16699   return DAG.getNode(X86ISD::CATCHRET, DL, MVT::Other, Chain,
16700                      DAG.getRegister(ReturnReg, PtrVT));
16701 }
16702
16703 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16704                                                SelectionDAG &DAG) const {
16705   SDLoc DL(Op);
16706   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16707                      DAG.getVTList(MVT::i32, MVT::Other),
16708                      Op.getOperand(0), Op.getOperand(1));
16709 }
16710
16711 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16712                                                 SelectionDAG &DAG) const {
16713   SDLoc DL(Op);
16714   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16715                      Op.getOperand(0), Op.getOperand(1));
16716 }
16717
16718 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16719   return Op.getOperand(0);
16720 }
16721
16722 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16723                                                 SelectionDAG &DAG) const {
16724   SDValue Root = Op.getOperand(0);
16725   SDValue Trmp = Op.getOperand(1); // trampoline
16726   SDValue FPtr = Op.getOperand(2); // nested function
16727   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16728   SDLoc dl (Op);
16729
16730   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16731   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16732
16733   if (Subtarget->is64Bit()) {
16734     SDValue OutChains[6];
16735
16736     // Large code-model.
16737     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16738     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16739
16740     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16741     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16742
16743     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16744
16745     // Load the pointer to the nested function into R11.
16746     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16747     SDValue Addr = Trmp;
16748     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16749                                 Addr, MachinePointerInfo(TrmpAddr),
16750                                 false, false, 0);
16751
16752     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16753                        DAG.getConstant(2, dl, MVT::i64));
16754     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16755                                 MachinePointerInfo(TrmpAddr, 2),
16756                                 false, false, 2);
16757
16758     // Load the 'nest' parameter value into R10.
16759     // R10 is specified in X86CallingConv.td
16760     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16761     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16762                        DAG.getConstant(10, dl, MVT::i64));
16763     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16764                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16765                                 false, false, 0);
16766
16767     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16768                        DAG.getConstant(12, dl, MVT::i64));
16769     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16770                                 MachinePointerInfo(TrmpAddr, 12),
16771                                 false, false, 2);
16772
16773     // Jump to the nested function.
16774     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16775     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16776                        DAG.getConstant(20, dl, MVT::i64));
16777     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16778                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16779                                 false, false, 0);
16780
16781     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16782     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16783                        DAG.getConstant(22, dl, MVT::i64));
16784     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16785                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16786                                 false, false, 0);
16787
16788     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16789   } else {
16790     const Function *Func =
16791       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16792     CallingConv::ID CC = Func->getCallingConv();
16793     unsigned NestReg;
16794
16795     switch (CC) {
16796     default:
16797       llvm_unreachable("Unsupported calling convention");
16798     case CallingConv::C:
16799     case CallingConv::X86_StdCall: {
16800       // Pass 'nest' parameter in ECX.
16801       // Must be kept in sync with X86CallingConv.td
16802       NestReg = X86::ECX;
16803
16804       // Check that ECX wasn't needed by an 'inreg' parameter.
16805       FunctionType *FTy = Func->getFunctionType();
16806       const AttributeSet &Attrs = Func->getAttributes();
16807
16808       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16809         unsigned InRegCount = 0;
16810         unsigned Idx = 1;
16811
16812         for (FunctionType::param_iterator I = FTy->param_begin(),
16813              E = FTy->param_end(); I != E; ++I, ++Idx)
16814           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
16815             auto &DL = DAG.getDataLayout();
16816             // FIXME: should only count parameters that are lowered to integers.
16817             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16818           }
16819
16820         if (InRegCount > 2) {
16821           report_fatal_error("Nest register in use - reduce number of inreg"
16822                              " parameters!");
16823         }
16824       }
16825       break;
16826     }
16827     case CallingConv::X86_FastCall:
16828     case CallingConv::X86_ThisCall:
16829     case CallingConv::Fast:
16830       // Pass 'nest' parameter in EAX.
16831       // Must be kept in sync with X86CallingConv.td
16832       NestReg = X86::EAX;
16833       break;
16834     }
16835
16836     SDValue OutChains[4];
16837     SDValue Addr, Disp;
16838
16839     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16840                        DAG.getConstant(10, dl, MVT::i32));
16841     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16842
16843     // This is storing the opcode for MOV32ri.
16844     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16845     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16846     OutChains[0] = DAG.getStore(Root, dl,
16847                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16848                                 Trmp, MachinePointerInfo(TrmpAddr),
16849                                 false, false, 0);
16850
16851     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16852                        DAG.getConstant(1, dl, MVT::i32));
16853     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16854                                 MachinePointerInfo(TrmpAddr, 1),
16855                                 false, false, 1);
16856
16857     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16858     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16859                        DAG.getConstant(5, dl, MVT::i32));
16860     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16861                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16862                                 false, false, 1);
16863
16864     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16865                        DAG.getConstant(6, dl, MVT::i32));
16866     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16867                                 MachinePointerInfo(TrmpAddr, 6),
16868                                 false, false, 1);
16869
16870     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16871   }
16872 }
16873
16874 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16875                                             SelectionDAG &DAG) const {
16876   /*
16877    The rounding mode is in bits 11:10 of FPSR, and has the following
16878    settings:
16879      00 Round to nearest
16880      01 Round to -inf
16881      10 Round to +inf
16882      11 Round to 0
16883
16884   FLT_ROUNDS, on the other hand, expects the following:
16885     -1 Undefined
16886      0 Round to 0
16887      1 Round to nearest
16888      2 Round to +inf
16889      3 Round to -inf
16890
16891   To perform the conversion, we do:
16892     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16893   */
16894
16895   MachineFunction &MF = DAG.getMachineFunction();
16896   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16897   unsigned StackAlignment = TFI.getStackAlignment();
16898   MVT VT = Op.getSimpleValueType();
16899   SDLoc DL(Op);
16900
16901   // Save FP Control Word to stack slot
16902   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16903   SDValue StackSlot =
16904       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16905
16906   MachineMemOperand *MMO =
16907       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
16908                               MachineMemOperand::MOStore, 2, 2);
16909
16910   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16911   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16912                                           DAG.getVTList(MVT::Other),
16913                                           Ops, MVT::i16, MMO);
16914
16915   // Load FP Control Word from stack slot
16916   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16917                             MachinePointerInfo(), false, false, false, 0);
16918
16919   // Transform as necessary
16920   SDValue CWD1 =
16921     DAG.getNode(ISD::SRL, DL, MVT::i16,
16922                 DAG.getNode(ISD::AND, DL, MVT::i16,
16923                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16924                 DAG.getConstant(11, DL, MVT::i8));
16925   SDValue CWD2 =
16926     DAG.getNode(ISD::SRL, DL, MVT::i16,
16927                 DAG.getNode(ISD::AND, DL, MVT::i16,
16928                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16929                 DAG.getConstant(9, DL, MVT::i8));
16930
16931   SDValue RetVal =
16932     DAG.getNode(ISD::AND, DL, MVT::i16,
16933                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16934                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16935                             DAG.getConstant(1, DL, MVT::i16)),
16936                 DAG.getConstant(3, DL, MVT::i16));
16937
16938   return DAG.getNode((VT.getSizeInBits() < 16 ?
16939                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16940 }
16941
16942 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16943   MVT VT = Op.getSimpleValueType();
16944   EVT OpVT = VT;
16945   unsigned NumBits = VT.getSizeInBits();
16946   SDLoc dl(Op);
16947
16948   Op = Op.getOperand(0);
16949   if (VT == MVT::i8) {
16950     // Zero extend to i32 since there is not an i8 bsr.
16951     OpVT = MVT::i32;
16952     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16953   }
16954
16955   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16956   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16957   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16958
16959   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16960   SDValue Ops[] = {
16961     Op,
16962     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16963     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16964     Op.getValue(1)
16965   };
16966   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16967
16968   // Finally xor with NumBits-1.
16969   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16970                    DAG.getConstant(NumBits - 1, dl, OpVT));
16971
16972   if (VT == MVT::i8)
16973     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16974   return Op;
16975 }
16976
16977 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16978   MVT VT = Op.getSimpleValueType();
16979   EVT OpVT = VT;
16980   unsigned NumBits = VT.getSizeInBits();
16981   SDLoc dl(Op);
16982
16983   Op = Op.getOperand(0);
16984   if (VT == MVT::i8) {
16985     // Zero extend to i32 since there is not an i8 bsr.
16986     OpVT = MVT::i32;
16987     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16988   }
16989
16990   // Issue a bsr (scan bits in reverse).
16991   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16992   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16993
16994   // And xor with NumBits-1.
16995   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16996                    DAG.getConstant(NumBits - 1, dl, OpVT));
16997
16998   if (VT == MVT::i8)
16999     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17000   return Op;
17001 }
17002
17003 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17004   MVT VT = Op.getSimpleValueType();
17005   unsigned NumBits = VT.getSizeInBits();
17006   SDLoc dl(Op);
17007   Op = Op.getOperand(0);
17008
17009   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17010   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17011   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
17012
17013   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17014   SDValue Ops[] = {
17015     Op,
17016     DAG.getConstant(NumBits, dl, VT),
17017     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17018     Op.getValue(1)
17019   };
17020   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17021 }
17022
17023 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17024 // ones, and then concatenate the result back.
17025 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17026   MVT VT = Op.getSimpleValueType();
17027
17028   assert(VT.is256BitVector() && VT.isInteger() &&
17029          "Unsupported value type for operation");
17030
17031   unsigned NumElems = VT.getVectorNumElements();
17032   SDLoc dl(Op);
17033
17034   // Extract the LHS vectors
17035   SDValue LHS = Op.getOperand(0);
17036   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17037   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17038
17039   // Extract the RHS vectors
17040   SDValue RHS = Op.getOperand(1);
17041   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17042   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17043
17044   MVT EltVT = VT.getVectorElementType();
17045   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17046
17047   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17048                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17049                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17050 }
17051
17052 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17053   if (Op.getValueType() == MVT::i1)
17054     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17055                        Op.getOperand(0), Op.getOperand(1));
17056   assert(Op.getSimpleValueType().is256BitVector() &&
17057          Op.getSimpleValueType().isInteger() &&
17058          "Only handle AVX 256-bit vector integer operation");
17059   return Lower256IntArith(Op, DAG);
17060 }
17061
17062 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17063   if (Op.getValueType() == MVT::i1)
17064     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17065                        Op.getOperand(0), Op.getOperand(1));
17066   assert(Op.getSimpleValueType().is256BitVector() &&
17067          Op.getSimpleValueType().isInteger() &&
17068          "Only handle AVX 256-bit vector integer operation");
17069   return Lower256IntArith(Op, DAG);
17070 }
17071
17072 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17073   assert(Op.getSimpleValueType().is256BitVector() &&
17074          Op.getSimpleValueType().isInteger() &&
17075          "Only handle AVX 256-bit vector integer operation");
17076   return Lower256IntArith(Op, DAG);
17077 }
17078
17079 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17080                         SelectionDAG &DAG) {
17081   SDLoc dl(Op);
17082   MVT VT = Op.getSimpleValueType();
17083
17084   if (VT == MVT::i1)
17085     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17086
17087   // Decompose 256-bit ops into smaller 128-bit ops.
17088   if (VT.is256BitVector() && !Subtarget->hasInt256())
17089     return Lower256IntArith(Op, DAG);
17090
17091   SDValue A = Op.getOperand(0);
17092   SDValue B = Op.getOperand(1);
17093
17094   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17095   // pairs, multiply and truncate.
17096   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17097     if (Subtarget->hasInt256()) {
17098       if (VT == MVT::v32i8) {
17099         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17100         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17101         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17102         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17103         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17104         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17105         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17106         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17107                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17108                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17109       }
17110
17111       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17112       return DAG.getNode(
17113           ISD::TRUNCATE, dl, VT,
17114           DAG.getNode(ISD::MUL, dl, ExVT,
17115                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17116                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17117     }
17118
17119     assert(VT == MVT::v16i8 &&
17120            "Pre-AVX2 support only supports v16i8 multiplication");
17121     MVT ExVT = MVT::v8i16;
17122
17123     // Extract the lo parts and sign extend to i16
17124     SDValue ALo, BLo;
17125     if (Subtarget->hasSSE41()) {
17126       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17127       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17128     } else {
17129       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17130                               -1, 4, -1, 5, -1, 6, -1, 7};
17131       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17132       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17133       ALo = DAG.getBitcast(ExVT, ALo);
17134       BLo = DAG.getBitcast(ExVT, BLo);
17135       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17136       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17137     }
17138
17139     // Extract the hi parts and sign extend to i16
17140     SDValue AHi, BHi;
17141     if (Subtarget->hasSSE41()) {
17142       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17143                               -1, -1, -1, -1, -1, -1, -1, -1};
17144       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17145       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17146       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17147       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17148     } else {
17149       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17150                               -1, 12, -1, 13, -1, 14, -1, 15};
17151       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17152       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17153       AHi = DAG.getBitcast(ExVT, AHi);
17154       BHi = DAG.getBitcast(ExVT, BHi);
17155       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17156       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17157     }
17158
17159     // Multiply, mask the lower 8bits of the lo/hi results and pack
17160     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17161     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17162     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17163     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17164     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17165   }
17166
17167   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17168   if (VT == MVT::v4i32) {
17169     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17170            "Should not custom lower when pmuldq is available!");
17171
17172     // Extract the odd parts.
17173     static const int UnpackMask[] = { 1, -1, 3, -1 };
17174     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17175     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17176
17177     // Multiply the even parts.
17178     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17179     // Now multiply odd parts.
17180     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17181
17182     Evens = DAG.getBitcast(VT, Evens);
17183     Odds = DAG.getBitcast(VT, Odds);
17184
17185     // Merge the two vectors back together with a shuffle. This expands into 2
17186     // shuffles.
17187     static const int ShufMask[] = { 0, 4, 2, 6 };
17188     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17189   }
17190
17191   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17192          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17193
17194   //  Ahi = psrlqi(a, 32);
17195   //  Bhi = psrlqi(b, 32);
17196   //
17197   //  AloBlo = pmuludq(a, b);
17198   //  AloBhi = pmuludq(a, Bhi);
17199   //  AhiBlo = pmuludq(Ahi, b);
17200
17201   //  AloBhi = psllqi(AloBhi, 32);
17202   //  AhiBlo = psllqi(AhiBlo, 32);
17203   //  return AloBlo + AloBhi + AhiBlo;
17204
17205   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17206   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17207
17208   SDValue AhiBlo = Ahi;
17209   SDValue AloBhi = Bhi;
17210   // Bit cast to 32-bit vectors for MULUDQ
17211   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17212                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17213   A = DAG.getBitcast(MulVT, A);
17214   B = DAG.getBitcast(MulVT, B);
17215   Ahi = DAG.getBitcast(MulVT, Ahi);
17216   Bhi = DAG.getBitcast(MulVT, Bhi);
17217
17218   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17219   // After shifting right const values the result may be all-zero.
17220   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17221     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17222     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17223   }
17224   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17225     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17226     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17227   }
17228
17229   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17230   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17231 }
17232
17233 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17234   assert(Subtarget->isTargetWin64() && "Unexpected target");
17235   EVT VT = Op.getValueType();
17236   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17237          "Unexpected return type for lowering");
17238
17239   RTLIB::Libcall LC;
17240   bool isSigned;
17241   switch (Op->getOpcode()) {
17242   default: llvm_unreachable("Unexpected request for libcall!");
17243   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17244   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17245   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17246   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17247   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17248   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17249   }
17250
17251   SDLoc dl(Op);
17252   SDValue InChain = DAG.getEntryNode();
17253
17254   TargetLowering::ArgListTy Args;
17255   TargetLowering::ArgListEntry Entry;
17256   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17257     EVT ArgVT = Op->getOperand(i).getValueType();
17258     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17259            "Unexpected argument type for lowering");
17260     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17261     Entry.Node = StackPtr;
17262     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17263                            false, false, 16);
17264     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17265     Entry.Ty = PointerType::get(ArgTy,0);
17266     Entry.isSExt = false;
17267     Entry.isZExt = false;
17268     Args.push_back(Entry);
17269   }
17270
17271   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17272                                          getPointerTy(DAG.getDataLayout()));
17273
17274   TargetLowering::CallLoweringInfo CLI(DAG);
17275   CLI.setDebugLoc(dl).setChain(InChain)
17276     .setCallee(getLibcallCallingConv(LC),
17277                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17278                Callee, std::move(Args), 0)
17279     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17280
17281   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17282   return DAG.getBitcast(VT, CallInfo.first);
17283 }
17284
17285 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17286                              SelectionDAG &DAG) {
17287   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17288   EVT VT = Op0.getValueType();
17289   SDLoc dl(Op);
17290
17291   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17292          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17293
17294   // PMULxD operations multiply each even value (starting at 0) of LHS with
17295   // the related value of RHS and produce a widen result.
17296   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17297   // => <2 x i64> <ae|cg>
17298   //
17299   // In other word, to have all the results, we need to perform two PMULxD:
17300   // 1. one with the even values.
17301   // 2. one with the odd values.
17302   // To achieve #2, with need to place the odd values at an even position.
17303   //
17304   // Place the odd value at an even position (basically, shift all values 1
17305   // step to the left):
17306   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17307   // <a|b|c|d> => <b|undef|d|undef>
17308   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17309   // <e|f|g|h> => <f|undef|h|undef>
17310   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17311
17312   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17313   // ints.
17314   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17315   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17316   unsigned Opcode =
17317       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17318   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17319   // => <2 x i64> <ae|cg>
17320   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17321   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17322   // => <2 x i64> <bf|dh>
17323   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17324
17325   // Shuffle it back into the right order.
17326   SDValue Highs, Lows;
17327   if (VT == MVT::v8i32) {
17328     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17329     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17330     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17331     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17332   } else {
17333     const int HighMask[] = {1, 5, 3, 7};
17334     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17335     const int LowMask[] = {0, 4, 2, 6};
17336     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17337   }
17338
17339   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17340   // unsigned multiply.
17341   if (IsSigned && !Subtarget->hasSSE41()) {
17342     SDValue ShAmt = DAG.getConstant(
17343         31, dl,
17344         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17345     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17346                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17347     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17348                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17349
17350     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17351     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17352   }
17353
17354   // The first result of MUL_LOHI is actually the low value, followed by the
17355   // high value.
17356   SDValue Ops[] = {Lows, Highs};
17357   return DAG.getMergeValues(Ops, dl);
17358 }
17359
17360 // Return true if the required (according to Opcode) shift-imm form is natively
17361 // supported by the Subtarget
17362 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17363                                         unsigned Opcode) {
17364   if (VT.getScalarSizeInBits() < 16)
17365     return false;
17366
17367   if (VT.is512BitVector() &&
17368       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17369     return true;
17370
17371   bool LShift = VT.is128BitVector() ||
17372     (VT.is256BitVector() && Subtarget->hasInt256());
17373
17374   bool AShift = LShift && (Subtarget->hasVLX() ||
17375     (VT != MVT::v2i64 && VT != MVT::v4i64));
17376   return (Opcode == ISD::SRA) ? AShift : LShift;
17377 }
17378
17379 // The shift amount is a variable, but it is the same for all vector lanes.
17380 // These instructions are defined together with shift-immediate.
17381 static
17382 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17383                                       unsigned Opcode) {
17384   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17385 }
17386
17387 // Return true if the required (according to Opcode) variable-shift form is
17388 // natively supported by the Subtarget
17389 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17390                                     unsigned Opcode) {
17391
17392   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17393     return false;
17394
17395   // vXi16 supported only on AVX-512, BWI
17396   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17397     return false;
17398
17399   if (VT.is512BitVector() || Subtarget->hasVLX())
17400     return true;
17401
17402   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17403   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17404   return (Opcode == ISD::SRA) ? AShift : LShift;
17405 }
17406
17407 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17408                                          const X86Subtarget *Subtarget) {
17409   MVT VT = Op.getSimpleValueType();
17410   SDLoc dl(Op);
17411   SDValue R = Op.getOperand(0);
17412   SDValue Amt = Op.getOperand(1);
17413
17414   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17415     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17416
17417   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17418     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17419     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17420     SDValue Ex = DAG.getBitcast(ExVT, R);
17421
17422     if (ShiftAmt >= 32) {
17423       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17424       SDValue Upper =
17425           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17426       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17427                                                  ShiftAmt - 32, DAG);
17428       if (VT == MVT::v2i64)
17429         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17430       if (VT == MVT::v4i64)
17431         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17432                                   {9, 1, 11, 3, 13, 5, 15, 7});
17433     } else {
17434       // SRA upper i32, SHL whole i64 and select lower i32.
17435       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17436                                                  ShiftAmt, DAG);
17437       SDValue Lower =
17438           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17439       Lower = DAG.getBitcast(ExVT, Lower);
17440       if (VT == MVT::v2i64)
17441         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17442       if (VT == MVT::v4i64)
17443         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17444                                   {8, 1, 10, 3, 12, 5, 14, 7});
17445     }
17446     return DAG.getBitcast(VT, Ex);
17447   };
17448
17449   // Optimize shl/srl/sra with constant shift amount.
17450   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17451     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17452       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17453
17454       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17455         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17456
17457       // i64 SRA needs to be performed as partial shifts.
17458       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17459           Op.getOpcode() == ISD::SRA)
17460         return ArithmeticShiftRight64(ShiftAmt);
17461
17462       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17463         unsigned NumElts = VT.getVectorNumElements();
17464         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17465
17466         if (Op.getOpcode() == ISD::SHL) {
17467           // Simple i8 add case
17468           if (ShiftAmt == 1)
17469             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17470
17471           // Make a large shift.
17472           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17473                                                    R, ShiftAmt, DAG);
17474           SHL = DAG.getBitcast(VT, SHL);
17475           // Zero out the rightmost bits.
17476           SmallVector<SDValue, 32> V(
17477               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17478           return DAG.getNode(ISD::AND, dl, VT, SHL,
17479                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17480         }
17481         if (Op.getOpcode() == ISD::SRL) {
17482           // Make a large shift.
17483           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17484                                                    R, ShiftAmt, DAG);
17485           SRL = DAG.getBitcast(VT, SRL);
17486           // Zero out the leftmost bits.
17487           SmallVector<SDValue, 32> V(
17488               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17489           return DAG.getNode(ISD::AND, dl, VT, SRL,
17490                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17491         }
17492         if (Op.getOpcode() == ISD::SRA) {
17493           if (ShiftAmt == 7) {
17494             // ashr(R, 7)  === cmp_slt(R, 0)
17495             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17496             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17497           }
17498
17499           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17500           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17501           SmallVector<SDValue, 32> V(NumElts,
17502                                      DAG.getConstant(128 >> ShiftAmt, dl,
17503                                                      MVT::i8));
17504           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17505           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17506           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17507           return Res;
17508         }
17509         llvm_unreachable("Unknown shift opcode.");
17510       }
17511     }
17512   }
17513
17514   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17515   if (!Subtarget->is64Bit() &&
17516       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17517
17518     // Peek through any splat that was introduced for i64 shift vectorization.
17519     int SplatIndex = -1;
17520     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17521       if (SVN->isSplat()) {
17522         SplatIndex = SVN->getSplatIndex();
17523         Amt = Amt.getOperand(0);
17524         assert(SplatIndex < (int)VT.getVectorNumElements() &&
17525                "Splat shuffle referencing second operand");
17526       }
17527
17528     if (Amt.getOpcode() != ISD::BITCAST ||
17529         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17530       return SDValue();
17531
17532     Amt = Amt.getOperand(0);
17533     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17534                      VT.getVectorNumElements();
17535     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17536     uint64_t ShiftAmt = 0;
17537     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17538     for (unsigned i = 0; i != Ratio; ++i) {
17539       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17540       if (!C)
17541         return SDValue();
17542       // 6 == Log2(64)
17543       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17544     }
17545
17546     // Check remaining shift amounts (if not a splat).
17547     if (SplatIndex < 0) {
17548       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17549         uint64_t ShAmt = 0;
17550         for (unsigned j = 0; j != Ratio; ++j) {
17551           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17552           if (!C)
17553             return SDValue();
17554           // 6 == Log2(64)
17555           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17556         }
17557         if (ShAmt != ShiftAmt)
17558           return SDValue();
17559       }
17560     }
17561
17562     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17563       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17564
17565     if (Op.getOpcode() == ISD::SRA)
17566       return ArithmeticShiftRight64(ShiftAmt);
17567   }
17568
17569   return SDValue();
17570 }
17571
17572 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17573                                         const X86Subtarget* Subtarget) {
17574   MVT VT = Op.getSimpleValueType();
17575   SDLoc dl(Op);
17576   SDValue R = Op.getOperand(0);
17577   SDValue Amt = Op.getOperand(1);
17578
17579   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17580     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17581
17582   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17583     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17584
17585   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17586     SDValue BaseShAmt;
17587     EVT EltVT = VT.getVectorElementType();
17588
17589     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17590       // Check if this build_vector node is doing a splat.
17591       // If so, then set BaseShAmt equal to the splat value.
17592       BaseShAmt = BV->getSplatValue();
17593       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17594         BaseShAmt = SDValue();
17595     } else {
17596       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17597         Amt = Amt.getOperand(0);
17598
17599       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17600       if (SVN && SVN->isSplat()) {
17601         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17602         SDValue InVec = Amt.getOperand(0);
17603         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17604           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17605                  "Unexpected shuffle index found!");
17606           BaseShAmt = InVec.getOperand(SplatIdx);
17607         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17608            if (ConstantSDNode *C =
17609                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17610              if (C->getZExtValue() == SplatIdx)
17611                BaseShAmt = InVec.getOperand(1);
17612            }
17613         }
17614
17615         if (!BaseShAmt)
17616           // Avoid introducing an extract element from a shuffle.
17617           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17618                                   DAG.getIntPtrConstant(SplatIdx, dl));
17619       }
17620     }
17621
17622     if (BaseShAmt.getNode()) {
17623       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17624       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17625         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17626       else if (EltVT.bitsLT(MVT::i32))
17627         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17628
17629       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17630     }
17631   }
17632
17633   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17634   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17635       Amt.getOpcode() == ISD::BITCAST &&
17636       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17637     Amt = Amt.getOperand(0);
17638     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17639                      VT.getVectorNumElements();
17640     std::vector<SDValue> Vals(Ratio);
17641     for (unsigned i = 0; i != Ratio; ++i)
17642       Vals[i] = Amt.getOperand(i);
17643     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17644       for (unsigned j = 0; j != Ratio; ++j)
17645         if (Vals[j] != Amt.getOperand(i + j))
17646           return SDValue();
17647     }
17648
17649     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17650       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17651   }
17652   return SDValue();
17653 }
17654
17655 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17656                           SelectionDAG &DAG) {
17657   MVT VT = Op.getSimpleValueType();
17658   SDLoc dl(Op);
17659   SDValue R = Op.getOperand(0);
17660   SDValue Amt = Op.getOperand(1);
17661
17662   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17663   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17664
17665   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17666     return V;
17667
17668   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17669       return V;
17670
17671   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17672     return Op;
17673
17674   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17675   // shifts per-lane and then shuffle the partial results back together.
17676   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17677     // Splat the shift amounts so the scalar shifts above will catch it.
17678     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17679     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17680     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17681     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17682     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17683   }
17684
17685   // i64 vector arithmetic shift can be emulated with the transform:
17686   // M = lshr(SIGN_BIT, Amt)
17687   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17688   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17689       Op.getOpcode() == ISD::SRA) {
17690     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17691     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17692     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17693     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17694     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17695     return R;
17696   }
17697
17698   // If possible, lower this packed shift into a vector multiply instead of
17699   // expanding it into a sequence of scalar shifts.
17700   // Do this only if the vector shift count is a constant build_vector.
17701   if (Op.getOpcode() == ISD::SHL &&
17702       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17703        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17704       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17705     SmallVector<SDValue, 8> Elts;
17706     EVT SVT = VT.getScalarType();
17707     unsigned SVTBits = SVT.getSizeInBits();
17708     const APInt &One = APInt(SVTBits, 1);
17709     unsigned NumElems = VT.getVectorNumElements();
17710
17711     for (unsigned i=0; i !=NumElems; ++i) {
17712       SDValue Op = Amt->getOperand(i);
17713       if (Op->getOpcode() == ISD::UNDEF) {
17714         Elts.push_back(Op);
17715         continue;
17716       }
17717
17718       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17719       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17720       uint64_t ShAmt = C.getZExtValue();
17721       if (ShAmt >= SVTBits) {
17722         Elts.push_back(DAG.getUNDEF(SVT));
17723         continue;
17724       }
17725       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17726     }
17727     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17728     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17729   }
17730
17731   // Lower SHL with variable shift amount.
17732   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17733     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17734
17735     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17736                      DAG.getConstant(0x3f800000U, dl, VT));
17737     Op = DAG.getBitcast(MVT::v4f32, Op);
17738     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17739     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17740   }
17741
17742   // If possible, lower this shift as a sequence of two shifts by
17743   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17744   // Example:
17745   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17746   //
17747   // Could be rewritten as:
17748   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17749   //
17750   // The advantage is that the two shifts from the example would be
17751   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17752   // the vector shift into four scalar shifts plus four pairs of vector
17753   // insert/extract.
17754   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17755       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17756     unsigned TargetOpcode = X86ISD::MOVSS;
17757     bool CanBeSimplified;
17758     // The splat value for the first packed shift (the 'X' from the example).
17759     SDValue Amt1 = Amt->getOperand(0);
17760     // The splat value for the second packed shift (the 'Y' from the example).
17761     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17762                                         Amt->getOperand(2);
17763
17764     // See if it is possible to replace this node with a sequence of
17765     // two shifts followed by a MOVSS/MOVSD
17766     if (VT == MVT::v4i32) {
17767       // Check if it is legal to use a MOVSS.
17768       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17769                         Amt2 == Amt->getOperand(3);
17770       if (!CanBeSimplified) {
17771         // Otherwise, check if we can still simplify this node using a MOVSD.
17772         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17773                           Amt->getOperand(2) == Amt->getOperand(3);
17774         TargetOpcode = X86ISD::MOVSD;
17775         Amt2 = Amt->getOperand(2);
17776       }
17777     } else {
17778       // Do similar checks for the case where the machine value type
17779       // is MVT::v8i16.
17780       CanBeSimplified = Amt1 == Amt->getOperand(1);
17781       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17782         CanBeSimplified = Amt2 == Amt->getOperand(i);
17783
17784       if (!CanBeSimplified) {
17785         TargetOpcode = X86ISD::MOVSD;
17786         CanBeSimplified = true;
17787         Amt2 = Amt->getOperand(4);
17788         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17789           CanBeSimplified = Amt1 == Amt->getOperand(i);
17790         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17791           CanBeSimplified = Amt2 == Amt->getOperand(j);
17792       }
17793     }
17794
17795     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17796         isa<ConstantSDNode>(Amt2)) {
17797       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17798       EVT CastVT = MVT::v4i32;
17799       SDValue Splat1 =
17800         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17801       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17802       SDValue Splat2 =
17803         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17804       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17805       if (TargetOpcode == X86ISD::MOVSD)
17806         CastVT = MVT::v2i64;
17807       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17808       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17809       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17810                                             BitCast1, DAG);
17811       return DAG.getBitcast(VT, Result);
17812     }
17813   }
17814
17815   // v4i32 Non Uniform Shifts.
17816   // If the shift amount is constant we can shift each lane using the SSE2
17817   // immediate shifts, else we need to zero-extend each lane to the lower i64
17818   // and shift using the SSE2 variable shifts.
17819   // The separate results can then be blended together.
17820   if (VT == MVT::v4i32) {
17821     unsigned Opc = Op.getOpcode();
17822     SDValue Amt0, Amt1, Amt2, Amt3;
17823     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17824       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17825       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17826       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17827       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17828     } else {
17829       // ISD::SHL is handled above but we include it here for completeness.
17830       switch (Opc) {
17831       default:
17832         llvm_unreachable("Unknown target vector shift node");
17833       case ISD::SHL:
17834         Opc = X86ISD::VSHL;
17835         break;
17836       case ISD::SRL:
17837         Opc = X86ISD::VSRL;
17838         break;
17839       case ISD::SRA:
17840         Opc = X86ISD::VSRA;
17841         break;
17842       }
17843       // The SSE2 shifts use the lower i64 as the same shift amount for
17844       // all lanes and the upper i64 is ignored. These shuffle masks
17845       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17846       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17847       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17848       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17849       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17850       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17851     }
17852
17853     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17854     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17855     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17856     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17857     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17858     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17859     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17860   }
17861
17862   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17863     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17864     unsigned ShiftOpcode = Op->getOpcode();
17865
17866     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17867       // On SSE41 targets we make use of the fact that VSELECT lowers
17868       // to PBLENDVB which selects bytes based just on the sign bit.
17869       if (Subtarget->hasSSE41()) {
17870         V0 = DAG.getBitcast(VT, V0);
17871         V1 = DAG.getBitcast(VT, V1);
17872         Sel = DAG.getBitcast(VT, Sel);
17873         return DAG.getBitcast(SelVT,
17874                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17875       }
17876       // On pre-SSE41 targets we test for the sign bit by comparing to
17877       // zero - a negative value will set all bits of the lanes to true
17878       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17879       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17880       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17881       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17882     };
17883
17884     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17885     // We can safely do this using i16 shifts as we're only interested in
17886     // the 3 lower bits of each byte.
17887     Amt = DAG.getBitcast(ExtVT, Amt);
17888     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17889     Amt = DAG.getBitcast(VT, Amt);
17890
17891     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17892       // r = VSELECT(r, shift(r, 4), a);
17893       SDValue M =
17894           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17895       R = SignBitSelect(VT, Amt, M, R);
17896
17897       // a += a
17898       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17899
17900       // r = VSELECT(r, shift(r, 2), a);
17901       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17902       R = SignBitSelect(VT, Amt, M, R);
17903
17904       // a += a
17905       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17906
17907       // return VSELECT(r, shift(r, 1), a);
17908       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17909       R = SignBitSelect(VT, Amt, M, R);
17910       return R;
17911     }
17912
17913     if (Op->getOpcode() == ISD::SRA) {
17914       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17915       // so we can correctly sign extend. We don't care what happens to the
17916       // lower byte.
17917       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17918       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17919       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17920       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17921       ALo = DAG.getBitcast(ExtVT, ALo);
17922       AHi = DAG.getBitcast(ExtVT, AHi);
17923       RLo = DAG.getBitcast(ExtVT, RLo);
17924       RHi = DAG.getBitcast(ExtVT, RHi);
17925
17926       // r = VSELECT(r, shift(r, 4), a);
17927       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17928                                 DAG.getConstant(4, dl, ExtVT));
17929       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17930                                 DAG.getConstant(4, dl, ExtVT));
17931       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17932       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17933
17934       // a += a
17935       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17936       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17937
17938       // r = VSELECT(r, shift(r, 2), a);
17939       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17940                         DAG.getConstant(2, dl, ExtVT));
17941       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17942                         DAG.getConstant(2, dl, ExtVT));
17943       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17944       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17945
17946       // a += a
17947       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17948       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17949
17950       // r = VSELECT(r, shift(r, 1), a);
17951       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17952                         DAG.getConstant(1, dl, ExtVT));
17953       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17954                         DAG.getConstant(1, dl, ExtVT));
17955       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17956       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17957
17958       // Logical shift the result back to the lower byte, leaving a zero upper
17959       // byte
17960       // meaning that we can safely pack with PACKUSWB.
17961       RLo =
17962           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17963       RHi =
17964           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17965       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17966     }
17967   }
17968
17969   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17970   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17971   // solution better.
17972   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17973     MVT ExtVT = MVT::v8i32;
17974     unsigned ExtOpc =
17975         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17976     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17977     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17978     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17979                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17980   }
17981
17982   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17983     MVT ExtVT = MVT::v8i32;
17984     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17985     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17986     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17987     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17988     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17989     ALo = DAG.getBitcast(ExtVT, ALo);
17990     AHi = DAG.getBitcast(ExtVT, AHi);
17991     RLo = DAG.getBitcast(ExtVT, RLo);
17992     RHi = DAG.getBitcast(ExtVT, RHi);
17993     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17994     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17995     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17996     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17997     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17998   }
17999
18000   if (VT == MVT::v8i16) {
18001     unsigned ShiftOpcode = Op->getOpcode();
18002
18003     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18004       // On SSE41 targets we make use of the fact that VSELECT lowers
18005       // to PBLENDVB which selects bytes based just on the sign bit.
18006       if (Subtarget->hasSSE41()) {
18007         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18008         V0 = DAG.getBitcast(ExtVT, V0);
18009         V1 = DAG.getBitcast(ExtVT, V1);
18010         Sel = DAG.getBitcast(ExtVT, Sel);
18011         return DAG.getBitcast(
18012             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18013       }
18014       // On pre-SSE41 targets we splat the sign bit - a negative value will
18015       // set all bits of the lanes to true and VSELECT uses that in
18016       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18017       SDValue C =
18018           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18019       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18020     };
18021
18022     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18023     if (Subtarget->hasSSE41()) {
18024       // On SSE41 targets we need to replicate the shift mask in both
18025       // bytes for PBLENDVB.
18026       Amt = DAG.getNode(
18027           ISD::OR, dl, VT,
18028           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18029           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18030     } else {
18031       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18032     }
18033
18034     // r = VSELECT(r, shift(r, 8), a);
18035     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18036     R = SignBitSelect(Amt, M, R);
18037
18038     // a += a
18039     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18040
18041     // r = VSELECT(r, shift(r, 4), a);
18042     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18043     R = SignBitSelect(Amt, M, R);
18044
18045     // a += a
18046     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18047
18048     // r = VSELECT(r, shift(r, 2), a);
18049     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18050     R = SignBitSelect(Amt, M, R);
18051
18052     // a += a
18053     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18054
18055     // return VSELECT(r, shift(r, 1), a);
18056     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18057     R = SignBitSelect(Amt, M, R);
18058     return R;
18059   }
18060
18061   // Decompose 256-bit shifts into smaller 128-bit shifts.
18062   if (VT.is256BitVector()) {
18063     unsigned NumElems = VT.getVectorNumElements();
18064     MVT EltVT = VT.getVectorElementType();
18065     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18066
18067     // Extract the two vectors
18068     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18069     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18070
18071     // Recreate the shift amount vectors
18072     SDValue Amt1, Amt2;
18073     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18074       // Constant shift amount
18075       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18076       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18077       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18078
18079       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18080       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18081     } else {
18082       // Variable shift amount
18083       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18084       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18085     }
18086
18087     // Issue new vector shifts for the smaller types
18088     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18089     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18090
18091     // Concatenate the result back
18092     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18093   }
18094
18095   return SDValue();
18096 }
18097
18098 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18099   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18100   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18101   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18102   // has only one use.
18103   SDNode *N = Op.getNode();
18104   SDValue LHS = N->getOperand(0);
18105   SDValue RHS = N->getOperand(1);
18106   unsigned BaseOp = 0;
18107   unsigned Cond = 0;
18108   SDLoc DL(Op);
18109   switch (Op.getOpcode()) {
18110   default: llvm_unreachable("Unknown ovf instruction!");
18111   case ISD::SADDO:
18112     // A subtract of one will be selected as a INC. Note that INC doesn't
18113     // set CF, so we can't do this for UADDO.
18114     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18115       if (C->isOne()) {
18116         BaseOp = X86ISD::INC;
18117         Cond = X86::COND_O;
18118         break;
18119       }
18120     BaseOp = X86ISD::ADD;
18121     Cond = X86::COND_O;
18122     break;
18123   case ISD::UADDO:
18124     BaseOp = X86ISD::ADD;
18125     Cond = X86::COND_B;
18126     break;
18127   case ISD::SSUBO:
18128     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18129     // set CF, so we can't do this for USUBO.
18130     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18131       if (C->isOne()) {
18132         BaseOp = X86ISD::DEC;
18133         Cond = X86::COND_O;
18134         break;
18135       }
18136     BaseOp = X86ISD::SUB;
18137     Cond = X86::COND_O;
18138     break;
18139   case ISD::USUBO:
18140     BaseOp = X86ISD::SUB;
18141     Cond = X86::COND_B;
18142     break;
18143   case ISD::SMULO:
18144     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18145     Cond = X86::COND_O;
18146     break;
18147   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18148     if (N->getValueType(0) == MVT::i8) {
18149       BaseOp = X86ISD::UMUL8;
18150       Cond = X86::COND_O;
18151       break;
18152     }
18153     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18154                                  MVT::i32);
18155     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18156
18157     SDValue SetCC =
18158       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18159                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18160                   SDValue(Sum.getNode(), 2));
18161
18162     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18163   }
18164   }
18165
18166   // Also sets EFLAGS.
18167   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18168   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18169
18170   SDValue SetCC =
18171     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18172                 DAG.getConstant(Cond, DL, MVT::i32),
18173                 SDValue(Sum.getNode(), 1));
18174
18175   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18176 }
18177
18178 /// Returns true if the operand type is exactly twice the native width, and
18179 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18180 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18181 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18182 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18183   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18184
18185   if (OpWidth == 64)
18186     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18187   else if (OpWidth == 128)
18188     return Subtarget->hasCmpxchg16b();
18189   else
18190     return false;
18191 }
18192
18193 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18194   return needsCmpXchgNb(SI->getValueOperand()->getType());
18195 }
18196
18197 // Note: this turns large loads into lock cmpxchg8b/16b.
18198 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18199 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18200   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18201   return needsCmpXchgNb(PTy->getElementType());
18202 }
18203
18204 TargetLoweringBase::AtomicRMWExpansionKind
18205 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18206   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18207   Type *MemType = AI->getType();
18208
18209   // If the operand is too big, we must see if cmpxchg8/16b is available
18210   // and default to library calls otherwise.
18211   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18212     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
18213                                    : AtomicRMWExpansionKind::None;
18214   }
18215
18216   AtomicRMWInst::BinOp Op = AI->getOperation();
18217   switch (Op) {
18218   default:
18219     llvm_unreachable("Unknown atomic operation");
18220   case AtomicRMWInst::Xchg:
18221   case AtomicRMWInst::Add:
18222   case AtomicRMWInst::Sub:
18223     // It's better to use xadd, xsub or xchg for these in all cases.
18224     return AtomicRMWExpansionKind::None;
18225   case AtomicRMWInst::Or:
18226   case AtomicRMWInst::And:
18227   case AtomicRMWInst::Xor:
18228     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18229     // prefix to a normal instruction for these operations.
18230     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
18231                             : AtomicRMWExpansionKind::None;
18232   case AtomicRMWInst::Nand:
18233   case AtomicRMWInst::Max:
18234   case AtomicRMWInst::Min:
18235   case AtomicRMWInst::UMax:
18236   case AtomicRMWInst::UMin:
18237     // These always require a non-trivial set of data operations on x86. We must
18238     // use a cmpxchg loop.
18239     return AtomicRMWExpansionKind::CmpXChg;
18240   }
18241 }
18242
18243 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18244   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18245   // no-sse2). There isn't any reason to disable it if the target processor
18246   // supports it.
18247   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18248 }
18249
18250 LoadInst *
18251 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18252   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18253   Type *MemType = AI->getType();
18254   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18255   // there is no benefit in turning such RMWs into loads, and it is actually
18256   // harmful as it introduces a mfence.
18257   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18258     return nullptr;
18259
18260   auto Builder = IRBuilder<>(AI);
18261   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18262   auto SynchScope = AI->getSynchScope();
18263   // We must restrict the ordering to avoid generating loads with Release or
18264   // ReleaseAcquire orderings.
18265   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18266   auto Ptr = AI->getPointerOperand();
18267
18268   // Before the load we need a fence. Here is an example lifted from
18269   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18270   // is required:
18271   // Thread 0:
18272   //   x.store(1, relaxed);
18273   //   r1 = y.fetch_add(0, release);
18274   // Thread 1:
18275   //   y.fetch_add(42, acquire);
18276   //   r2 = x.load(relaxed);
18277   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18278   // lowered to just a load without a fence. A mfence flushes the store buffer,
18279   // making the optimization clearly correct.
18280   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18281   // otherwise, we might be able to be more aggressive on relaxed idempotent
18282   // rmw. In practice, they do not look useful, so we don't try to be
18283   // especially clever.
18284   if (SynchScope == SingleThread)
18285     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18286     // the IR level, so we must wrap it in an intrinsic.
18287     return nullptr;
18288
18289   if (!hasMFENCE(*Subtarget))
18290     // FIXME: it might make sense to use a locked operation here but on a
18291     // different cache-line to prevent cache-line bouncing. In practice it
18292     // is probably a small win, and x86 processors without mfence are rare
18293     // enough that we do not bother.
18294     return nullptr;
18295
18296   Function *MFence =
18297       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18298   Builder.CreateCall(MFence, {});
18299
18300   // Finally we can emit the atomic load.
18301   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18302           AI->getType()->getPrimitiveSizeInBits());
18303   Loaded->setAtomic(Order, SynchScope);
18304   AI->replaceAllUsesWith(Loaded);
18305   AI->eraseFromParent();
18306   return Loaded;
18307 }
18308
18309 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18310                                  SelectionDAG &DAG) {
18311   SDLoc dl(Op);
18312   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18313     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18314   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18315     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18316
18317   // The only fence that needs an instruction is a sequentially-consistent
18318   // cross-thread fence.
18319   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18320     if (hasMFENCE(*Subtarget))
18321       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18322
18323     SDValue Chain = Op.getOperand(0);
18324     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18325     SDValue Ops[] = {
18326       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18327       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18328       DAG.getRegister(0, MVT::i32),            // Index
18329       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18330       DAG.getRegister(0, MVT::i32),            // Segment.
18331       Zero,
18332       Chain
18333     };
18334     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18335     return SDValue(Res, 0);
18336   }
18337
18338   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18339   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18340 }
18341
18342 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18343                              SelectionDAG &DAG) {
18344   MVT T = Op.getSimpleValueType();
18345   SDLoc DL(Op);
18346   unsigned Reg = 0;
18347   unsigned size = 0;
18348   switch(T.SimpleTy) {
18349   default: llvm_unreachable("Invalid value type!");
18350   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18351   case MVT::i16: Reg = X86::AX;  size = 2; break;
18352   case MVT::i32: Reg = X86::EAX; size = 4; break;
18353   case MVT::i64:
18354     assert(Subtarget->is64Bit() && "Node not type legal!");
18355     Reg = X86::RAX; size = 8;
18356     break;
18357   }
18358   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18359                                   Op.getOperand(2), SDValue());
18360   SDValue Ops[] = { cpIn.getValue(0),
18361                     Op.getOperand(1),
18362                     Op.getOperand(3),
18363                     DAG.getTargetConstant(size, DL, MVT::i8),
18364                     cpIn.getValue(1) };
18365   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18366   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18367   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18368                                            Ops, T, MMO);
18369
18370   SDValue cpOut =
18371     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18372   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18373                                       MVT::i32, cpOut.getValue(2));
18374   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18375                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18376                                 EFLAGS);
18377
18378   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18379   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18380   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18381   return SDValue();
18382 }
18383
18384 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18385                             SelectionDAG &DAG) {
18386   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18387   MVT DstVT = Op.getSimpleValueType();
18388
18389   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18390     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18391     if (DstVT != MVT::f64)
18392       // This conversion needs to be expanded.
18393       return SDValue();
18394
18395     SDValue InVec = Op->getOperand(0);
18396     SDLoc dl(Op);
18397     unsigned NumElts = SrcVT.getVectorNumElements();
18398     EVT SVT = SrcVT.getVectorElementType();
18399
18400     // Widen the vector in input in the case of MVT::v2i32.
18401     // Example: from MVT::v2i32 to MVT::v4i32.
18402     SmallVector<SDValue, 16> Elts;
18403     for (unsigned i = 0, e = NumElts; i != e; ++i)
18404       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18405                                  DAG.getIntPtrConstant(i, dl)));
18406
18407     // Explicitly mark the extra elements as Undef.
18408     Elts.append(NumElts, DAG.getUNDEF(SVT));
18409
18410     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18411     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18412     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18413     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18414                        DAG.getIntPtrConstant(0, dl));
18415   }
18416
18417   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18418          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18419   assert((DstVT == MVT::i64 ||
18420           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18421          "Unexpected custom BITCAST");
18422   // i64 <=> MMX conversions are Legal.
18423   if (SrcVT==MVT::i64 && DstVT.isVector())
18424     return Op;
18425   if (DstVT==MVT::i64 && SrcVT.isVector())
18426     return Op;
18427   // MMX <=> MMX conversions are Legal.
18428   if (SrcVT.isVector() && DstVT.isVector())
18429     return Op;
18430   // All other conversions need to be expanded.
18431   return SDValue();
18432 }
18433
18434 /// Compute the horizontal sum of bytes in V for the elements of VT.
18435 ///
18436 /// Requires V to be a byte vector and VT to be an integer vector type with
18437 /// wider elements than V's type. The width of the elements of VT determines
18438 /// how many bytes of V are summed horizontally to produce each element of the
18439 /// result.
18440 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18441                                       const X86Subtarget *Subtarget,
18442                                       SelectionDAG &DAG) {
18443   SDLoc DL(V);
18444   MVT ByteVecVT = V.getSimpleValueType();
18445   MVT EltVT = VT.getVectorElementType();
18446   int NumElts = VT.getVectorNumElements();
18447   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18448          "Expected value to have byte element type.");
18449   assert(EltVT != MVT::i8 &&
18450          "Horizontal byte sum only makes sense for wider elements!");
18451   unsigned VecSize = VT.getSizeInBits();
18452   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18453
18454   // PSADBW instruction horizontally add all bytes and leave the result in i64
18455   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18456   if (EltVT == MVT::i64) {
18457     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18458     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18459     return DAG.getBitcast(VT, V);
18460   }
18461
18462   if (EltVT == MVT::i32) {
18463     // We unpack the low half and high half into i32s interleaved with zeros so
18464     // that we can use PSADBW to horizontally sum them. The most useful part of
18465     // this is that it lines up the results of two PSADBW instructions to be
18466     // two v2i64 vectors which concatenated are the 4 population counts. We can
18467     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18468     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18469     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18470     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18471
18472     // Do the horizontal sums into two v2i64s.
18473     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18474     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18475                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18476     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18477                        DAG.getBitcast(ByteVecVT, High), Zeros);
18478
18479     // Merge them together.
18480     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18481     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18482                     DAG.getBitcast(ShortVecVT, Low),
18483                     DAG.getBitcast(ShortVecVT, High));
18484
18485     return DAG.getBitcast(VT, V);
18486   }
18487
18488   // The only element type left is i16.
18489   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18490
18491   // To obtain pop count for each i16 element starting from the pop count for
18492   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18493   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18494   // directly supported.
18495   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18496   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18497   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18498   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18499                   DAG.getBitcast(ByteVecVT, V));
18500   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18501 }
18502
18503 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18504                                         const X86Subtarget *Subtarget,
18505                                         SelectionDAG &DAG) {
18506   MVT VT = Op.getSimpleValueType();
18507   MVT EltVT = VT.getVectorElementType();
18508   unsigned VecSize = VT.getSizeInBits();
18509
18510   // Implement a lookup table in register by using an algorithm based on:
18511   // http://wm.ite.pl/articles/sse-popcount.html
18512   //
18513   // The general idea is that every lower byte nibble in the input vector is an
18514   // index into a in-register pre-computed pop count table. We then split up the
18515   // input vector in two new ones: (1) a vector with only the shifted-right
18516   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18517   // masked out higher ones) for each byte. PSHUB is used separately with both
18518   // to index the in-register table. Next, both are added and the result is a
18519   // i8 vector where each element contains the pop count for input byte.
18520   //
18521   // To obtain the pop count for elements != i8, we follow up with the same
18522   // approach and use additional tricks as described below.
18523   //
18524   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18525                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18526                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18527                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18528
18529   int NumByteElts = VecSize / 8;
18530   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18531   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18532   SmallVector<SDValue, 16> LUTVec;
18533   for (int i = 0; i < NumByteElts; ++i)
18534     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18535   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18536   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18537                                   DAG.getConstant(0x0F, DL, MVT::i8));
18538   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18539
18540   // High nibbles
18541   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18542   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18543   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18544
18545   // Low nibbles
18546   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18547
18548   // The input vector is used as the shuffle mask that index elements into the
18549   // LUT. After counting low and high nibbles, add the vector to obtain the
18550   // final pop count per i8 element.
18551   SDValue HighPopCnt =
18552       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18553   SDValue LowPopCnt =
18554       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18555   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18556
18557   if (EltVT == MVT::i8)
18558     return PopCnt;
18559
18560   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18561 }
18562
18563 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18564                                        const X86Subtarget *Subtarget,
18565                                        SelectionDAG &DAG) {
18566   MVT VT = Op.getSimpleValueType();
18567   assert(VT.is128BitVector() &&
18568          "Only 128-bit vector bitmath lowering supported.");
18569
18570   int VecSize = VT.getSizeInBits();
18571   MVT EltVT = VT.getVectorElementType();
18572   int Len = EltVT.getSizeInBits();
18573
18574   // This is the vectorized version of the "best" algorithm from
18575   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18576   // with a minor tweak to use a series of adds + shifts instead of vector
18577   // multiplications. Implemented for all integer vector types. We only use
18578   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18579   // much faster, even faster than using native popcnt instructions.
18580
18581   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18582     MVT VT = V.getSimpleValueType();
18583     SmallVector<SDValue, 32> Shifters(
18584         VT.getVectorNumElements(),
18585         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18586     return DAG.getNode(OpCode, DL, VT, V,
18587                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18588   };
18589   auto GetMask = [&](SDValue V, APInt Mask) {
18590     MVT VT = V.getSimpleValueType();
18591     SmallVector<SDValue, 32> Masks(
18592         VT.getVectorNumElements(),
18593         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18594     return DAG.getNode(ISD::AND, DL, VT, V,
18595                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18596   };
18597
18598   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18599   // x86, so set the SRL type to have elements at least i16 wide. This is
18600   // correct because all of our SRLs are followed immediately by a mask anyways
18601   // that handles any bits that sneak into the high bits of the byte elements.
18602   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18603
18604   SDValue V = Op;
18605
18606   // v = v - ((v >> 1) & 0x55555555...)
18607   SDValue Srl =
18608       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18609   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18610   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18611
18612   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18613   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18614   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18615   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18616   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18617
18618   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18619   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18620   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18621   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18622
18623   // At this point, V contains the byte-wise population count, and we are
18624   // merely doing a horizontal sum if necessary to get the wider element
18625   // counts.
18626   if (EltVT == MVT::i8)
18627     return V;
18628
18629   return LowerHorizontalByteSum(
18630       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18631       DAG);
18632 }
18633
18634 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18635                                 SelectionDAG &DAG) {
18636   MVT VT = Op.getSimpleValueType();
18637   // FIXME: Need to add AVX-512 support here!
18638   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18639          "Unknown CTPOP type to handle");
18640   SDLoc DL(Op.getNode());
18641   SDValue Op0 = Op.getOperand(0);
18642
18643   if (!Subtarget->hasSSSE3()) {
18644     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18645     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18646     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18647   }
18648
18649   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18650     unsigned NumElems = VT.getVectorNumElements();
18651
18652     // Extract each 128-bit vector, compute pop count and concat the result.
18653     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18654     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18655
18656     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18657                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18658                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18659   }
18660
18661   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18662 }
18663
18664 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18665                           SelectionDAG &DAG) {
18666   assert(Op.getValueType().isVector() &&
18667          "We only do custom lowering for vector population count.");
18668   return LowerVectorCTPOP(Op, Subtarget, DAG);
18669 }
18670
18671 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18672   SDNode *Node = Op.getNode();
18673   SDLoc dl(Node);
18674   EVT T = Node->getValueType(0);
18675   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18676                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18677   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18678                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18679                        Node->getOperand(0),
18680                        Node->getOperand(1), negOp,
18681                        cast<AtomicSDNode>(Node)->getMemOperand(),
18682                        cast<AtomicSDNode>(Node)->getOrdering(),
18683                        cast<AtomicSDNode>(Node)->getSynchScope());
18684 }
18685
18686 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18687   SDNode *Node = Op.getNode();
18688   SDLoc dl(Node);
18689   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18690
18691   // Convert seq_cst store -> xchg
18692   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18693   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18694   //        (The only way to get a 16-byte store is cmpxchg16b)
18695   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18696   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18697       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18698     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18699                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18700                                  Node->getOperand(0),
18701                                  Node->getOperand(1), Node->getOperand(2),
18702                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18703                                  cast<AtomicSDNode>(Node)->getOrdering(),
18704                                  cast<AtomicSDNode>(Node)->getSynchScope());
18705     return Swap.getValue(1);
18706   }
18707   // Other atomic stores have a simple pattern.
18708   return Op;
18709 }
18710
18711 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18712   EVT VT = Op.getNode()->getSimpleValueType(0);
18713
18714   // Let legalize expand this if it isn't a legal type yet.
18715   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18716     return SDValue();
18717
18718   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18719
18720   unsigned Opc;
18721   bool ExtraOp = false;
18722   switch (Op.getOpcode()) {
18723   default: llvm_unreachable("Invalid code");
18724   case ISD::ADDC: Opc = X86ISD::ADD; break;
18725   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18726   case ISD::SUBC: Opc = X86ISD::SUB; break;
18727   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18728   }
18729
18730   if (!ExtraOp)
18731     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18732                        Op.getOperand(1));
18733   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18734                      Op.getOperand(1), Op.getOperand(2));
18735 }
18736
18737 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18738                             SelectionDAG &DAG) {
18739   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18740
18741   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18742   // which returns the values as { float, float } (in XMM0) or
18743   // { double, double } (which is returned in XMM0, XMM1).
18744   SDLoc dl(Op);
18745   SDValue Arg = Op.getOperand(0);
18746   EVT ArgVT = Arg.getValueType();
18747   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18748
18749   TargetLowering::ArgListTy Args;
18750   TargetLowering::ArgListEntry Entry;
18751
18752   Entry.Node = Arg;
18753   Entry.Ty = ArgTy;
18754   Entry.isSExt = false;
18755   Entry.isZExt = false;
18756   Args.push_back(Entry);
18757
18758   bool isF64 = ArgVT == MVT::f64;
18759   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18760   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18761   // the results are returned via SRet in memory.
18762   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18763   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18764   SDValue Callee =
18765       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18766
18767   Type *RetTy = isF64
18768     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18769     : (Type*)VectorType::get(ArgTy, 4);
18770
18771   TargetLowering::CallLoweringInfo CLI(DAG);
18772   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18773     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18774
18775   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18776
18777   if (isF64)
18778     // Returned in xmm0 and xmm1.
18779     return CallResult.first;
18780
18781   // Returned in bits 0:31 and 32:64 xmm0.
18782   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18783                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18784   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18785                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18786   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18787   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18788 }
18789
18790 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18791                              SelectionDAG &DAG) {
18792   assert(Subtarget->hasAVX512() &&
18793          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18794
18795   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18796   EVT VT = N->getValue().getValueType();
18797   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18798   SDLoc dl(Op);
18799
18800   // X86 scatter kills mask register, so its type should be added to
18801   // the list of return values
18802   if (N->getNumValues() == 1) {
18803     SDValue Index = N->getIndex();
18804     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18805         !Index.getValueType().is512BitVector())
18806       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18807
18808     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18809     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18810                       N->getOperand(3), Index };
18811
18812     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18813     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18814     return SDValue(NewScatter.getNode(), 0);
18815   }
18816   return Op;
18817 }
18818
18819 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18820                             SelectionDAG &DAG) {
18821   assert(Subtarget->hasAVX512() &&
18822          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18823
18824   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18825   EVT VT = Op.getValueType();
18826   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18827   SDLoc dl(Op);
18828
18829   SDValue Index = N->getIndex();
18830   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18831       !Index.getValueType().is512BitVector()) {
18832     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18833     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18834                       N->getOperand(3), Index };
18835     DAG.UpdateNodeOperands(N, Ops);
18836   }
18837   return Op;
18838 }
18839
18840 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18841                                                     SelectionDAG &DAG) const {
18842   // TODO: Eventually, the lowering of these nodes should be informed by or
18843   // deferred to the GC strategy for the function in which they appear. For
18844   // now, however, they must be lowered to something. Since they are logically
18845   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18846   // require special handling for these nodes), lower them as literal NOOPs for
18847   // the time being.
18848   SmallVector<SDValue, 2> Ops;
18849
18850   Ops.push_back(Op.getOperand(0));
18851   if (Op->getGluedNode())
18852     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18853
18854   SDLoc OpDL(Op);
18855   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18856   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18857
18858   return NOOP;
18859 }
18860
18861 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18862                                                   SelectionDAG &DAG) const {
18863   // TODO: Eventually, the lowering of these nodes should be informed by or
18864   // deferred to the GC strategy for the function in which they appear. For
18865   // now, however, they must be lowered to something. Since they are logically
18866   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18867   // require special handling for these nodes), lower them as literal NOOPs for
18868   // the time being.
18869   SmallVector<SDValue, 2> Ops;
18870
18871   Ops.push_back(Op.getOperand(0));
18872   if (Op->getGluedNode())
18873     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18874
18875   SDLoc OpDL(Op);
18876   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18877   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18878
18879   return NOOP;
18880 }
18881
18882 /// LowerOperation - Provide custom lowering hooks for some operations.
18883 ///
18884 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18885   switch (Op.getOpcode()) {
18886   default: llvm_unreachable("Should not custom lower this!");
18887   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18888   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18889     return LowerCMP_SWAP(Op, Subtarget, DAG);
18890   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18891   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18892   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18893   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18894   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18895   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18896   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18897   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18898   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18899   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18900   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18901   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18902   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18903   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18904   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18905   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18906   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18907   case ISD::SHL_PARTS:
18908   case ISD::SRA_PARTS:
18909   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18910   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18911   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18912   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18913   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18914   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18915   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18916   case ISD::SIGN_EXTEND_VECTOR_INREG:
18917     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18918   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18919   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18920   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18921   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18922   case ISD::FABS:
18923   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18924   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18925   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18926   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18927   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18928   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18929   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18930   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18931   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18932   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18933   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18934   case ISD::INTRINSIC_VOID:
18935   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18936   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18937   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18938   case ISD::FRAME_TO_ARGS_OFFSET:
18939                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18940   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18941   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18942   case ISD::CATCHRET:           return LowerCATCHRET(Op, DAG);
18943   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18944   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18945   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18946   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18947   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18948   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18949   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18950   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18951   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18952   case ISD::UMUL_LOHI:
18953   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18954   case ISD::SRA:
18955   case ISD::SRL:
18956   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18957   case ISD::SADDO:
18958   case ISD::UADDO:
18959   case ISD::SSUBO:
18960   case ISD::USUBO:
18961   case ISD::SMULO:
18962   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18963   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18964   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18965   case ISD::ADDC:
18966   case ISD::ADDE:
18967   case ISD::SUBC:
18968   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18969   case ISD::ADD:                return LowerADD(Op, DAG);
18970   case ISD::SUB:                return LowerSUB(Op, DAG);
18971   case ISD::SMAX:
18972   case ISD::SMIN:
18973   case ISD::UMAX:
18974   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
18975   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18976   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18977   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18978   case ISD::GC_TRANSITION_START:
18979                                 return LowerGC_TRANSITION_START(Op, DAG);
18980   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18981   }
18982 }
18983
18984 /// ReplaceNodeResults - Replace a node with an illegal result type
18985 /// with a new node built out of custom code.
18986 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18987                                            SmallVectorImpl<SDValue>&Results,
18988                                            SelectionDAG &DAG) const {
18989   SDLoc dl(N);
18990   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18991   switch (N->getOpcode()) {
18992   default:
18993     llvm_unreachable("Do not know how to custom type legalize this operation!");
18994   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18995   case X86ISD::FMINC:
18996   case X86ISD::FMIN:
18997   case X86ISD::FMAXC:
18998   case X86ISD::FMAX: {
18999     EVT VT = N->getValueType(0);
19000     if (VT != MVT::v2f32)
19001       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19002     SDValue UNDEF = DAG.getUNDEF(VT);
19003     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19004                               N->getOperand(0), UNDEF);
19005     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19006                               N->getOperand(1), UNDEF);
19007     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19008     return;
19009   }
19010   case ISD::SIGN_EXTEND_INREG:
19011   case ISD::ADDC:
19012   case ISD::ADDE:
19013   case ISD::SUBC:
19014   case ISD::SUBE:
19015     // We don't want to expand or promote these.
19016     return;
19017   case ISD::SDIV:
19018   case ISD::UDIV:
19019   case ISD::SREM:
19020   case ISD::UREM:
19021   case ISD::SDIVREM:
19022   case ISD::UDIVREM: {
19023     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19024     Results.push_back(V);
19025     return;
19026   }
19027   case ISD::FP_TO_SINT:
19028   case ISD::FP_TO_UINT: {
19029     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19030
19031     std::pair<SDValue,SDValue> Vals =
19032         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19033     SDValue FIST = Vals.first, StackSlot = Vals.second;
19034     if (FIST.getNode()) {
19035       EVT VT = N->getValueType(0);
19036       // Return a load from the stack slot.
19037       if (StackSlot.getNode())
19038         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19039                                       MachinePointerInfo(),
19040                                       false, false, false, 0));
19041       else
19042         Results.push_back(FIST);
19043     }
19044     return;
19045   }
19046   case ISD::UINT_TO_FP: {
19047     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19048     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19049         N->getValueType(0) != MVT::v2f32)
19050       return;
19051     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19052                                  N->getOperand(0));
19053     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19054                                      MVT::f64);
19055     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19056     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19057                              DAG.getBitcast(MVT::v2i64, VBias));
19058     Or = DAG.getBitcast(MVT::v2f64, Or);
19059     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19060     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19061     return;
19062   }
19063   case ISD::FP_ROUND: {
19064     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19065         return;
19066     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19067     Results.push_back(V);
19068     return;
19069   }
19070   case ISD::FP_EXTEND: {
19071     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19072     // No other ValueType for FP_EXTEND should reach this point.
19073     assert(N->getValueType(0) == MVT::v2f32 &&
19074            "Do not know how to legalize this Node");
19075     return;
19076   }
19077   case ISD::INTRINSIC_W_CHAIN: {
19078     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19079     switch (IntNo) {
19080     default : llvm_unreachable("Do not know how to custom type "
19081                                "legalize this intrinsic operation!");
19082     case Intrinsic::x86_rdtsc:
19083       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19084                                      Results);
19085     case Intrinsic::x86_rdtscp:
19086       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19087                                      Results);
19088     case Intrinsic::x86_rdpmc:
19089       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19090     }
19091   }
19092   case ISD::READCYCLECOUNTER: {
19093     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19094                                    Results);
19095   }
19096   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19097     EVT T = N->getValueType(0);
19098     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19099     bool Regs64bit = T == MVT::i128;
19100     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19101     SDValue cpInL, cpInH;
19102     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19103                         DAG.getConstant(0, dl, HalfT));
19104     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19105                         DAG.getConstant(1, dl, HalfT));
19106     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19107                              Regs64bit ? X86::RAX : X86::EAX,
19108                              cpInL, SDValue());
19109     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19110                              Regs64bit ? X86::RDX : X86::EDX,
19111                              cpInH, cpInL.getValue(1));
19112     SDValue swapInL, swapInH;
19113     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19114                           DAG.getConstant(0, dl, HalfT));
19115     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19116                           DAG.getConstant(1, dl, HalfT));
19117     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19118                                Regs64bit ? X86::RBX : X86::EBX,
19119                                swapInL, cpInH.getValue(1));
19120     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19121                                Regs64bit ? X86::RCX : X86::ECX,
19122                                swapInH, swapInL.getValue(1));
19123     SDValue Ops[] = { swapInH.getValue(0),
19124                       N->getOperand(1),
19125                       swapInH.getValue(1) };
19126     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19127     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19128     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19129                                   X86ISD::LCMPXCHG8_DAG;
19130     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19131     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19132                                         Regs64bit ? X86::RAX : X86::EAX,
19133                                         HalfT, Result.getValue(1));
19134     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19135                                         Regs64bit ? X86::RDX : X86::EDX,
19136                                         HalfT, cpOutL.getValue(2));
19137     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19138
19139     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19140                                         MVT::i32, cpOutH.getValue(2));
19141     SDValue Success =
19142         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19143                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19144     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19145
19146     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19147     Results.push_back(Success);
19148     Results.push_back(EFLAGS.getValue(1));
19149     return;
19150   }
19151   case ISD::ATOMIC_SWAP:
19152   case ISD::ATOMIC_LOAD_ADD:
19153   case ISD::ATOMIC_LOAD_SUB:
19154   case ISD::ATOMIC_LOAD_AND:
19155   case ISD::ATOMIC_LOAD_OR:
19156   case ISD::ATOMIC_LOAD_XOR:
19157   case ISD::ATOMIC_LOAD_NAND:
19158   case ISD::ATOMIC_LOAD_MIN:
19159   case ISD::ATOMIC_LOAD_MAX:
19160   case ISD::ATOMIC_LOAD_UMIN:
19161   case ISD::ATOMIC_LOAD_UMAX:
19162   case ISD::ATOMIC_LOAD: {
19163     // Delegate to generic TypeLegalization. Situations we can really handle
19164     // should have already been dealt with by AtomicExpandPass.cpp.
19165     break;
19166   }
19167   case ISD::BITCAST: {
19168     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19169     EVT DstVT = N->getValueType(0);
19170     EVT SrcVT = N->getOperand(0)->getValueType(0);
19171
19172     if (SrcVT != MVT::f64 ||
19173         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19174       return;
19175
19176     unsigned NumElts = DstVT.getVectorNumElements();
19177     EVT SVT = DstVT.getVectorElementType();
19178     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19179     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19180                                    MVT::v2f64, N->getOperand(0));
19181     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19182
19183     if (ExperimentalVectorWideningLegalization) {
19184       // If we are legalizing vectors by widening, we already have the desired
19185       // legal vector type, just return it.
19186       Results.push_back(ToVecInt);
19187       return;
19188     }
19189
19190     SmallVector<SDValue, 8> Elts;
19191     for (unsigned i = 0, e = NumElts; i != e; ++i)
19192       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19193                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19194
19195     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19196   }
19197   }
19198 }
19199
19200 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19201   switch ((X86ISD::NodeType)Opcode) {
19202   case X86ISD::FIRST_NUMBER:       break;
19203   case X86ISD::BSF:                return "X86ISD::BSF";
19204   case X86ISD::BSR:                return "X86ISD::BSR";
19205   case X86ISD::SHLD:               return "X86ISD::SHLD";
19206   case X86ISD::SHRD:               return "X86ISD::SHRD";
19207   case X86ISD::FAND:               return "X86ISD::FAND";
19208   case X86ISD::FANDN:              return "X86ISD::FANDN";
19209   case X86ISD::FOR:                return "X86ISD::FOR";
19210   case X86ISD::FXOR:               return "X86ISD::FXOR";
19211   case X86ISD::FILD:               return "X86ISD::FILD";
19212   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19213   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19214   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19215   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19216   case X86ISD::FLD:                return "X86ISD::FLD";
19217   case X86ISD::FST:                return "X86ISD::FST";
19218   case X86ISD::CALL:               return "X86ISD::CALL";
19219   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19220   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19221   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19222   case X86ISD::BT:                 return "X86ISD::BT";
19223   case X86ISD::CMP:                return "X86ISD::CMP";
19224   case X86ISD::COMI:               return "X86ISD::COMI";
19225   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19226   case X86ISD::CMPM:               return "X86ISD::CMPM";
19227   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19228   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19229   case X86ISD::SETCC:              return "X86ISD::SETCC";
19230   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19231   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19232   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19233   case X86ISD::CMOV:               return "X86ISD::CMOV";
19234   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19235   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19236   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19237   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19238   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19239   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19240   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19241   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19242   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19243   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19244   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19245   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19246   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19247   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19248   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19249   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19250   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19251   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19252   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19253   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19254   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19255   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19256   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19257   case X86ISD::HADD:               return "X86ISD::HADD";
19258   case X86ISD::HSUB:               return "X86ISD::HSUB";
19259   case X86ISD::FHADD:              return "X86ISD::FHADD";
19260   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19261   case X86ISD::ABS:                return "X86ISD::ABS";
19262   case X86ISD::FMAX:               return "X86ISD::FMAX";
19263   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19264   case X86ISD::FMIN:               return "X86ISD::FMIN";
19265   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19266   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19267   case X86ISD::FMINC:              return "X86ISD::FMINC";
19268   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19269   case X86ISD::FRCP:               return "X86ISD::FRCP";
19270   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19271   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19272   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19273   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19274   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19275   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19276   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19277   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19278   case X86ISD::CATCHRET:           return "X86ISD::CATCHRET";
19279   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19280   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19281   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19282   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19283   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19284   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19285   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19286   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19287   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19288   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19289   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19290   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19291   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19292   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19293   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19294   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19295   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19296   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19297   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19298   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19299   case X86ISD::VSHL:               return "X86ISD::VSHL";
19300   case X86ISD::VSRL:               return "X86ISD::VSRL";
19301   case X86ISD::VSRA:               return "X86ISD::VSRA";
19302   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19303   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19304   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19305   case X86ISD::CMPP:               return "X86ISD::CMPP";
19306   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19307   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19308   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19309   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19310   case X86ISD::ADD:                return "X86ISD::ADD";
19311   case X86ISD::SUB:                return "X86ISD::SUB";
19312   case X86ISD::ADC:                return "X86ISD::ADC";
19313   case X86ISD::SBB:                return "X86ISD::SBB";
19314   case X86ISD::SMUL:               return "X86ISD::SMUL";
19315   case X86ISD::UMUL:               return "X86ISD::UMUL";
19316   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19317   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19318   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19319   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19320   case X86ISD::INC:                return "X86ISD::INC";
19321   case X86ISD::DEC:                return "X86ISD::DEC";
19322   case X86ISD::OR:                 return "X86ISD::OR";
19323   case X86ISD::XOR:                return "X86ISD::XOR";
19324   case X86ISD::AND:                return "X86ISD::AND";
19325   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19326   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19327   case X86ISD::PTEST:              return "X86ISD::PTEST";
19328   case X86ISD::TESTP:              return "X86ISD::TESTP";
19329   case X86ISD::TESTM:              return "X86ISD::TESTM";
19330   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19331   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19332   case X86ISD::KTEST:              return "X86ISD::KTEST";
19333   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19334   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19335   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19336   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19337   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19338   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19339   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19340   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19341   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19342   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19343   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19344   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19345   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19346   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19347   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19348   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19349   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19350   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19351   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19352   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19353   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19354   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19355   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19356   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19357   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19358   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19359   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19360   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19361   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19362   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19363   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19364   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19365   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19366   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19367   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19368   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19369   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
19370   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19371   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19372   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19373   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19374   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19375   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19376   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19377   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19378   case X86ISD::SAHF:               return "X86ISD::SAHF";
19379   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19380   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19381   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19382   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19383   case X86ISD::FMADD:              return "X86ISD::FMADD";
19384   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19385   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19386   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19387   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19388   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19389   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19390   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19391   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19392   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19393   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19394   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19395   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19396   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19397   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19398   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19399   case X86ISD::XTEST:              return "X86ISD::XTEST";
19400   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19401   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19402   case X86ISD::SELECT:             return "X86ISD::SELECT";
19403   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19404   case X86ISD::RCP28:              return "X86ISD::RCP28";
19405   case X86ISD::EXP2:               return "X86ISD::EXP2";
19406   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19407   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19408   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19409   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19410   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19411   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19412   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19413   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19414   case X86ISD::ADDS:               return "X86ISD::ADDS";
19415   case X86ISD::SUBS:               return "X86ISD::SUBS";
19416   case X86ISD::AVG:                return "X86ISD::AVG";
19417   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19418   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19419   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19420   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19421   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19422   }
19423   return nullptr;
19424 }
19425
19426 // isLegalAddressingMode - Return true if the addressing mode represented
19427 // by AM is legal for this target, for a load/store of the specified type.
19428 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19429                                               const AddrMode &AM, Type *Ty,
19430                                               unsigned AS) const {
19431   // X86 supports extremely general addressing modes.
19432   CodeModel::Model M = getTargetMachine().getCodeModel();
19433   Reloc::Model R = getTargetMachine().getRelocationModel();
19434
19435   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19436   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19437     return false;
19438
19439   if (AM.BaseGV) {
19440     unsigned GVFlags =
19441       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19442
19443     // If a reference to this global requires an extra load, we can't fold it.
19444     if (isGlobalStubReference(GVFlags))
19445       return false;
19446
19447     // If BaseGV requires a register for the PIC base, we cannot also have a
19448     // BaseReg specified.
19449     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19450       return false;
19451
19452     // If lower 4G is not available, then we must use rip-relative addressing.
19453     if ((M != CodeModel::Small || R != Reloc::Static) &&
19454         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19455       return false;
19456   }
19457
19458   switch (AM.Scale) {
19459   case 0:
19460   case 1:
19461   case 2:
19462   case 4:
19463   case 8:
19464     // These scales always work.
19465     break;
19466   case 3:
19467   case 5:
19468   case 9:
19469     // These scales are formed with basereg+scalereg.  Only accept if there is
19470     // no basereg yet.
19471     if (AM.HasBaseReg)
19472       return false;
19473     break;
19474   default:  // Other stuff never works.
19475     return false;
19476   }
19477
19478   return true;
19479 }
19480
19481 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19482   unsigned Bits = Ty->getScalarSizeInBits();
19483
19484   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19485   // particularly cheaper than those without.
19486   if (Bits == 8)
19487     return false;
19488
19489   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19490   // variable shifts just as cheap as scalar ones.
19491   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19492     return false;
19493
19494   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19495   // fully general vector.
19496   return true;
19497 }
19498
19499 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19500   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19501     return false;
19502   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19503   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19504   return NumBits1 > NumBits2;
19505 }
19506
19507 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19508   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19509     return false;
19510
19511   if (!isTypeLegal(EVT::getEVT(Ty1)))
19512     return false;
19513
19514   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19515
19516   // Assuming the caller doesn't have a zeroext or signext return parameter,
19517   // truncation all the way down to i1 is valid.
19518   return true;
19519 }
19520
19521 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19522   return isInt<32>(Imm);
19523 }
19524
19525 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19526   // Can also use sub to handle negated immediates.
19527   return isInt<32>(Imm);
19528 }
19529
19530 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19531   if (!VT1.isInteger() || !VT2.isInteger())
19532     return false;
19533   unsigned NumBits1 = VT1.getSizeInBits();
19534   unsigned NumBits2 = VT2.getSizeInBits();
19535   return NumBits1 > NumBits2;
19536 }
19537
19538 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19539   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19540   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19541 }
19542
19543 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19544   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19545   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19546 }
19547
19548 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19549   EVT VT1 = Val.getValueType();
19550   if (isZExtFree(VT1, VT2))
19551     return true;
19552
19553   if (Val.getOpcode() != ISD::LOAD)
19554     return false;
19555
19556   if (!VT1.isSimple() || !VT1.isInteger() ||
19557       !VT2.isSimple() || !VT2.isInteger())
19558     return false;
19559
19560   switch (VT1.getSimpleVT().SimpleTy) {
19561   default: break;
19562   case MVT::i8:
19563   case MVT::i16:
19564   case MVT::i32:
19565     // X86 has 8, 16, and 32-bit zero-extending loads.
19566     return true;
19567   }
19568
19569   return false;
19570 }
19571
19572 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19573
19574 bool
19575 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19576   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19577     return false;
19578
19579   VT = VT.getScalarType();
19580
19581   if (!VT.isSimple())
19582     return false;
19583
19584   switch (VT.getSimpleVT().SimpleTy) {
19585   case MVT::f32:
19586   case MVT::f64:
19587     return true;
19588   default:
19589     break;
19590   }
19591
19592   return false;
19593 }
19594
19595 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19596   // i16 instructions are longer (0x66 prefix) and potentially slower.
19597   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19598 }
19599
19600 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19601 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19602 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19603 /// are assumed to be legal.
19604 bool
19605 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19606                                       EVT VT) const {
19607   if (!VT.isSimple())
19608     return false;
19609
19610   // Not for i1 vectors
19611   if (VT.getScalarType() == MVT::i1)
19612     return false;
19613
19614   // Very little shuffling can be done for 64-bit vectors right now.
19615   if (VT.getSizeInBits() == 64)
19616     return false;
19617
19618   // We only care that the types being shuffled are legal. The lowering can
19619   // handle any possible shuffle mask that results.
19620   return isTypeLegal(VT.getSimpleVT());
19621 }
19622
19623 bool
19624 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19625                                           EVT VT) const {
19626   // Just delegate to the generic legality, clear masks aren't special.
19627   return isShuffleMaskLegal(Mask, VT);
19628 }
19629
19630 //===----------------------------------------------------------------------===//
19631 //                           X86 Scheduler Hooks
19632 //===----------------------------------------------------------------------===//
19633
19634 /// Utility function to emit xbegin specifying the start of an RTM region.
19635 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19636                                      const TargetInstrInfo *TII) {
19637   DebugLoc DL = MI->getDebugLoc();
19638
19639   const BasicBlock *BB = MBB->getBasicBlock();
19640   MachineFunction::iterator I = MBB;
19641   ++I;
19642
19643   // For the v = xbegin(), we generate
19644   //
19645   // thisMBB:
19646   //  xbegin sinkMBB
19647   //
19648   // mainMBB:
19649   //  eax = -1
19650   //
19651   // sinkMBB:
19652   //  v = eax
19653
19654   MachineBasicBlock *thisMBB = MBB;
19655   MachineFunction *MF = MBB->getParent();
19656   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19657   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19658   MF->insert(I, mainMBB);
19659   MF->insert(I, sinkMBB);
19660
19661   // Transfer the remainder of BB and its successor edges to sinkMBB.
19662   sinkMBB->splice(sinkMBB->begin(), MBB,
19663                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19664   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19665
19666   // thisMBB:
19667   //  xbegin sinkMBB
19668   //  # fallthrough to mainMBB
19669   //  # abortion to sinkMBB
19670   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19671   thisMBB->addSuccessor(mainMBB);
19672   thisMBB->addSuccessor(sinkMBB);
19673
19674   // mainMBB:
19675   //  EAX = -1
19676   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19677   mainMBB->addSuccessor(sinkMBB);
19678
19679   // sinkMBB:
19680   // EAX is live into the sinkMBB
19681   sinkMBB->addLiveIn(X86::EAX);
19682   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19683           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19684     .addReg(X86::EAX);
19685
19686   MI->eraseFromParent();
19687   return sinkMBB;
19688 }
19689
19690 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19691 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19692 // in the .td file.
19693 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19694                                        const TargetInstrInfo *TII) {
19695   unsigned Opc;
19696   switch (MI->getOpcode()) {
19697   default: llvm_unreachable("illegal opcode!");
19698   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19699   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19700   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19701   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19702   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19703   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19704   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19705   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19706   }
19707
19708   DebugLoc dl = MI->getDebugLoc();
19709   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19710
19711   unsigned NumArgs = MI->getNumOperands();
19712   for (unsigned i = 1; i < NumArgs; ++i) {
19713     MachineOperand &Op = MI->getOperand(i);
19714     if (!(Op.isReg() && Op.isImplicit()))
19715       MIB.addOperand(Op);
19716   }
19717   if (MI->hasOneMemOperand())
19718     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19719
19720   BuildMI(*BB, MI, dl,
19721     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19722     .addReg(X86::XMM0);
19723
19724   MI->eraseFromParent();
19725   return BB;
19726 }
19727
19728 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19729 // defs in an instruction pattern
19730 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19731                                        const TargetInstrInfo *TII) {
19732   unsigned Opc;
19733   switch (MI->getOpcode()) {
19734   default: llvm_unreachable("illegal opcode!");
19735   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19736   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19737   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19738   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19739   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19740   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19741   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19742   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19743   }
19744
19745   DebugLoc dl = MI->getDebugLoc();
19746   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19747
19748   unsigned NumArgs = MI->getNumOperands(); // remove the results
19749   for (unsigned i = 1; i < NumArgs; ++i) {
19750     MachineOperand &Op = MI->getOperand(i);
19751     if (!(Op.isReg() && Op.isImplicit()))
19752       MIB.addOperand(Op);
19753   }
19754   if (MI->hasOneMemOperand())
19755     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19756
19757   BuildMI(*BB, MI, dl,
19758     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19759     .addReg(X86::ECX);
19760
19761   MI->eraseFromParent();
19762   return BB;
19763 }
19764
19765 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19766                                       const X86Subtarget *Subtarget) {
19767   DebugLoc dl = MI->getDebugLoc();
19768   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19769   // Address into RAX/EAX, other two args into ECX, EDX.
19770   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19771   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19772   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19773   for (int i = 0; i < X86::AddrNumOperands; ++i)
19774     MIB.addOperand(MI->getOperand(i));
19775
19776   unsigned ValOps = X86::AddrNumOperands;
19777   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19778     .addReg(MI->getOperand(ValOps).getReg());
19779   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19780     .addReg(MI->getOperand(ValOps+1).getReg());
19781
19782   // The instruction doesn't actually take any operands though.
19783   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19784
19785   MI->eraseFromParent(); // The pseudo is gone now.
19786   return BB;
19787 }
19788
19789 MachineBasicBlock *
19790 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19791                                                  MachineBasicBlock *MBB) const {
19792   // Emit va_arg instruction on X86-64.
19793
19794   // Operands to this pseudo-instruction:
19795   // 0  ) Output        : destination address (reg)
19796   // 1-5) Input         : va_list address (addr, i64mem)
19797   // 6  ) ArgSize       : Size (in bytes) of vararg type
19798   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19799   // 8  ) Align         : Alignment of type
19800   // 9  ) EFLAGS (implicit-def)
19801
19802   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19803   static_assert(X86::AddrNumOperands == 5,
19804                 "VAARG_64 assumes 5 address operands");
19805
19806   unsigned DestReg = MI->getOperand(0).getReg();
19807   MachineOperand &Base = MI->getOperand(1);
19808   MachineOperand &Scale = MI->getOperand(2);
19809   MachineOperand &Index = MI->getOperand(3);
19810   MachineOperand &Disp = MI->getOperand(4);
19811   MachineOperand &Segment = MI->getOperand(5);
19812   unsigned ArgSize = MI->getOperand(6).getImm();
19813   unsigned ArgMode = MI->getOperand(7).getImm();
19814   unsigned Align = MI->getOperand(8).getImm();
19815
19816   // Memory Reference
19817   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19818   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19819   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19820
19821   // Machine Information
19822   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19823   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19824   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19825   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19826   DebugLoc DL = MI->getDebugLoc();
19827
19828   // struct va_list {
19829   //   i32   gp_offset
19830   //   i32   fp_offset
19831   //   i64   overflow_area (address)
19832   //   i64   reg_save_area (address)
19833   // }
19834   // sizeof(va_list) = 24
19835   // alignment(va_list) = 8
19836
19837   unsigned TotalNumIntRegs = 6;
19838   unsigned TotalNumXMMRegs = 8;
19839   bool UseGPOffset = (ArgMode == 1);
19840   bool UseFPOffset = (ArgMode == 2);
19841   unsigned MaxOffset = TotalNumIntRegs * 8 +
19842                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19843
19844   /* Align ArgSize to a multiple of 8 */
19845   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19846   bool NeedsAlign = (Align > 8);
19847
19848   MachineBasicBlock *thisMBB = MBB;
19849   MachineBasicBlock *overflowMBB;
19850   MachineBasicBlock *offsetMBB;
19851   MachineBasicBlock *endMBB;
19852
19853   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19854   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19855   unsigned OffsetReg = 0;
19856
19857   if (!UseGPOffset && !UseFPOffset) {
19858     // If we only pull from the overflow region, we don't create a branch.
19859     // We don't need to alter control flow.
19860     OffsetDestReg = 0; // unused
19861     OverflowDestReg = DestReg;
19862
19863     offsetMBB = nullptr;
19864     overflowMBB = thisMBB;
19865     endMBB = thisMBB;
19866   } else {
19867     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19868     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19869     // If not, pull from overflow_area. (branch to overflowMBB)
19870     //
19871     //       thisMBB
19872     //         |     .
19873     //         |        .
19874     //     offsetMBB   overflowMBB
19875     //         |        .
19876     //         |     .
19877     //        endMBB
19878
19879     // Registers for the PHI in endMBB
19880     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19881     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19882
19883     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19884     MachineFunction *MF = MBB->getParent();
19885     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19886     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19887     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19888
19889     MachineFunction::iterator MBBIter = MBB;
19890     ++MBBIter;
19891
19892     // Insert the new basic blocks
19893     MF->insert(MBBIter, offsetMBB);
19894     MF->insert(MBBIter, overflowMBB);
19895     MF->insert(MBBIter, endMBB);
19896
19897     // Transfer the remainder of MBB and its successor edges to endMBB.
19898     endMBB->splice(endMBB->begin(), thisMBB,
19899                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19900     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19901
19902     // Make offsetMBB and overflowMBB successors of thisMBB
19903     thisMBB->addSuccessor(offsetMBB);
19904     thisMBB->addSuccessor(overflowMBB);
19905
19906     // endMBB is a successor of both offsetMBB and overflowMBB
19907     offsetMBB->addSuccessor(endMBB);
19908     overflowMBB->addSuccessor(endMBB);
19909
19910     // Load the offset value into a register
19911     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19912     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19913       .addOperand(Base)
19914       .addOperand(Scale)
19915       .addOperand(Index)
19916       .addDisp(Disp, UseFPOffset ? 4 : 0)
19917       .addOperand(Segment)
19918       .setMemRefs(MMOBegin, MMOEnd);
19919
19920     // Check if there is enough room left to pull this argument.
19921     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19922       .addReg(OffsetReg)
19923       .addImm(MaxOffset + 8 - ArgSizeA8);
19924
19925     // Branch to "overflowMBB" if offset >= max
19926     // Fall through to "offsetMBB" otherwise
19927     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19928       .addMBB(overflowMBB);
19929   }
19930
19931   // In offsetMBB, emit code to use the reg_save_area.
19932   if (offsetMBB) {
19933     assert(OffsetReg != 0);
19934
19935     // Read the reg_save_area address.
19936     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19937     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19938       .addOperand(Base)
19939       .addOperand(Scale)
19940       .addOperand(Index)
19941       .addDisp(Disp, 16)
19942       .addOperand(Segment)
19943       .setMemRefs(MMOBegin, MMOEnd);
19944
19945     // Zero-extend the offset
19946     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19947       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19948         .addImm(0)
19949         .addReg(OffsetReg)
19950         .addImm(X86::sub_32bit);
19951
19952     // Add the offset to the reg_save_area to get the final address.
19953     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19954       .addReg(OffsetReg64)
19955       .addReg(RegSaveReg);
19956
19957     // Compute the offset for the next argument
19958     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19959     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19960       .addReg(OffsetReg)
19961       .addImm(UseFPOffset ? 16 : 8);
19962
19963     // Store it back into the va_list.
19964     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19965       .addOperand(Base)
19966       .addOperand(Scale)
19967       .addOperand(Index)
19968       .addDisp(Disp, UseFPOffset ? 4 : 0)
19969       .addOperand(Segment)
19970       .addReg(NextOffsetReg)
19971       .setMemRefs(MMOBegin, MMOEnd);
19972
19973     // Jump to endMBB
19974     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19975       .addMBB(endMBB);
19976   }
19977
19978   //
19979   // Emit code to use overflow area
19980   //
19981
19982   // Load the overflow_area address into a register.
19983   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19984   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19985     .addOperand(Base)
19986     .addOperand(Scale)
19987     .addOperand(Index)
19988     .addDisp(Disp, 8)
19989     .addOperand(Segment)
19990     .setMemRefs(MMOBegin, MMOEnd);
19991
19992   // If we need to align it, do so. Otherwise, just copy the address
19993   // to OverflowDestReg.
19994   if (NeedsAlign) {
19995     // Align the overflow address
19996     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19997     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19998
19999     // aligned_addr = (addr + (align-1)) & ~(align-1)
20000     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20001       .addReg(OverflowAddrReg)
20002       .addImm(Align-1);
20003
20004     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20005       .addReg(TmpReg)
20006       .addImm(~(uint64_t)(Align-1));
20007   } else {
20008     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20009       .addReg(OverflowAddrReg);
20010   }
20011
20012   // Compute the next overflow address after this argument.
20013   // (the overflow address should be kept 8-byte aligned)
20014   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20015   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20016     .addReg(OverflowDestReg)
20017     .addImm(ArgSizeA8);
20018
20019   // Store the new overflow address.
20020   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20021     .addOperand(Base)
20022     .addOperand(Scale)
20023     .addOperand(Index)
20024     .addDisp(Disp, 8)
20025     .addOperand(Segment)
20026     .addReg(NextAddrReg)
20027     .setMemRefs(MMOBegin, MMOEnd);
20028
20029   // If we branched, emit the PHI to the front of endMBB.
20030   if (offsetMBB) {
20031     BuildMI(*endMBB, endMBB->begin(), DL,
20032             TII->get(X86::PHI), DestReg)
20033       .addReg(OffsetDestReg).addMBB(offsetMBB)
20034       .addReg(OverflowDestReg).addMBB(overflowMBB);
20035   }
20036
20037   // Erase the pseudo instruction
20038   MI->eraseFromParent();
20039
20040   return endMBB;
20041 }
20042
20043 MachineBasicBlock *
20044 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20045                                                  MachineInstr *MI,
20046                                                  MachineBasicBlock *MBB) const {
20047   // Emit code to save XMM registers to the stack. The ABI says that the
20048   // number of registers to save is given in %al, so it's theoretically
20049   // possible to do an indirect jump trick to avoid saving all of them,
20050   // however this code takes a simpler approach and just executes all
20051   // of the stores if %al is non-zero. It's less code, and it's probably
20052   // easier on the hardware branch predictor, and stores aren't all that
20053   // expensive anyway.
20054
20055   // Create the new basic blocks. One block contains all the XMM stores,
20056   // and one block is the final destination regardless of whether any
20057   // stores were performed.
20058   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20059   MachineFunction *F = MBB->getParent();
20060   MachineFunction::iterator MBBIter = MBB;
20061   ++MBBIter;
20062   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20063   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20064   F->insert(MBBIter, XMMSaveMBB);
20065   F->insert(MBBIter, EndMBB);
20066
20067   // Transfer the remainder of MBB and its successor edges to EndMBB.
20068   EndMBB->splice(EndMBB->begin(), MBB,
20069                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20070   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20071
20072   // The original block will now fall through to the XMM save block.
20073   MBB->addSuccessor(XMMSaveMBB);
20074   // The XMMSaveMBB will fall through to the end block.
20075   XMMSaveMBB->addSuccessor(EndMBB);
20076
20077   // Now add the instructions.
20078   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20079   DebugLoc DL = MI->getDebugLoc();
20080
20081   unsigned CountReg = MI->getOperand(0).getReg();
20082   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20083   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20084
20085   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20086     // If %al is 0, branch around the XMM save block.
20087     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20088     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20089     MBB->addSuccessor(EndMBB);
20090   }
20091
20092   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20093   // that was just emitted, but clearly shouldn't be "saved".
20094   assert((MI->getNumOperands() <= 3 ||
20095           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20096           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20097          && "Expected last argument to be EFLAGS");
20098   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20099   // In the XMM save block, save all the XMM argument registers.
20100   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20101     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20102     MachineMemOperand *MMO = F->getMachineMemOperand(
20103         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20104         MachineMemOperand::MOStore,
20105         /*Size=*/16, /*Align=*/16);
20106     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20107       .addFrameIndex(RegSaveFrameIndex)
20108       .addImm(/*Scale=*/1)
20109       .addReg(/*IndexReg=*/0)
20110       .addImm(/*Disp=*/Offset)
20111       .addReg(/*Segment=*/0)
20112       .addReg(MI->getOperand(i).getReg())
20113       .addMemOperand(MMO);
20114   }
20115
20116   MI->eraseFromParent();   // The pseudo instruction is gone now.
20117
20118   return EndMBB;
20119 }
20120
20121 // The EFLAGS operand of SelectItr might be missing a kill marker
20122 // because there were multiple uses of EFLAGS, and ISel didn't know
20123 // which to mark. Figure out whether SelectItr should have had a
20124 // kill marker, and set it if it should. Returns the correct kill
20125 // marker value.
20126 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20127                                      MachineBasicBlock* BB,
20128                                      const TargetRegisterInfo* TRI) {
20129   // Scan forward through BB for a use/def of EFLAGS.
20130   MachineBasicBlock::iterator miI(std::next(SelectItr));
20131   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20132     const MachineInstr& mi = *miI;
20133     if (mi.readsRegister(X86::EFLAGS))
20134       return false;
20135     if (mi.definesRegister(X86::EFLAGS))
20136       break; // Should have kill-flag - update below.
20137   }
20138
20139   // If we hit the end of the block, check whether EFLAGS is live into a
20140   // successor.
20141   if (miI == BB->end()) {
20142     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20143                                           sEnd = BB->succ_end();
20144          sItr != sEnd; ++sItr) {
20145       MachineBasicBlock* succ = *sItr;
20146       if (succ->isLiveIn(X86::EFLAGS))
20147         return false;
20148     }
20149   }
20150
20151   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20152   // out. SelectMI should have a kill flag on EFLAGS.
20153   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20154   return true;
20155 }
20156
20157 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20158 // together with other CMOV pseudo-opcodes into a single basic-block with
20159 // conditional jump around it.
20160 static bool isCMOVPseudo(MachineInstr *MI) {
20161   switch (MI->getOpcode()) {
20162   case X86::CMOV_FR32:
20163   case X86::CMOV_FR64:
20164   case X86::CMOV_GR8:
20165   case X86::CMOV_GR16:
20166   case X86::CMOV_GR32:
20167   case X86::CMOV_RFP32:
20168   case X86::CMOV_RFP64:
20169   case X86::CMOV_RFP80:
20170   case X86::CMOV_V2F64:
20171   case X86::CMOV_V2I64:
20172   case X86::CMOV_V4F32:
20173   case X86::CMOV_V4F64:
20174   case X86::CMOV_V4I64:
20175   case X86::CMOV_V16F32:
20176   case X86::CMOV_V8F32:
20177   case X86::CMOV_V8F64:
20178   case X86::CMOV_V8I64:
20179   case X86::CMOV_V8I1:
20180   case X86::CMOV_V16I1:
20181   case X86::CMOV_V32I1:
20182   case X86::CMOV_V64I1:
20183     return true;
20184
20185   default:
20186     return false;
20187   }
20188 }
20189
20190 MachineBasicBlock *
20191 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20192                                      MachineBasicBlock *BB) const {
20193   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20194   DebugLoc DL = MI->getDebugLoc();
20195
20196   // To "insert" a SELECT_CC instruction, we actually have to insert the
20197   // diamond control-flow pattern.  The incoming instruction knows the
20198   // destination vreg to set, the condition code register to branch on, the
20199   // true/false values to select between, and a branch opcode to use.
20200   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20201   MachineFunction::iterator It = BB;
20202   ++It;
20203
20204   //  thisMBB:
20205   //  ...
20206   //   TrueVal = ...
20207   //   cmpTY ccX, r1, r2
20208   //   bCC copy1MBB
20209   //   fallthrough --> copy0MBB
20210   MachineBasicBlock *thisMBB = BB;
20211   MachineFunction *F = BB->getParent();
20212
20213   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20214   // as described above, by inserting a BB, and then making a PHI at the join
20215   // point to select the true and false operands of the CMOV in the PHI.
20216   //
20217   // The code also handles two different cases of multiple CMOV opcodes
20218   // in a row.
20219   //
20220   // Case 1:
20221   // In this case, there are multiple CMOVs in a row, all which are based on
20222   // the same condition setting (or the exact opposite condition setting).
20223   // In this case we can lower all the CMOVs using a single inserted BB, and
20224   // then make a number of PHIs at the join point to model the CMOVs. The only
20225   // trickiness here, is that in a case like:
20226   //
20227   // t2 = CMOV cond1 t1, f1
20228   // t3 = CMOV cond1 t2, f2
20229   //
20230   // when rewriting this into PHIs, we have to perform some renaming on the
20231   // temps since you cannot have a PHI operand refer to a PHI result earlier
20232   // in the same block.  The "simple" but wrong lowering would be:
20233   //
20234   // t2 = PHI t1(BB1), f1(BB2)
20235   // t3 = PHI t2(BB1), f2(BB2)
20236   //
20237   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20238   // renaming is to note that on the path through BB1, t2 is really just a
20239   // copy of t1, and do that renaming, properly generating:
20240   //
20241   // t2 = PHI t1(BB1), f1(BB2)
20242   // t3 = PHI t1(BB1), f2(BB2)
20243   //
20244   // Case 2, we lower cascaded CMOVs such as
20245   //
20246   //   (CMOV (CMOV F, T, cc1), T, cc2)
20247   //
20248   // to two successives branches.  For that, we look for another CMOV as the
20249   // following instruction.
20250   //
20251   // Without this, we would add a PHI between the two jumps, which ends up
20252   // creating a few copies all around. For instance, for
20253   //
20254   //    (sitofp (zext (fcmp une)))
20255   //
20256   // we would generate:
20257   //
20258   //         ucomiss %xmm1, %xmm0
20259   //         movss  <1.0f>, %xmm0
20260   //         movaps  %xmm0, %xmm1
20261   //         jne     .LBB5_2
20262   //         xorps   %xmm1, %xmm1
20263   // .LBB5_2:
20264   //         jp      .LBB5_4
20265   //         movaps  %xmm1, %xmm0
20266   // .LBB5_4:
20267   //         retq
20268   //
20269   // because this custom-inserter would have generated:
20270   //
20271   //   A
20272   //   | \
20273   //   |  B
20274   //   | /
20275   //   C
20276   //   | \
20277   //   |  D
20278   //   | /
20279   //   E
20280   //
20281   // A: X = ...; Y = ...
20282   // B: empty
20283   // C: Z = PHI [X, A], [Y, B]
20284   // D: empty
20285   // E: PHI [X, C], [Z, D]
20286   //
20287   // If we lower both CMOVs in a single step, we can instead generate:
20288   //
20289   //   A
20290   //   | \
20291   //   |  C
20292   //   | /|
20293   //   |/ |
20294   //   |  |
20295   //   |  D
20296   //   | /
20297   //   E
20298   //
20299   // A: X = ...; Y = ...
20300   // D: empty
20301   // E: PHI [X, A], [X, C], [Y, D]
20302   //
20303   // Which, in our sitofp/fcmp example, gives us something like:
20304   //
20305   //         ucomiss %xmm1, %xmm0
20306   //         movss  <1.0f>, %xmm0
20307   //         jne     .LBB5_4
20308   //         jp      .LBB5_4
20309   //         xorps   %xmm0, %xmm0
20310   // .LBB5_4:
20311   //         retq
20312   //
20313   MachineInstr *CascadedCMOV = nullptr;
20314   MachineInstr *LastCMOV = MI;
20315   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20316   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20317   MachineBasicBlock::iterator NextMIIt =
20318       std::next(MachineBasicBlock::iterator(MI));
20319
20320   // Check for case 1, where there are multiple CMOVs with the same condition
20321   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
20322   // number of jumps the most.
20323
20324   if (isCMOVPseudo(MI)) {
20325     // See if we have a string of CMOVS with the same condition.
20326     while (NextMIIt != BB->end() &&
20327            isCMOVPseudo(NextMIIt) &&
20328            (NextMIIt->getOperand(3).getImm() == CC ||
20329             NextMIIt->getOperand(3).getImm() == OppCC)) {
20330       LastCMOV = &*NextMIIt;
20331       ++NextMIIt;
20332     }
20333   }
20334
20335   // This checks for case 2, but only do this if we didn't already find
20336   // case 1, as indicated by LastCMOV == MI.
20337   if (LastCMOV == MI &&
20338       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20339       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20340       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20341     CascadedCMOV = &*NextMIIt;
20342   }
20343
20344   MachineBasicBlock *jcc1MBB = nullptr;
20345
20346   // If we have a cascaded CMOV, we lower it to two successive branches to
20347   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20348   if (CascadedCMOV) {
20349     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20350     F->insert(It, jcc1MBB);
20351     jcc1MBB->addLiveIn(X86::EFLAGS);
20352   }
20353
20354   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20355   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20356   F->insert(It, copy0MBB);
20357   F->insert(It, sinkMBB);
20358
20359   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20360   // live into the sink and copy blocks.
20361   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20362
20363   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20364   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20365       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20366     copy0MBB->addLiveIn(X86::EFLAGS);
20367     sinkMBB->addLiveIn(X86::EFLAGS);
20368   }
20369
20370   // Transfer the remainder of BB and its successor edges to sinkMBB.
20371   sinkMBB->splice(sinkMBB->begin(), BB,
20372                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20373   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20374
20375   // Add the true and fallthrough blocks as its successors.
20376   if (CascadedCMOV) {
20377     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20378     BB->addSuccessor(jcc1MBB);
20379
20380     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20381     // jump to the sinkMBB.
20382     jcc1MBB->addSuccessor(copy0MBB);
20383     jcc1MBB->addSuccessor(sinkMBB);
20384   } else {
20385     BB->addSuccessor(copy0MBB);
20386   }
20387
20388   // The true block target of the first (or only) branch is always sinkMBB.
20389   BB->addSuccessor(sinkMBB);
20390
20391   // Create the conditional branch instruction.
20392   unsigned Opc = X86::GetCondBranchFromCond(CC);
20393   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20394
20395   if (CascadedCMOV) {
20396     unsigned Opc2 = X86::GetCondBranchFromCond(
20397         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20398     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20399   }
20400
20401   //  copy0MBB:
20402   //   %FalseValue = ...
20403   //   # fallthrough to sinkMBB
20404   copy0MBB->addSuccessor(sinkMBB);
20405
20406   //  sinkMBB:
20407   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20408   //  ...
20409   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20410   MachineBasicBlock::iterator MIItEnd =
20411     std::next(MachineBasicBlock::iterator(LastCMOV));
20412   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20413   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20414   MachineInstrBuilder MIB;
20415
20416   // As we are creating the PHIs, we have to be careful if there is more than
20417   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
20418   // PHIs have to reference the individual true/false inputs from earlier PHIs.
20419   // That also means that PHI construction must work forward from earlier to
20420   // later, and that the code must maintain a mapping from earlier PHI's
20421   // destination registers, and the registers that went into the PHI.
20422
20423   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20424     unsigned DestReg = MIIt->getOperand(0).getReg();
20425     unsigned Op1Reg = MIIt->getOperand(1).getReg();
20426     unsigned Op2Reg = MIIt->getOperand(2).getReg();
20427
20428     // If this CMOV we are generating is the opposite condition from
20429     // the jump we generated, then we have to swap the operands for the
20430     // PHI that is going to be generated.
20431     if (MIIt->getOperand(3).getImm() == OppCC)
20432         std::swap(Op1Reg, Op2Reg);
20433
20434     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20435       Op1Reg = RegRewriteTable[Op1Reg].first;
20436
20437     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20438       Op2Reg = RegRewriteTable[Op2Reg].second;
20439
20440     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20441                   TII->get(X86::PHI), DestReg)
20442           .addReg(Op1Reg).addMBB(copy0MBB)
20443           .addReg(Op2Reg).addMBB(thisMBB);
20444
20445     // Add this PHI to the rewrite table.
20446     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20447   }
20448
20449   // If we have a cascaded CMOV, the second Jcc provides the same incoming
20450   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20451   if (CascadedCMOV) {
20452     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20453     // Copy the PHI result to the register defined by the second CMOV.
20454     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20455             DL, TII->get(TargetOpcode::COPY),
20456             CascadedCMOV->getOperand(0).getReg())
20457         .addReg(MI->getOperand(0).getReg());
20458     CascadedCMOV->eraseFromParent();
20459   }
20460
20461   // Now remove the CMOV(s).
20462   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20463     (MIIt++)->eraseFromParent();
20464
20465   return sinkMBB;
20466 }
20467
20468 MachineBasicBlock *
20469 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20470                                        MachineBasicBlock *BB) const {
20471   // Combine the following atomic floating-point modification pattern:
20472   //   a.store(reg OP a.load(acquire), release)
20473   // Transform them into:
20474   //   OPss (%gpr), %xmm
20475   //   movss %xmm, (%gpr)
20476   // Or sd equivalent for 64-bit operations.
20477   unsigned MOp, FOp;
20478   switch (MI->getOpcode()) {
20479   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20480   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20481   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20482   }
20483   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20484   DebugLoc DL = MI->getDebugLoc();
20485   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20486   unsigned MSrc = MI->getOperand(0).getReg();
20487   unsigned VSrc = MI->getOperand(5).getReg();
20488   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20489                                 .addReg(/*Base=*/MSrc)
20490                                 .addImm(/*Scale=*/1)
20491                                 .addReg(/*Index=*/0)
20492                                 .addImm(0)
20493                                 .addReg(0);
20494   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20495                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20496                           .addReg(VSrc)
20497                           .addReg(/*Base=*/MSrc)
20498                           .addImm(/*Scale=*/1)
20499                           .addReg(/*Index=*/0)
20500                           .addImm(/*Disp=*/0)
20501                           .addReg(/*Segment=*/0);
20502   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20503   MI->eraseFromParent(); // The pseudo instruction is gone now.
20504   return BB;
20505 }
20506
20507 MachineBasicBlock *
20508 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20509                                         MachineBasicBlock *BB) const {
20510   MachineFunction *MF = BB->getParent();
20511   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20512   DebugLoc DL = MI->getDebugLoc();
20513   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20514
20515   assert(MF->shouldSplitStack());
20516
20517   const bool Is64Bit = Subtarget->is64Bit();
20518   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20519
20520   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20521   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20522
20523   // BB:
20524   //  ... [Till the alloca]
20525   // If stacklet is not large enough, jump to mallocMBB
20526   //
20527   // bumpMBB:
20528   //  Allocate by subtracting from RSP
20529   //  Jump to continueMBB
20530   //
20531   // mallocMBB:
20532   //  Allocate by call to runtime
20533   //
20534   // continueMBB:
20535   //  ...
20536   //  [rest of original BB]
20537   //
20538
20539   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20540   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20541   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20542
20543   MachineRegisterInfo &MRI = MF->getRegInfo();
20544   const TargetRegisterClass *AddrRegClass =
20545       getRegClassFor(getPointerTy(MF->getDataLayout()));
20546
20547   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20548     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20549     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20550     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20551     sizeVReg = MI->getOperand(1).getReg(),
20552     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20553
20554   MachineFunction::iterator MBBIter = BB;
20555   ++MBBIter;
20556
20557   MF->insert(MBBIter, bumpMBB);
20558   MF->insert(MBBIter, mallocMBB);
20559   MF->insert(MBBIter, continueMBB);
20560
20561   continueMBB->splice(continueMBB->begin(), BB,
20562                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20563   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20564
20565   // Add code to the main basic block to check if the stack limit has been hit,
20566   // and if so, jump to mallocMBB otherwise to bumpMBB.
20567   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20568   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20569     .addReg(tmpSPVReg).addReg(sizeVReg);
20570   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20571     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20572     .addReg(SPLimitVReg);
20573   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20574
20575   // bumpMBB simply decreases the stack pointer, since we know the current
20576   // stacklet has enough space.
20577   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20578     .addReg(SPLimitVReg);
20579   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20580     .addReg(SPLimitVReg);
20581   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20582
20583   // Calls into a routine in libgcc to allocate more space from the heap.
20584   const uint32_t *RegMask =
20585       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20586   if (IsLP64) {
20587     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20588       .addReg(sizeVReg);
20589     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20590       .addExternalSymbol("__morestack_allocate_stack_space")
20591       .addRegMask(RegMask)
20592       .addReg(X86::RDI, RegState::Implicit)
20593       .addReg(X86::RAX, RegState::ImplicitDefine);
20594   } else if (Is64Bit) {
20595     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20596       .addReg(sizeVReg);
20597     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20598       .addExternalSymbol("__morestack_allocate_stack_space")
20599       .addRegMask(RegMask)
20600       .addReg(X86::EDI, RegState::Implicit)
20601       .addReg(X86::EAX, RegState::ImplicitDefine);
20602   } else {
20603     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20604       .addImm(12);
20605     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20606     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20607       .addExternalSymbol("__morestack_allocate_stack_space")
20608       .addRegMask(RegMask)
20609       .addReg(X86::EAX, RegState::ImplicitDefine);
20610   }
20611
20612   if (!Is64Bit)
20613     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20614       .addImm(16);
20615
20616   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20617     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20618   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20619
20620   // Set up the CFG correctly.
20621   BB->addSuccessor(bumpMBB);
20622   BB->addSuccessor(mallocMBB);
20623   mallocMBB->addSuccessor(continueMBB);
20624   bumpMBB->addSuccessor(continueMBB);
20625
20626   // Take care of the PHI nodes.
20627   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20628           MI->getOperand(0).getReg())
20629     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20630     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20631
20632   // Delete the original pseudo instruction.
20633   MI->eraseFromParent();
20634
20635   // And we're done.
20636   return continueMBB;
20637 }
20638
20639 MachineBasicBlock *
20640 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20641                                         MachineBasicBlock *BB) const {
20642   DebugLoc DL = MI->getDebugLoc();
20643
20644   assert(!Subtarget->isTargetMachO());
20645
20646   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20647                                                     DL);
20648
20649   MI->eraseFromParent();   // The pseudo instruction is gone now.
20650   return BB;
20651 }
20652
20653 MachineBasicBlock *
20654 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20655                                       MachineBasicBlock *BB) const {
20656   // This is pretty easy.  We're taking the value that we received from
20657   // our load from the relocation, sticking it in either RDI (x86-64)
20658   // or EAX and doing an indirect call.  The return value will then
20659   // be in the normal return register.
20660   MachineFunction *F = BB->getParent();
20661   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20662   DebugLoc DL = MI->getDebugLoc();
20663
20664   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20665   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20666
20667   // Get a register mask for the lowered call.
20668   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20669   // proper register mask.
20670   const uint32_t *RegMask =
20671       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20672   if (Subtarget->is64Bit()) {
20673     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20674                                       TII->get(X86::MOV64rm), X86::RDI)
20675     .addReg(X86::RIP)
20676     .addImm(0).addReg(0)
20677     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20678                       MI->getOperand(3).getTargetFlags())
20679     .addReg(0);
20680     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20681     addDirectMem(MIB, X86::RDI);
20682     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20683   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20684     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20685                                       TII->get(X86::MOV32rm), X86::EAX)
20686     .addReg(0)
20687     .addImm(0).addReg(0)
20688     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20689                       MI->getOperand(3).getTargetFlags())
20690     .addReg(0);
20691     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20692     addDirectMem(MIB, X86::EAX);
20693     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20694   } else {
20695     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20696                                       TII->get(X86::MOV32rm), X86::EAX)
20697     .addReg(TII->getGlobalBaseReg(F))
20698     .addImm(0).addReg(0)
20699     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20700                       MI->getOperand(3).getTargetFlags())
20701     .addReg(0);
20702     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20703     addDirectMem(MIB, X86::EAX);
20704     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20705   }
20706
20707   MI->eraseFromParent(); // The pseudo instruction is gone now.
20708   return BB;
20709 }
20710
20711 MachineBasicBlock *
20712 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20713                                     MachineBasicBlock *MBB) const {
20714   DebugLoc DL = MI->getDebugLoc();
20715   MachineFunction *MF = MBB->getParent();
20716   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20717   MachineRegisterInfo &MRI = MF->getRegInfo();
20718
20719   const BasicBlock *BB = MBB->getBasicBlock();
20720   MachineFunction::iterator I = MBB;
20721   ++I;
20722
20723   // Memory Reference
20724   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20725   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20726
20727   unsigned DstReg;
20728   unsigned MemOpndSlot = 0;
20729
20730   unsigned CurOp = 0;
20731
20732   DstReg = MI->getOperand(CurOp++).getReg();
20733   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20734   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20735   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20736   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20737
20738   MemOpndSlot = CurOp;
20739
20740   MVT PVT = getPointerTy(MF->getDataLayout());
20741   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20742          "Invalid Pointer Size!");
20743
20744   // For v = setjmp(buf), we generate
20745   //
20746   // thisMBB:
20747   //  buf[LabelOffset] = restoreMBB
20748   //  SjLjSetup restoreMBB
20749   //
20750   // mainMBB:
20751   //  v_main = 0
20752   //
20753   // sinkMBB:
20754   //  v = phi(main, restore)
20755   //
20756   // restoreMBB:
20757   //  if base pointer being used, load it from frame
20758   //  v_restore = 1
20759
20760   MachineBasicBlock *thisMBB = MBB;
20761   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20762   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20763   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20764   MF->insert(I, mainMBB);
20765   MF->insert(I, sinkMBB);
20766   MF->push_back(restoreMBB);
20767
20768   MachineInstrBuilder MIB;
20769
20770   // Transfer the remainder of BB and its successor edges to sinkMBB.
20771   sinkMBB->splice(sinkMBB->begin(), MBB,
20772                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20773   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20774
20775   // thisMBB:
20776   unsigned PtrStoreOpc = 0;
20777   unsigned LabelReg = 0;
20778   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20779   Reloc::Model RM = MF->getTarget().getRelocationModel();
20780   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20781                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20782
20783   // Prepare IP either in reg or imm.
20784   if (!UseImmLabel) {
20785     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20786     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20787     LabelReg = MRI.createVirtualRegister(PtrRC);
20788     if (Subtarget->is64Bit()) {
20789       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20790               .addReg(X86::RIP)
20791               .addImm(0)
20792               .addReg(0)
20793               .addMBB(restoreMBB)
20794               .addReg(0);
20795     } else {
20796       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20797       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20798               .addReg(XII->getGlobalBaseReg(MF))
20799               .addImm(0)
20800               .addReg(0)
20801               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20802               .addReg(0);
20803     }
20804   } else
20805     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20806   // Store IP
20807   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20808   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20809     if (i == X86::AddrDisp)
20810       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20811     else
20812       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20813   }
20814   if (!UseImmLabel)
20815     MIB.addReg(LabelReg);
20816   else
20817     MIB.addMBB(restoreMBB);
20818   MIB.setMemRefs(MMOBegin, MMOEnd);
20819   // Setup
20820   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20821           .addMBB(restoreMBB);
20822
20823   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20824   MIB.addRegMask(RegInfo->getNoPreservedMask());
20825   thisMBB->addSuccessor(mainMBB);
20826   thisMBB->addSuccessor(restoreMBB);
20827
20828   // mainMBB:
20829   //  EAX = 0
20830   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20831   mainMBB->addSuccessor(sinkMBB);
20832
20833   // sinkMBB:
20834   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20835           TII->get(X86::PHI), DstReg)
20836     .addReg(mainDstReg).addMBB(mainMBB)
20837     .addReg(restoreDstReg).addMBB(restoreMBB);
20838
20839   // restoreMBB:
20840   if (RegInfo->hasBasePointer(*MF)) {
20841     const bool Uses64BitFramePtr =
20842         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20843     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20844     X86FI->setRestoreBasePointer(MF);
20845     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20846     unsigned BasePtr = RegInfo->getBaseRegister();
20847     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20848     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20849                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20850       .setMIFlag(MachineInstr::FrameSetup);
20851   }
20852   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20853   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20854   restoreMBB->addSuccessor(sinkMBB);
20855
20856   MI->eraseFromParent();
20857   return sinkMBB;
20858 }
20859
20860 MachineBasicBlock *
20861 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20862                                      MachineBasicBlock *MBB) const {
20863   DebugLoc DL = MI->getDebugLoc();
20864   MachineFunction *MF = MBB->getParent();
20865   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20866   MachineRegisterInfo &MRI = MF->getRegInfo();
20867
20868   // Memory Reference
20869   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20870   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20871
20872   MVT PVT = getPointerTy(MF->getDataLayout());
20873   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20874          "Invalid Pointer Size!");
20875
20876   const TargetRegisterClass *RC =
20877     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20878   unsigned Tmp = MRI.createVirtualRegister(RC);
20879   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20880   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20881   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20882   unsigned SP = RegInfo->getStackRegister();
20883
20884   MachineInstrBuilder MIB;
20885
20886   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20887   const int64_t SPOffset = 2 * PVT.getStoreSize();
20888
20889   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20890   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20891
20892   // Reload FP
20893   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20894   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20895     MIB.addOperand(MI->getOperand(i));
20896   MIB.setMemRefs(MMOBegin, MMOEnd);
20897   // Reload IP
20898   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20899   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20900     if (i == X86::AddrDisp)
20901       MIB.addDisp(MI->getOperand(i), LabelOffset);
20902     else
20903       MIB.addOperand(MI->getOperand(i));
20904   }
20905   MIB.setMemRefs(MMOBegin, MMOEnd);
20906   // Reload SP
20907   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20908   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20909     if (i == X86::AddrDisp)
20910       MIB.addDisp(MI->getOperand(i), SPOffset);
20911     else
20912       MIB.addOperand(MI->getOperand(i));
20913   }
20914   MIB.setMemRefs(MMOBegin, MMOEnd);
20915   // Jump
20916   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20917
20918   MI->eraseFromParent();
20919   return MBB;
20920 }
20921
20922 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20923 // accumulator loops. Writing back to the accumulator allows the coalescer
20924 // to remove extra copies in the loop.
20925 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20926 MachineBasicBlock *
20927 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20928                                  MachineBasicBlock *MBB) const {
20929   MachineOperand &AddendOp = MI->getOperand(3);
20930
20931   // Bail out early if the addend isn't a register - we can't switch these.
20932   if (!AddendOp.isReg())
20933     return MBB;
20934
20935   MachineFunction &MF = *MBB->getParent();
20936   MachineRegisterInfo &MRI = MF.getRegInfo();
20937
20938   // Check whether the addend is defined by a PHI:
20939   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20940   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20941   if (!AddendDef.isPHI())
20942     return MBB;
20943
20944   // Look for the following pattern:
20945   // loop:
20946   //   %addend = phi [%entry, 0], [%loop, %result]
20947   //   ...
20948   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20949
20950   // Replace with:
20951   //   loop:
20952   //   %addend = phi [%entry, 0], [%loop, %result]
20953   //   ...
20954   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20955
20956   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20957     assert(AddendDef.getOperand(i).isReg());
20958     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20959     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20960     if (&PHISrcInst == MI) {
20961       // Found a matching instruction.
20962       unsigned NewFMAOpc = 0;
20963       switch (MI->getOpcode()) {
20964         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20965         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20966         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20967         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20968         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20969         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20970         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20971         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20972         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20973         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20974         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20975         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20976         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20977         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20978         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20979         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20980         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20981         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20982         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20983         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20984
20985         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20986         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20987         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20988         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20989         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20990         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20991         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20992         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20993         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20994         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20995         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20996         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20997         default: llvm_unreachable("Unrecognized FMA variant.");
20998       }
20999
21000       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21001       MachineInstrBuilder MIB =
21002         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21003         .addOperand(MI->getOperand(0))
21004         .addOperand(MI->getOperand(3))
21005         .addOperand(MI->getOperand(2))
21006         .addOperand(MI->getOperand(1));
21007       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21008       MI->eraseFromParent();
21009     }
21010   }
21011
21012   return MBB;
21013 }
21014
21015 MachineBasicBlock *
21016 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21017                                                MachineBasicBlock *BB) const {
21018   switch (MI->getOpcode()) {
21019   default: llvm_unreachable("Unexpected instr type to insert");
21020   case X86::TAILJMPd64:
21021   case X86::TAILJMPr64:
21022   case X86::TAILJMPm64:
21023   case X86::TAILJMPd64_REX:
21024   case X86::TAILJMPr64_REX:
21025   case X86::TAILJMPm64_REX:
21026     llvm_unreachable("TAILJMP64 would not be touched here.");
21027   case X86::TCRETURNdi64:
21028   case X86::TCRETURNri64:
21029   case X86::TCRETURNmi64:
21030     return BB;
21031   case X86::WIN_ALLOCA:
21032     return EmitLoweredWinAlloca(MI, BB);
21033   case X86::SEG_ALLOCA_32:
21034   case X86::SEG_ALLOCA_64:
21035     return EmitLoweredSegAlloca(MI, BB);
21036   case X86::TLSCall_32:
21037   case X86::TLSCall_64:
21038     return EmitLoweredTLSCall(MI, BB);
21039   case X86::CMOV_FR32:
21040   case X86::CMOV_FR64:
21041   case X86::CMOV_GR8:
21042   case X86::CMOV_GR16:
21043   case X86::CMOV_GR32:
21044   case X86::CMOV_RFP32:
21045   case X86::CMOV_RFP64:
21046   case X86::CMOV_RFP80:
21047   case X86::CMOV_V2F64:
21048   case X86::CMOV_V2I64:
21049   case X86::CMOV_V4F32:
21050   case X86::CMOV_V4F64:
21051   case X86::CMOV_V4I64:
21052   case X86::CMOV_V16F32:
21053   case X86::CMOV_V8F32:
21054   case X86::CMOV_V8F64:
21055   case X86::CMOV_V8I64:
21056   case X86::CMOV_V8I1:
21057   case X86::CMOV_V16I1:
21058   case X86::CMOV_V32I1:
21059   case X86::CMOV_V64I1:
21060     return EmitLoweredSelect(MI, BB);
21061
21062   case X86::RELEASE_FADD32mr:
21063   case X86::RELEASE_FADD64mr:
21064     return EmitLoweredAtomicFP(MI, BB);
21065
21066   case X86::FP32_TO_INT16_IN_MEM:
21067   case X86::FP32_TO_INT32_IN_MEM:
21068   case X86::FP32_TO_INT64_IN_MEM:
21069   case X86::FP64_TO_INT16_IN_MEM:
21070   case X86::FP64_TO_INT32_IN_MEM:
21071   case X86::FP64_TO_INT64_IN_MEM:
21072   case X86::FP80_TO_INT16_IN_MEM:
21073   case X86::FP80_TO_INT32_IN_MEM:
21074   case X86::FP80_TO_INT64_IN_MEM: {
21075     MachineFunction *F = BB->getParent();
21076     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21077     DebugLoc DL = MI->getDebugLoc();
21078
21079     // Change the floating point control register to use "round towards zero"
21080     // mode when truncating to an integer value.
21081     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21082     addFrameReference(BuildMI(*BB, MI, DL,
21083                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21084
21085     // Load the old value of the high byte of the control word...
21086     unsigned OldCW =
21087       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21088     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21089                       CWFrameIdx);
21090
21091     // Set the high part to be round to zero...
21092     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21093       .addImm(0xC7F);
21094
21095     // Reload the modified control word now...
21096     addFrameReference(BuildMI(*BB, MI, DL,
21097                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21098
21099     // Restore the memory image of control word to original value
21100     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21101       .addReg(OldCW);
21102
21103     // Get the X86 opcode to use.
21104     unsigned Opc;
21105     switch (MI->getOpcode()) {
21106     default: llvm_unreachable("illegal opcode!");
21107     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21108     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21109     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21110     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21111     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21112     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21113     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21114     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21115     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21116     }
21117
21118     X86AddressMode AM;
21119     MachineOperand &Op = MI->getOperand(0);
21120     if (Op.isReg()) {
21121       AM.BaseType = X86AddressMode::RegBase;
21122       AM.Base.Reg = Op.getReg();
21123     } else {
21124       AM.BaseType = X86AddressMode::FrameIndexBase;
21125       AM.Base.FrameIndex = Op.getIndex();
21126     }
21127     Op = MI->getOperand(1);
21128     if (Op.isImm())
21129       AM.Scale = Op.getImm();
21130     Op = MI->getOperand(2);
21131     if (Op.isImm())
21132       AM.IndexReg = Op.getImm();
21133     Op = MI->getOperand(3);
21134     if (Op.isGlobal()) {
21135       AM.GV = Op.getGlobal();
21136     } else {
21137       AM.Disp = Op.getImm();
21138     }
21139     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21140                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21141
21142     // Reload the original control word now.
21143     addFrameReference(BuildMI(*BB, MI, DL,
21144                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21145
21146     MI->eraseFromParent();   // The pseudo instruction is gone now.
21147     return BB;
21148   }
21149     // String/text processing lowering.
21150   case X86::PCMPISTRM128REG:
21151   case X86::VPCMPISTRM128REG:
21152   case X86::PCMPISTRM128MEM:
21153   case X86::VPCMPISTRM128MEM:
21154   case X86::PCMPESTRM128REG:
21155   case X86::VPCMPESTRM128REG:
21156   case X86::PCMPESTRM128MEM:
21157   case X86::VPCMPESTRM128MEM:
21158     assert(Subtarget->hasSSE42() &&
21159            "Target must have SSE4.2 or AVX features enabled");
21160     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21161
21162   // String/text processing lowering.
21163   case X86::PCMPISTRIREG:
21164   case X86::VPCMPISTRIREG:
21165   case X86::PCMPISTRIMEM:
21166   case X86::VPCMPISTRIMEM:
21167   case X86::PCMPESTRIREG:
21168   case X86::VPCMPESTRIREG:
21169   case X86::PCMPESTRIMEM:
21170   case X86::VPCMPESTRIMEM:
21171     assert(Subtarget->hasSSE42() &&
21172            "Target must have SSE4.2 or AVX features enabled");
21173     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21174
21175   // Thread synchronization.
21176   case X86::MONITOR:
21177     return EmitMonitor(MI, BB, Subtarget);
21178
21179   // xbegin
21180   case X86::XBEGIN:
21181     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21182
21183   case X86::VASTART_SAVE_XMM_REGS:
21184     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21185
21186   case X86::VAARG_64:
21187     return EmitVAARG64WithCustomInserter(MI, BB);
21188
21189   case X86::EH_SjLj_SetJmp32:
21190   case X86::EH_SjLj_SetJmp64:
21191     return emitEHSjLjSetJmp(MI, BB);
21192
21193   case X86::EH_SjLj_LongJmp32:
21194   case X86::EH_SjLj_LongJmp64:
21195     return emitEHSjLjLongJmp(MI, BB);
21196
21197   case TargetOpcode::STATEPOINT:
21198     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21199     // this point in the process.  We diverge later.
21200     return emitPatchPoint(MI, BB);
21201
21202   case TargetOpcode::STACKMAP:
21203   case TargetOpcode::PATCHPOINT:
21204     return emitPatchPoint(MI, BB);
21205
21206   case X86::VFMADDPDr213r:
21207   case X86::VFMADDPSr213r:
21208   case X86::VFMADDSDr213r:
21209   case X86::VFMADDSSr213r:
21210   case X86::VFMSUBPDr213r:
21211   case X86::VFMSUBPSr213r:
21212   case X86::VFMSUBSDr213r:
21213   case X86::VFMSUBSSr213r:
21214   case X86::VFNMADDPDr213r:
21215   case X86::VFNMADDPSr213r:
21216   case X86::VFNMADDSDr213r:
21217   case X86::VFNMADDSSr213r:
21218   case X86::VFNMSUBPDr213r:
21219   case X86::VFNMSUBPSr213r:
21220   case X86::VFNMSUBSDr213r:
21221   case X86::VFNMSUBSSr213r:
21222   case X86::VFMADDSUBPDr213r:
21223   case X86::VFMADDSUBPSr213r:
21224   case X86::VFMSUBADDPDr213r:
21225   case X86::VFMSUBADDPSr213r:
21226   case X86::VFMADDPDr213rY:
21227   case X86::VFMADDPSr213rY:
21228   case X86::VFMSUBPDr213rY:
21229   case X86::VFMSUBPSr213rY:
21230   case X86::VFNMADDPDr213rY:
21231   case X86::VFNMADDPSr213rY:
21232   case X86::VFNMSUBPDr213rY:
21233   case X86::VFNMSUBPSr213rY:
21234   case X86::VFMADDSUBPDr213rY:
21235   case X86::VFMADDSUBPSr213rY:
21236   case X86::VFMSUBADDPDr213rY:
21237   case X86::VFMSUBADDPSr213rY:
21238     return emitFMA3Instr(MI, BB);
21239   }
21240 }
21241
21242 //===----------------------------------------------------------------------===//
21243 //                           X86 Optimization Hooks
21244 //===----------------------------------------------------------------------===//
21245
21246 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21247                                                       APInt &KnownZero,
21248                                                       APInt &KnownOne,
21249                                                       const SelectionDAG &DAG,
21250                                                       unsigned Depth) const {
21251   unsigned BitWidth = KnownZero.getBitWidth();
21252   unsigned Opc = Op.getOpcode();
21253   assert((Opc >= ISD::BUILTIN_OP_END ||
21254           Opc == ISD::INTRINSIC_WO_CHAIN ||
21255           Opc == ISD::INTRINSIC_W_CHAIN ||
21256           Opc == ISD::INTRINSIC_VOID) &&
21257          "Should use MaskedValueIsZero if you don't know whether Op"
21258          " is a target node!");
21259
21260   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21261   switch (Opc) {
21262   default: break;
21263   case X86ISD::ADD:
21264   case X86ISD::SUB:
21265   case X86ISD::ADC:
21266   case X86ISD::SBB:
21267   case X86ISD::SMUL:
21268   case X86ISD::UMUL:
21269   case X86ISD::INC:
21270   case X86ISD::DEC:
21271   case X86ISD::OR:
21272   case X86ISD::XOR:
21273   case X86ISD::AND:
21274     // These nodes' second result is a boolean.
21275     if (Op.getResNo() == 0)
21276       break;
21277     // Fallthrough
21278   case X86ISD::SETCC:
21279     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21280     break;
21281   case ISD::INTRINSIC_WO_CHAIN: {
21282     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21283     unsigned NumLoBits = 0;
21284     switch (IntId) {
21285     default: break;
21286     case Intrinsic::x86_sse_movmsk_ps:
21287     case Intrinsic::x86_avx_movmsk_ps_256:
21288     case Intrinsic::x86_sse2_movmsk_pd:
21289     case Intrinsic::x86_avx_movmsk_pd_256:
21290     case Intrinsic::x86_mmx_pmovmskb:
21291     case Intrinsic::x86_sse2_pmovmskb_128:
21292     case Intrinsic::x86_avx2_pmovmskb: {
21293       // High bits of movmskp{s|d}, pmovmskb are known zero.
21294       switch (IntId) {
21295         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21296         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21297         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21298         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21299         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21300         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21301         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21302         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21303       }
21304       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21305       break;
21306     }
21307     }
21308     break;
21309   }
21310   }
21311 }
21312
21313 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21314   SDValue Op,
21315   const SelectionDAG &,
21316   unsigned Depth) const {
21317   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21318   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21319     return Op.getValueType().getScalarType().getSizeInBits();
21320
21321   // Fallback case.
21322   return 1;
21323 }
21324
21325 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21326 /// node is a GlobalAddress + offset.
21327 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21328                                        const GlobalValue* &GA,
21329                                        int64_t &Offset) const {
21330   if (N->getOpcode() == X86ISD::Wrapper) {
21331     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21332       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21333       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21334       return true;
21335     }
21336   }
21337   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21338 }
21339
21340 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21341 /// same as extracting the high 128-bit part of 256-bit vector and then
21342 /// inserting the result into the low part of a new 256-bit vector
21343 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21344   EVT VT = SVOp->getValueType(0);
21345   unsigned NumElems = VT.getVectorNumElements();
21346
21347   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21348   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21349     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21350         SVOp->getMaskElt(j) >= 0)
21351       return false;
21352
21353   return true;
21354 }
21355
21356 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21357 /// same as extracting the low 128-bit part of 256-bit vector and then
21358 /// inserting the result into the high part of a new 256-bit vector
21359 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21360   EVT VT = SVOp->getValueType(0);
21361   unsigned NumElems = VT.getVectorNumElements();
21362
21363   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21364   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21365     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21366         SVOp->getMaskElt(j) >= 0)
21367       return false;
21368
21369   return true;
21370 }
21371
21372 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21373 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21374                                         TargetLowering::DAGCombinerInfo &DCI,
21375                                         const X86Subtarget* Subtarget) {
21376   SDLoc dl(N);
21377   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21378   SDValue V1 = SVOp->getOperand(0);
21379   SDValue V2 = SVOp->getOperand(1);
21380   EVT VT = SVOp->getValueType(0);
21381   unsigned NumElems = VT.getVectorNumElements();
21382
21383   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21384       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21385     //
21386     //                   0,0,0,...
21387     //                      |
21388     //    V      UNDEF    BUILD_VECTOR    UNDEF
21389     //     \      /           \           /
21390     //  CONCAT_VECTOR         CONCAT_VECTOR
21391     //         \                  /
21392     //          \                /
21393     //          RESULT: V + zero extended
21394     //
21395     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21396         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21397         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21398       return SDValue();
21399
21400     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21401       return SDValue();
21402
21403     // To match the shuffle mask, the first half of the mask should
21404     // be exactly the first vector, and all the rest a splat with the
21405     // first element of the second one.
21406     for (unsigned i = 0; i != NumElems/2; ++i)
21407       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21408           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21409         return SDValue();
21410
21411     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21412     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21413       if (Ld->hasNUsesOfValue(1, 0)) {
21414         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21415         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21416         SDValue ResNode =
21417           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21418                                   Ld->getMemoryVT(),
21419                                   Ld->getPointerInfo(),
21420                                   Ld->getAlignment(),
21421                                   false/*isVolatile*/, true/*ReadMem*/,
21422                                   false/*WriteMem*/);
21423
21424         // Make sure the newly-created LOAD is in the same position as Ld in
21425         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21426         // and update uses of Ld's output chain to use the TokenFactor.
21427         if (Ld->hasAnyUseOfValue(1)) {
21428           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21429                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21430           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21431           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21432                                  SDValue(ResNode.getNode(), 1));
21433         }
21434
21435         return DAG.getBitcast(VT, ResNode);
21436       }
21437     }
21438
21439     // Emit a zeroed vector and insert the desired subvector on its
21440     // first half.
21441     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21442     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21443     return DCI.CombineTo(N, InsV);
21444   }
21445
21446   //===--------------------------------------------------------------------===//
21447   // Combine some shuffles into subvector extracts and inserts:
21448   //
21449
21450   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21451   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21452     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21453     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21454     return DCI.CombineTo(N, InsV);
21455   }
21456
21457   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21458   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21459     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21460     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21461     return DCI.CombineTo(N, InsV);
21462   }
21463
21464   return SDValue();
21465 }
21466
21467 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21468 /// possible.
21469 ///
21470 /// This is the leaf of the recursive combinine below. When we have found some
21471 /// chain of single-use x86 shuffle instructions and accumulated the combined
21472 /// shuffle mask represented by them, this will try to pattern match that mask
21473 /// into either a single instruction if there is a special purpose instruction
21474 /// for this operation, or into a PSHUFB instruction which is a fully general
21475 /// instruction but should only be used to replace chains over a certain depth.
21476 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21477                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21478                                    TargetLowering::DAGCombinerInfo &DCI,
21479                                    const X86Subtarget *Subtarget) {
21480   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21481
21482   // Find the operand that enters the chain. Note that multiple uses are OK
21483   // here, we're not going to remove the operand we find.
21484   SDValue Input = Op.getOperand(0);
21485   while (Input.getOpcode() == ISD::BITCAST)
21486     Input = Input.getOperand(0);
21487
21488   MVT VT = Input.getSimpleValueType();
21489   MVT RootVT = Root.getSimpleValueType();
21490   SDLoc DL(Root);
21491
21492   // Just remove no-op shuffle masks.
21493   if (Mask.size() == 1) {
21494     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21495                   /*AddTo*/ true);
21496     return true;
21497   }
21498
21499   // Use the float domain if the operand type is a floating point type.
21500   bool FloatDomain = VT.isFloatingPoint();
21501
21502   // For floating point shuffles, we don't have free copies in the shuffle
21503   // instructions or the ability to load as part of the instruction, so
21504   // canonicalize their shuffles to UNPCK or MOV variants.
21505   //
21506   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21507   // vectors because it can have a load folded into it that UNPCK cannot. This
21508   // doesn't preclude something switching to the shorter encoding post-RA.
21509   //
21510   // FIXME: Should teach these routines about AVX vector widths.
21511   if (FloatDomain && VT.getSizeInBits() == 128) {
21512     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21513       bool Lo = Mask.equals({0, 0});
21514       unsigned Shuffle;
21515       MVT ShuffleVT;
21516       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21517       // is no slower than UNPCKLPD but has the option to fold the input operand
21518       // into even an unaligned memory load.
21519       if (Lo && Subtarget->hasSSE3()) {
21520         Shuffle = X86ISD::MOVDDUP;
21521         ShuffleVT = MVT::v2f64;
21522       } else {
21523         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21524         // than the UNPCK variants.
21525         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21526         ShuffleVT = MVT::v4f32;
21527       }
21528       if (Depth == 1 && Root->getOpcode() == Shuffle)
21529         return false; // Nothing to do!
21530       Op = DAG.getBitcast(ShuffleVT, Input);
21531       DCI.AddToWorklist(Op.getNode());
21532       if (Shuffle == X86ISD::MOVDDUP)
21533         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21534       else
21535         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21536       DCI.AddToWorklist(Op.getNode());
21537       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21538                     /*AddTo*/ true);
21539       return true;
21540     }
21541     if (Subtarget->hasSSE3() &&
21542         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21543       bool Lo = Mask.equals({0, 0, 2, 2});
21544       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21545       MVT ShuffleVT = MVT::v4f32;
21546       if (Depth == 1 && Root->getOpcode() == Shuffle)
21547         return false; // Nothing to do!
21548       Op = DAG.getBitcast(ShuffleVT, Input);
21549       DCI.AddToWorklist(Op.getNode());
21550       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21551       DCI.AddToWorklist(Op.getNode());
21552       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21553                     /*AddTo*/ true);
21554       return true;
21555     }
21556     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21557       bool Lo = Mask.equals({0, 0, 1, 1});
21558       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21559       MVT ShuffleVT = MVT::v4f32;
21560       if (Depth == 1 && Root->getOpcode() == Shuffle)
21561         return false; // Nothing to do!
21562       Op = DAG.getBitcast(ShuffleVT, Input);
21563       DCI.AddToWorklist(Op.getNode());
21564       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21565       DCI.AddToWorklist(Op.getNode());
21566       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21567                     /*AddTo*/ true);
21568       return true;
21569     }
21570   }
21571
21572   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21573   // variants as none of these have single-instruction variants that are
21574   // superior to the UNPCK formulation.
21575   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21576       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21577        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21578        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21579        Mask.equals(
21580            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21581     bool Lo = Mask[0] == 0;
21582     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21583     if (Depth == 1 && Root->getOpcode() == Shuffle)
21584       return false; // Nothing to do!
21585     MVT ShuffleVT;
21586     switch (Mask.size()) {
21587     case 8:
21588       ShuffleVT = MVT::v8i16;
21589       break;
21590     case 16:
21591       ShuffleVT = MVT::v16i8;
21592       break;
21593     default:
21594       llvm_unreachable("Impossible mask size!");
21595     };
21596     Op = DAG.getBitcast(ShuffleVT, Input);
21597     DCI.AddToWorklist(Op.getNode());
21598     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21599     DCI.AddToWorklist(Op.getNode());
21600     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21601                   /*AddTo*/ true);
21602     return true;
21603   }
21604
21605   // Don't try to re-form single instruction chains under any circumstances now
21606   // that we've done encoding canonicalization for them.
21607   if (Depth < 2)
21608     return false;
21609
21610   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21611   // can replace them with a single PSHUFB instruction profitably. Intel's
21612   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21613   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21614   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21615     SmallVector<SDValue, 16> PSHUFBMask;
21616     int NumBytes = VT.getSizeInBits() / 8;
21617     int Ratio = NumBytes / Mask.size();
21618     for (int i = 0; i < NumBytes; ++i) {
21619       if (Mask[i / Ratio] == SM_SentinelUndef) {
21620         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21621         continue;
21622       }
21623       int M = Mask[i / Ratio] != SM_SentinelZero
21624                   ? Ratio * Mask[i / Ratio] + i % Ratio
21625                   : 255;
21626       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21627     }
21628     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21629     Op = DAG.getBitcast(ByteVT, Input);
21630     DCI.AddToWorklist(Op.getNode());
21631     SDValue PSHUFBMaskOp =
21632         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21633     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21634     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21635     DCI.AddToWorklist(Op.getNode());
21636     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21637                   /*AddTo*/ true);
21638     return true;
21639   }
21640
21641   // Failed to find any combines.
21642   return false;
21643 }
21644
21645 /// \brief Fully generic combining of x86 shuffle instructions.
21646 ///
21647 /// This should be the last combine run over the x86 shuffle instructions. Once
21648 /// they have been fully optimized, this will recursively consider all chains
21649 /// of single-use shuffle instructions, build a generic model of the cumulative
21650 /// shuffle operation, and check for simpler instructions which implement this
21651 /// operation. We use this primarily for two purposes:
21652 ///
21653 /// 1) Collapse generic shuffles to specialized single instructions when
21654 ///    equivalent. In most cases, this is just an encoding size win, but
21655 ///    sometimes we will collapse multiple generic shuffles into a single
21656 ///    special-purpose shuffle.
21657 /// 2) Look for sequences of shuffle instructions with 3 or more total
21658 ///    instructions, and replace them with the slightly more expensive SSSE3
21659 ///    PSHUFB instruction if available. We do this as the last combining step
21660 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21661 ///    a suitable short sequence of other instructions. The PHUFB will either
21662 ///    use a register or have to read from memory and so is slightly (but only
21663 ///    slightly) more expensive than the other shuffle instructions.
21664 ///
21665 /// Because this is inherently a quadratic operation (for each shuffle in
21666 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21667 /// This should never be an issue in practice as the shuffle lowering doesn't
21668 /// produce sequences of more than 8 instructions.
21669 ///
21670 /// FIXME: We will currently miss some cases where the redundant shuffling
21671 /// would simplify under the threshold for PSHUFB formation because of
21672 /// combine-ordering. To fix this, we should do the redundant instruction
21673 /// combining in this recursive walk.
21674 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21675                                           ArrayRef<int> RootMask,
21676                                           int Depth, bool HasPSHUFB,
21677                                           SelectionDAG &DAG,
21678                                           TargetLowering::DAGCombinerInfo &DCI,
21679                                           const X86Subtarget *Subtarget) {
21680   // Bound the depth of our recursive combine because this is ultimately
21681   // quadratic in nature.
21682   if (Depth > 8)
21683     return false;
21684
21685   // Directly rip through bitcasts to find the underlying operand.
21686   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21687     Op = Op.getOperand(0);
21688
21689   MVT VT = Op.getSimpleValueType();
21690   if (!VT.isVector())
21691     return false; // Bail if we hit a non-vector.
21692
21693   assert(Root.getSimpleValueType().isVector() &&
21694          "Shuffles operate on vector types!");
21695   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21696          "Can only combine shuffles of the same vector register size.");
21697
21698   if (!isTargetShuffle(Op.getOpcode()))
21699     return false;
21700   SmallVector<int, 16> OpMask;
21701   bool IsUnary;
21702   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21703   // We only can combine unary shuffles which we can decode the mask for.
21704   if (!HaveMask || !IsUnary)
21705     return false;
21706
21707   assert(VT.getVectorNumElements() == OpMask.size() &&
21708          "Different mask size from vector size!");
21709   assert(((RootMask.size() > OpMask.size() &&
21710            RootMask.size() % OpMask.size() == 0) ||
21711           (OpMask.size() > RootMask.size() &&
21712            OpMask.size() % RootMask.size() == 0) ||
21713           OpMask.size() == RootMask.size()) &&
21714          "The smaller number of elements must divide the larger.");
21715   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21716   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21717   assert(((RootRatio == 1 && OpRatio == 1) ||
21718           (RootRatio == 1) != (OpRatio == 1)) &&
21719          "Must not have a ratio for both incoming and op masks!");
21720
21721   SmallVector<int, 16> Mask;
21722   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21723
21724   // Merge this shuffle operation's mask into our accumulated mask. Note that
21725   // this shuffle's mask will be the first applied to the input, followed by the
21726   // root mask to get us all the way to the root value arrangement. The reason
21727   // for this order is that we are recursing up the operation chain.
21728   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21729     int RootIdx = i / RootRatio;
21730     if (RootMask[RootIdx] < 0) {
21731       // This is a zero or undef lane, we're done.
21732       Mask.push_back(RootMask[RootIdx]);
21733       continue;
21734     }
21735
21736     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21737     int OpIdx = RootMaskedIdx / OpRatio;
21738     if (OpMask[OpIdx] < 0) {
21739       // The incoming lanes are zero or undef, it doesn't matter which ones we
21740       // are using.
21741       Mask.push_back(OpMask[OpIdx]);
21742       continue;
21743     }
21744
21745     // Ok, we have non-zero lanes, map them through.
21746     Mask.push_back(OpMask[OpIdx] * OpRatio +
21747                    RootMaskedIdx % OpRatio);
21748   }
21749
21750   // See if we can recurse into the operand to combine more things.
21751   switch (Op.getOpcode()) {
21752     case X86ISD::PSHUFB:
21753       HasPSHUFB = true;
21754     case X86ISD::PSHUFD:
21755     case X86ISD::PSHUFHW:
21756     case X86ISD::PSHUFLW:
21757       if (Op.getOperand(0).hasOneUse() &&
21758           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21759                                         HasPSHUFB, DAG, DCI, Subtarget))
21760         return true;
21761       break;
21762
21763     case X86ISD::UNPCKL:
21764     case X86ISD::UNPCKH:
21765       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21766       // We can't check for single use, we have to check that this shuffle is the only user.
21767       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21768           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21769                                         HasPSHUFB, DAG, DCI, Subtarget))
21770           return true;
21771       break;
21772   }
21773
21774   // Minor canonicalization of the accumulated shuffle mask to make it easier
21775   // to match below. All this does is detect masks with squential pairs of
21776   // elements, and shrink them to the half-width mask. It does this in a loop
21777   // so it will reduce the size of the mask to the minimal width mask which
21778   // performs an equivalent shuffle.
21779   SmallVector<int, 16> WidenedMask;
21780   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21781     Mask = std::move(WidenedMask);
21782     WidenedMask.clear();
21783   }
21784
21785   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21786                                 Subtarget);
21787 }
21788
21789 /// \brief Get the PSHUF-style mask from PSHUF node.
21790 ///
21791 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21792 /// PSHUF-style masks that can be reused with such instructions.
21793 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21794   MVT VT = N.getSimpleValueType();
21795   SmallVector<int, 4> Mask;
21796   bool IsUnary;
21797   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21798   (void)HaveMask;
21799   assert(HaveMask);
21800
21801   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21802   // matter. Check that the upper masks are repeats and remove them.
21803   if (VT.getSizeInBits() > 128) {
21804     int LaneElts = 128 / VT.getScalarSizeInBits();
21805 #ifndef NDEBUG
21806     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21807       for (int j = 0; j < LaneElts; ++j)
21808         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21809                "Mask doesn't repeat in high 128-bit lanes!");
21810 #endif
21811     Mask.resize(LaneElts);
21812   }
21813
21814   switch (N.getOpcode()) {
21815   case X86ISD::PSHUFD:
21816     return Mask;
21817   case X86ISD::PSHUFLW:
21818     Mask.resize(4);
21819     return Mask;
21820   case X86ISD::PSHUFHW:
21821     Mask.erase(Mask.begin(), Mask.begin() + 4);
21822     for (int &M : Mask)
21823       M -= 4;
21824     return Mask;
21825   default:
21826     llvm_unreachable("No valid shuffle instruction found!");
21827   }
21828 }
21829
21830 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21831 ///
21832 /// We walk up the chain and look for a combinable shuffle, skipping over
21833 /// shuffles that we could hoist this shuffle's transformation past without
21834 /// altering anything.
21835 static SDValue
21836 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21837                              SelectionDAG &DAG,
21838                              TargetLowering::DAGCombinerInfo &DCI) {
21839   assert(N.getOpcode() == X86ISD::PSHUFD &&
21840          "Called with something other than an x86 128-bit half shuffle!");
21841   SDLoc DL(N);
21842
21843   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21844   // of the shuffles in the chain so that we can form a fresh chain to replace
21845   // this one.
21846   SmallVector<SDValue, 8> Chain;
21847   SDValue V = N.getOperand(0);
21848   for (; V.hasOneUse(); V = V.getOperand(0)) {
21849     switch (V.getOpcode()) {
21850     default:
21851       return SDValue(); // Nothing combined!
21852
21853     case ISD::BITCAST:
21854       // Skip bitcasts as we always know the type for the target specific
21855       // instructions.
21856       continue;
21857
21858     case X86ISD::PSHUFD:
21859       // Found another dword shuffle.
21860       break;
21861
21862     case X86ISD::PSHUFLW:
21863       // Check that the low words (being shuffled) are the identity in the
21864       // dword shuffle, and the high words are self-contained.
21865       if (Mask[0] != 0 || Mask[1] != 1 ||
21866           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21867         return SDValue();
21868
21869       Chain.push_back(V);
21870       continue;
21871
21872     case X86ISD::PSHUFHW:
21873       // Check that the high words (being shuffled) are the identity in the
21874       // dword shuffle, and the low words are self-contained.
21875       if (Mask[2] != 2 || Mask[3] != 3 ||
21876           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21877         return SDValue();
21878
21879       Chain.push_back(V);
21880       continue;
21881
21882     case X86ISD::UNPCKL:
21883     case X86ISD::UNPCKH:
21884       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21885       // shuffle into a preceding word shuffle.
21886       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21887           V.getSimpleValueType().getScalarType() != MVT::i16)
21888         return SDValue();
21889
21890       // Search for a half-shuffle which we can combine with.
21891       unsigned CombineOp =
21892           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21893       if (V.getOperand(0) != V.getOperand(1) ||
21894           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21895         return SDValue();
21896       Chain.push_back(V);
21897       V = V.getOperand(0);
21898       do {
21899         switch (V.getOpcode()) {
21900         default:
21901           return SDValue(); // Nothing to combine.
21902
21903         case X86ISD::PSHUFLW:
21904         case X86ISD::PSHUFHW:
21905           if (V.getOpcode() == CombineOp)
21906             break;
21907
21908           Chain.push_back(V);
21909
21910           // Fallthrough!
21911         case ISD::BITCAST:
21912           V = V.getOperand(0);
21913           continue;
21914         }
21915         break;
21916       } while (V.hasOneUse());
21917       break;
21918     }
21919     // Break out of the loop if we break out of the switch.
21920     break;
21921   }
21922
21923   if (!V.hasOneUse())
21924     // We fell out of the loop without finding a viable combining instruction.
21925     return SDValue();
21926
21927   // Merge this node's mask and our incoming mask.
21928   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21929   for (int &M : Mask)
21930     M = VMask[M];
21931   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21932                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21933
21934   // Rebuild the chain around this new shuffle.
21935   while (!Chain.empty()) {
21936     SDValue W = Chain.pop_back_val();
21937
21938     if (V.getValueType() != W.getOperand(0).getValueType())
21939       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21940
21941     switch (W.getOpcode()) {
21942     default:
21943       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21944
21945     case X86ISD::UNPCKL:
21946     case X86ISD::UNPCKH:
21947       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21948       break;
21949
21950     case X86ISD::PSHUFD:
21951     case X86ISD::PSHUFLW:
21952     case X86ISD::PSHUFHW:
21953       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21954       break;
21955     }
21956   }
21957   if (V.getValueType() != N.getValueType())
21958     V = DAG.getBitcast(N.getValueType(), V);
21959
21960   // Return the new chain to replace N.
21961   return V;
21962 }
21963
21964 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21965 ///
21966 /// We walk up the chain, skipping shuffles of the other half and looking
21967 /// through shuffles which switch halves trying to find a shuffle of the same
21968 /// pair of dwords.
21969 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21970                                         SelectionDAG &DAG,
21971                                         TargetLowering::DAGCombinerInfo &DCI) {
21972   assert(
21973       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21974       "Called with something other than an x86 128-bit half shuffle!");
21975   SDLoc DL(N);
21976   unsigned CombineOpcode = N.getOpcode();
21977
21978   // Walk up a single-use chain looking for a combinable shuffle.
21979   SDValue V = N.getOperand(0);
21980   for (; V.hasOneUse(); V = V.getOperand(0)) {
21981     switch (V.getOpcode()) {
21982     default:
21983       return false; // Nothing combined!
21984
21985     case ISD::BITCAST:
21986       // Skip bitcasts as we always know the type for the target specific
21987       // instructions.
21988       continue;
21989
21990     case X86ISD::PSHUFLW:
21991     case X86ISD::PSHUFHW:
21992       if (V.getOpcode() == CombineOpcode)
21993         break;
21994
21995       // Other-half shuffles are no-ops.
21996       continue;
21997     }
21998     // Break out of the loop if we break out of the switch.
21999     break;
22000   }
22001
22002   if (!V.hasOneUse())
22003     // We fell out of the loop without finding a viable combining instruction.
22004     return false;
22005
22006   // Combine away the bottom node as its shuffle will be accumulated into
22007   // a preceding shuffle.
22008   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22009
22010   // Record the old value.
22011   SDValue Old = V;
22012
22013   // Merge this node's mask and our incoming mask (adjusted to account for all
22014   // the pshufd instructions encountered).
22015   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22016   for (int &M : Mask)
22017     M = VMask[M];
22018   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22019                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22020
22021   // Check that the shuffles didn't cancel each other out. If not, we need to
22022   // combine to the new one.
22023   if (Old != V)
22024     // Replace the combinable shuffle with the combined one, updating all users
22025     // so that we re-evaluate the chain here.
22026     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22027
22028   return true;
22029 }
22030
22031 /// \brief Try to combine x86 target specific shuffles.
22032 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22033                                            TargetLowering::DAGCombinerInfo &DCI,
22034                                            const X86Subtarget *Subtarget) {
22035   SDLoc DL(N);
22036   MVT VT = N.getSimpleValueType();
22037   SmallVector<int, 4> Mask;
22038
22039   switch (N.getOpcode()) {
22040   case X86ISD::PSHUFD:
22041   case X86ISD::PSHUFLW:
22042   case X86ISD::PSHUFHW:
22043     Mask = getPSHUFShuffleMask(N);
22044     assert(Mask.size() == 4);
22045     break;
22046   default:
22047     return SDValue();
22048   }
22049
22050   // Nuke no-op shuffles that show up after combining.
22051   if (isNoopShuffleMask(Mask))
22052     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22053
22054   // Look for simplifications involving one or two shuffle instructions.
22055   SDValue V = N.getOperand(0);
22056   switch (N.getOpcode()) {
22057   default:
22058     break;
22059   case X86ISD::PSHUFLW:
22060   case X86ISD::PSHUFHW:
22061     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22062
22063     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22064       return SDValue(); // We combined away this shuffle, so we're done.
22065
22066     // See if this reduces to a PSHUFD which is no more expensive and can
22067     // combine with more operations. Note that it has to at least flip the
22068     // dwords as otherwise it would have been removed as a no-op.
22069     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22070       int DMask[] = {0, 1, 2, 3};
22071       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22072       DMask[DOffset + 0] = DOffset + 1;
22073       DMask[DOffset + 1] = DOffset + 0;
22074       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22075       V = DAG.getBitcast(DVT, V);
22076       DCI.AddToWorklist(V.getNode());
22077       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22078                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22079       DCI.AddToWorklist(V.getNode());
22080       return DAG.getBitcast(VT, V);
22081     }
22082
22083     // Look for shuffle patterns which can be implemented as a single unpack.
22084     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22085     // only works when we have a PSHUFD followed by two half-shuffles.
22086     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22087         (V.getOpcode() == X86ISD::PSHUFLW ||
22088          V.getOpcode() == X86ISD::PSHUFHW) &&
22089         V.getOpcode() != N.getOpcode() &&
22090         V.hasOneUse()) {
22091       SDValue D = V.getOperand(0);
22092       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22093         D = D.getOperand(0);
22094       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22095         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22096         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22097         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22098         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22099         int WordMask[8];
22100         for (int i = 0; i < 4; ++i) {
22101           WordMask[i + NOffset] = Mask[i] + NOffset;
22102           WordMask[i + VOffset] = VMask[i] + VOffset;
22103         }
22104         // Map the word mask through the DWord mask.
22105         int MappedMask[8];
22106         for (int i = 0; i < 8; ++i)
22107           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22108         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22109             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22110           // We can replace all three shuffles with an unpack.
22111           V = DAG.getBitcast(VT, D.getOperand(0));
22112           DCI.AddToWorklist(V.getNode());
22113           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22114                                                 : X86ISD::UNPCKH,
22115                              DL, VT, V, V);
22116         }
22117       }
22118     }
22119
22120     break;
22121
22122   case X86ISD::PSHUFD:
22123     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22124       return NewN;
22125
22126     break;
22127   }
22128
22129   return SDValue();
22130 }
22131
22132 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22133 ///
22134 /// We combine this directly on the abstract vector shuffle nodes so it is
22135 /// easier to generically match. We also insert dummy vector shuffle nodes for
22136 /// the operands which explicitly discard the lanes which are unused by this
22137 /// operation to try to flow through the rest of the combiner the fact that
22138 /// they're unused.
22139 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22140   SDLoc DL(N);
22141   EVT VT = N->getValueType(0);
22142
22143   // We only handle target-independent shuffles.
22144   // FIXME: It would be easy and harmless to use the target shuffle mask
22145   // extraction tool to support more.
22146   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22147     return SDValue();
22148
22149   auto *SVN = cast<ShuffleVectorSDNode>(N);
22150   ArrayRef<int> Mask = SVN->getMask();
22151   SDValue V1 = N->getOperand(0);
22152   SDValue V2 = N->getOperand(1);
22153
22154   // We require the first shuffle operand to be the SUB node, and the second to
22155   // be the ADD node.
22156   // FIXME: We should support the commuted patterns.
22157   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22158     return SDValue();
22159
22160   // If there are other uses of these operations we can't fold them.
22161   if (!V1->hasOneUse() || !V2->hasOneUse())
22162     return SDValue();
22163
22164   // Ensure that both operations have the same operands. Note that we can
22165   // commute the FADD operands.
22166   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22167   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22168       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22169     return SDValue();
22170
22171   // We're looking for blends between FADD and FSUB nodes. We insist on these
22172   // nodes being lined up in a specific expected pattern.
22173   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22174         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22175         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22176     return SDValue();
22177
22178   // Only specific types are legal at this point, assert so we notice if and
22179   // when these change.
22180   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22181           VT == MVT::v4f64) &&
22182          "Unknown vector type encountered!");
22183
22184   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22185 }
22186
22187 /// PerformShuffleCombine - Performs several different shuffle combines.
22188 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22189                                      TargetLowering::DAGCombinerInfo &DCI,
22190                                      const X86Subtarget *Subtarget) {
22191   SDLoc dl(N);
22192   SDValue N0 = N->getOperand(0);
22193   SDValue N1 = N->getOperand(1);
22194   EVT VT = N->getValueType(0);
22195
22196   // Don't create instructions with illegal types after legalize types has run.
22197   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22198   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22199     return SDValue();
22200
22201   // If we have legalized the vector types, look for blends of FADD and FSUB
22202   // nodes that we can fuse into an ADDSUB node.
22203   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22204     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22205       return AddSub;
22206
22207   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22208   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22209       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22210     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22211
22212   // During Type Legalization, when promoting illegal vector types,
22213   // the backend might introduce new shuffle dag nodes and bitcasts.
22214   //
22215   // This code performs the following transformation:
22216   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22217   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22218   //
22219   // We do this only if both the bitcast and the BINOP dag nodes have
22220   // one use. Also, perform this transformation only if the new binary
22221   // operation is legal. This is to avoid introducing dag nodes that
22222   // potentially need to be further expanded (or custom lowered) into a
22223   // less optimal sequence of dag nodes.
22224   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22225       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22226       N0.getOpcode() == ISD::BITCAST) {
22227     SDValue BC0 = N0.getOperand(0);
22228     EVT SVT = BC0.getValueType();
22229     unsigned Opcode = BC0.getOpcode();
22230     unsigned NumElts = VT.getVectorNumElements();
22231
22232     if (BC0.hasOneUse() && SVT.isVector() &&
22233         SVT.getVectorNumElements() * 2 == NumElts &&
22234         TLI.isOperationLegal(Opcode, VT)) {
22235       bool CanFold = false;
22236       switch (Opcode) {
22237       default : break;
22238       case ISD::ADD :
22239       case ISD::FADD :
22240       case ISD::SUB :
22241       case ISD::FSUB :
22242       case ISD::MUL :
22243       case ISD::FMUL :
22244         CanFold = true;
22245       }
22246
22247       unsigned SVTNumElts = SVT.getVectorNumElements();
22248       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22249       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22250         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22251       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22252         CanFold = SVOp->getMaskElt(i) < 0;
22253
22254       if (CanFold) {
22255         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22256         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22257         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22258         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22259       }
22260     }
22261   }
22262
22263   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22264   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22265   // consecutive, non-overlapping, and in the right order.
22266   SmallVector<SDValue, 16> Elts;
22267   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22268     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22269
22270   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22271     return LD;
22272
22273   if (isTargetShuffle(N->getOpcode())) {
22274     SDValue Shuffle =
22275         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22276     if (Shuffle.getNode())
22277       return Shuffle;
22278
22279     // Try recursively combining arbitrary sequences of x86 shuffle
22280     // instructions into higher-order shuffles. We do this after combining
22281     // specific PSHUF instruction sequences into their minimal form so that we
22282     // can evaluate how many specialized shuffle instructions are involved in
22283     // a particular chain.
22284     SmallVector<int, 1> NonceMask; // Just a placeholder.
22285     NonceMask.push_back(0);
22286     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22287                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22288                                       DCI, Subtarget))
22289       return SDValue(); // This routine will use CombineTo to replace N.
22290   }
22291
22292   return SDValue();
22293 }
22294
22295 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22296 /// specific shuffle of a load can be folded into a single element load.
22297 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22298 /// shuffles have been custom lowered so we need to handle those here.
22299 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22300                                          TargetLowering::DAGCombinerInfo &DCI) {
22301   if (DCI.isBeforeLegalizeOps())
22302     return SDValue();
22303
22304   SDValue InVec = N->getOperand(0);
22305   SDValue EltNo = N->getOperand(1);
22306
22307   if (!isa<ConstantSDNode>(EltNo))
22308     return SDValue();
22309
22310   EVT OriginalVT = InVec.getValueType();
22311
22312   if (InVec.getOpcode() == ISD::BITCAST) {
22313     // Don't duplicate a load with other uses.
22314     if (!InVec.hasOneUse())
22315       return SDValue();
22316     EVT BCVT = InVec.getOperand(0).getValueType();
22317     if (!BCVT.isVector() ||
22318         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22319       return SDValue();
22320     InVec = InVec.getOperand(0);
22321   }
22322
22323   EVT CurrentVT = InVec.getValueType();
22324
22325   if (!isTargetShuffle(InVec.getOpcode()))
22326     return SDValue();
22327
22328   // Don't duplicate a load with other uses.
22329   if (!InVec.hasOneUse())
22330     return SDValue();
22331
22332   SmallVector<int, 16> ShuffleMask;
22333   bool UnaryShuffle;
22334   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22335                             ShuffleMask, UnaryShuffle))
22336     return SDValue();
22337
22338   // Select the input vector, guarding against out of range extract vector.
22339   unsigned NumElems = CurrentVT.getVectorNumElements();
22340   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22341   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22342   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22343                                          : InVec.getOperand(1);
22344
22345   // If inputs to shuffle are the same for both ops, then allow 2 uses
22346   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22347                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22348
22349   if (LdNode.getOpcode() == ISD::BITCAST) {
22350     // Don't duplicate a load with other uses.
22351     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22352       return SDValue();
22353
22354     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22355     LdNode = LdNode.getOperand(0);
22356   }
22357
22358   if (!ISD::isNormalLoad(LdNode.getNode()))
22359     return SDValue();
22360
22361   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22362
22363   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22364     return SDValue();
22365
22366   EVT EltVT = N->getValueType(0);
22367   // If there's a bitcast before the shuffle, check if the load type and
22368   // alignment is valid.
22369   unsigned Align = LN0->getAlignment();
22370   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22371   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22372       EltVT.getTypeForEVT(*DAG.getContext()));
22373
22374   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22375     return SDValue();
22376
22377   // All checks match so transform back to vector_shuffle so that DAG combiner
22378   // can finish the job
22379   SDLoc dl(N);
22380
22381   // Create shuffle node taking into account the case that its a unary shuffle
22382   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22383                                    : InVec.getOperand(1);
22384   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22385                                  InVec.getOperand(0), Shuffle,
22386                                  &ShuffleMask[0]);
22387   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22388   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22389                      EltNo);
22390 }
22391
22392 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22393 /// special and don't usually play with other vector types, it's better to
22394 /// handle them early to be sure we emit efficient code by avoiding
22395 /// store-load conversions.
22396 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22397   if (N->getValueType(0) != MVT::x86mmx ||
22398       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22399       N->getOperand(0)->getValueType(0) != MVT::v2i32)
22400     return SDValue();
22401
22402   SDValue V = N->getOperand(0);
22403   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22404   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22405     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22406                        N->getValueType(0), V.getOperand(0));
22407
22408   return SDValue();
22409 }
22410
22411 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22412 /// generation and convert it from being a bunch of shuffles and extracts
22413 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22414 /// storing the value and loading scalars back, while for x64 we should
22415 /// use 64-bit extracts and shifts.
22416 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22417                                          TargetLowering::DAGCombinerInfo &DCI) {
22418   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22419     return NewOp;
22420
22421   SDValue InputVector = N->getOperand(0);
22422   SDLoc dl(InputVector);
22423   // Detect mmx to i32 conversion through a v2i32 elt extract.
22424   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22425       N->getValueType(0) == MVT::i32 &&
22426       InputVector.getValueType() == MVT::v2i32) {
22427
22428     // The bitcast source is a direct mmx result.
22429     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22430     if (MMXSrc.getValueType() == MVT::x86mmx)
22431       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22432                          N->getValueType(0),
22433                          InputVector.getNode()->getOperand(0));
22434
22435     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22436     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22437     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22438         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22439         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22440         MMXSrcOp.getValueType() == MVT::v1i64 &&
22441         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22442       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22443                          N->getValueType(0),
22444                          MMXSrcOp.getOperand(0));
22445   }
22446
22447   EVT VT = N->getValueType(0);
22448
22449   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22450       InputVector.getOpcode() == ISD::BITCAST &&
22451       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22452     uint64_t ExtractedElt =
22453           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22454     uint64_t InputValue =
22455           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22456     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22457     return DAG.getConstant(Res, dl, MVT::i1);
22458   }
22459   // Only operate on vectors of 4 elements, where the alternative shuffling
22460   // gets to be more expensive.
22461   if (InputVector.getValueType() != MVT::v4i32)
22462     return SDValue();
22463
22464   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22465   // single use which is a sign-extend or zero-extend, and all elements are
22466   // used.
22467   SmallVector<SDNode *, 4> Uses;
22468   unsigned ExtractedElements = 0;
22469   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22470        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22471     if (UI.getUse().getResNo() != InputVector.getResNo())
22472       return SDValue();
22473
22474     SDNode *Extract = *UI;
22475     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22476       return SDValue();
22477
22478     if (Extract->getValueType(0) != MVT::i32)
22479       return SDValue();
22480     if (!Extract->hasOneUse())
22481       return SDValue();
22482     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22483         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22484       return SDValue();
22485     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22486       return SDValue();
22487
22488     // Record which element was extracted.
22489     ExtractedElements |=
22490       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22491
22492     Uses.push_back(Extract);
22493   }
22494
22495   // If not all the elements were used, this may not be worthwhile.
22496   if (ExtractedElements != 15)
22497     return SDValue();
22498
22499   // Ok, we've now decided to do the transformation.
22500   // If 64-bit shifts are legal, use the extract-shift sequence,
22501   // otherwise bounce the vector off the cache.
22502   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22503   SDValue Vals[4];
22504
22505   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22506     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22507     auto &DL = DAG.getDataLayout();
22508     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22509     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22510       DAG.getConstant(0, dl, VecIdxTy));
22511     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22512       DAG.getConstant(1, dl, VecIdxTy));
22513
22514     SDValue ShAmt = DAG.getConstant(
22515         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22516     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22517     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22518       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22519     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22520     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22521       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22522   } else {
22523     // Store the value to a temporary stack slot.
22524     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22525     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22526       MachinePointerInfo(), false, false, 0);
22527
22528     EVT ElementType = InputVector.getValueType().getVectorElementType();
22529     unsigned EltSize = ElementType.getSizeInBits() / 8;
22530
22531     // Replace each use (extract) with a load of the appropriate element.
22532     for (unsigned i = 0; i < 4; ++i) {
22533       uint64_t Offset = EltSize * i;
22534       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22535       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22536
22537       SDValue ScalarAddr =
22538           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22539
22540       // Load the scalar.
22541       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22542                             ScalarAddr, MachinePointerInfo(),
22543                             false, false, false, 0);
22544
22545     }
22546   }
22547
22548   // Replace the extracts
22549   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22550     UE = Uses.end(); UI != UE; ++UI) {
22551     SDNode *Extract = *UI;
22552
22553     SDValue Idx = Extract->getOperand(1);
22554     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22555     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22556   }
22557
22558   // The replacement was made in place; don't return anything.
22559   return SDValue();
22560 }
22561
22562 static SDValue
22563 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22564                                       const X86Subtarget *Subtarget) {
22565   SDLoc dl(N);
22566   SDValue Cond = N->getOperand(0);
22567   SDValue LHS = N->getOperand(1);
22568   SDValue RHS = N->getOperand(2);
22569
22570   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22571     SDValue CondSrc = Cond->getOperand(0);
22572     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22573       Cond = CondSrc->getOperand(0);
22574   }
22575
22576   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22577     return SDValue();
22578
22579   // A vselect where all conditions and data are constants can be optimized into
22580   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22581   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22582       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22583     return SDValue();
22584
22585   unsigned MaskValue = 0;
22586   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22587     return SDValue();
22588
22589   MVT VT = N->getSimpleValueType(0);
22590   unsigned NumElems = VT.getVectorNumElements();
22591   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22592   for (unsigned i = 0; i < NumElems; ++i) {
22593     // Be sure we emit undef where we can.
22594     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22595       ShuffleMask[i] = -1;
22596     else
22597       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22598   }
22599
22600   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22601   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22602     return SDValue();
22603   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22604 }
22605
22606 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22607 /// nodes.
22608 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22609                                     TargetLowering::DAGCombinerInfo &DCI,
22610                                     const X86Subtarget *Subtarget) {
22611   SDLoc DL(N);
22612   SDValue Cond = N->getOperand(0);
22613   // Get the LHS/RHS of the select.
22614   SDValue LHS = N->getOperand(1);
22615   SDValue RHS = N->getOperand(2);
22616   EVT VT = LHS.getValueType();
22617   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22618
22619   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22620   // instructions match the semantics of the common C idiom x<y?x:y but not
22621   // x<=y?x:y, because of how they handle negative zero (which can be
22622   // ignored in unsafe-math mode).
22623   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22624   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22625       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22626       (Subtarget->hasSSE2() ||
22627        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22628     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22629
22630     unsigned Opcode = 0;
22631     // Check for x CC y ? x : y.
22632     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22633         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22634       switch (CC) {
22635       default: break;
22636       case ISD::SETULT:
22637         // Converting this to a min would handle NaNs incorrectly, and swapping
22638         // the operands would cause it to handle comparisons between positive
22639         // and negative zero incorrectly.
22640         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22641           if (!DAG.getTarget().Options.UnsafeFPMath &&
22642               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22643             break;
22644           std::swap(LHS, RHS);
22645         }
22646         Opcode = X86ISD::FMIN;
22647         break;
22648       case ISD::SETOLE:
22649         // Converting this to a min would handle comparisons between positive
22650         // and negative zero incorrectly.
22651         if (!DAG.getTarget().Options.UnsafeFPMath &&
22652             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22653           break;
22654         Opcode = X86ISD::FMIN;
22655         break;
22656       case ISD::SETULE:
22657         // Converting this to a min would handle both negative zeros and NaNs
22658         // incorrectly, but we can swap the operands to fix both.
22659         std::swap(LHS, RHS);
22660       case ISD::SETOLT:
22661       case ISD::SETLT:
22662       case ISD::SETLE:
22663         Opcode = X86ISD::FMIN;
22664         break;
22665
22666       case ISD::SETOGE:
22667         // Converting this to a max would handle comparisons between positive
22668         // and negative zero incorrectly.
22669         if (!DAG.getTarget().Options.UnsafeFPMath &&
22670             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22671           break;
22672         Opcode = X86ISD::FMAX;
22673         break;
22674       case ISD::SETUGT:
22675         // Converting this to a max would handle NaNs incorrectly, and swapping
22676         // the operands would cause it to handle comparisons between positive
22677         // and negative zero incorrectly.
22678         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22679           if (!DAG.getTarget().Options.UnsafeFPMath &&
22680               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22681             break;
22682           std::swap(LHS, RHS);
22683         }
22684         Opcode = X86ISD::FMAX;
22685         break;
22686       case ISD::SETUGE:
22687         // Converting this to a max would handle both negative zeros and NaNs
22688         // incorrectly, but we can swap the operands to fix both.
22689         std::swap(LHS, RHS);
22690       case ISD::SETOGT:
22691       case ISD::SETGT:
22692       case ISD::SETGE:
22693         Opcode = X86ISD::FMAX;
22694         break;
22695       }
22696     // Check for x CC y ? y : x -- a min/max with reversed arms.
22697     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22698                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22699       switch (CC) {
22700       default: break;
22701       case ISD::SETOGE:
22702         // Converting this to a min would handle comparisons between positive
22703         // and negative zero incorrectly, and swapping the operands would
22704         // cause it to handle NaNs incorrectly.
22705         if (!DAG.getTarget().Options.UnsafeFPMath &&
22706             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22707           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22708             break;
22709           std::swap(LHS, RHS);
22710         }
22711         Opcode = X86ISD::FMIN;
22712         break;
22713       case ISD::SETUGT:
22714         // Converting this to a min would handle NaNs incorrectly.
22715         if (!DAG.getTarget().Options.UnsafeFPMath &&
22716             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22717           break;
22718         Opcode = X86ISD::FMIN;
22719         break;
22720       case ISD::SETUGE:
22721         // Converting this to a min would handle both negative zeros and NaNs
22722         // incorrectly, but we can swap the operands to fix both.
22723         std::swap(LHS, RHS);
22724       case ISD::SETOGT:
22725       case ISD::SETGT:
22726       case ISD::SETGE:
22727         Opcode = X86ISD::FMIN;
22728         break;
22729
22730       case ISD::SETULT:
22731         // Converting this to a max would handle NaNs incorrectly.
22732         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22733           break;
22734         Opcode = X86ISD::FMAX;
22735         break;
22736       case ISD::SETOLE:
22737         // Converting this to a max would handle comparisons between positive
22738         // and negative zero incorrectly, and swapping the operands would
22739         // cause it to handle NaNs incorrectly.
22740         if (!DAG.getTarget().Options.UnsafeFPMath &&
22741             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22742           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22743             break;
22744           std::swap(LHS, RHS);
22745         }
22746         Opcode = X86ISD::FMAX;
22747         break;
22748       case ISD::SETULE:
22749         // Converting this to a max would handle both negative zeros and NaNs
22750         // incorrectly, but we can swap the operands to fix both.
22751         std::swap(LHS, RHS);
22752       case ISD::SETOLT:
22753       case ISD::SETLT:
22754       case ISD::SETLE:
22755         Opcode = X86ISD::FMAX;
22756         break;
22757       }
22758     }
22759
22760     if (Opcode)
22761       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22762   }
22763
22764   EVT CondVT = Cond.getValueType();
22765   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22766       CondVT.getVectorElementType() == MVT::i1) {
22767     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22768     // lowering on KNL. In this case we convert it to
22769     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22770     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22771     // Since SKX these selects have a proper lowering.
22772     EVT OpVT = LHS.getValueType();
22773     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22774         (OpVT.getVectorElementType() == MVT::i8 ||
22775          OpVT.getVectorElementType() == MVT::i16) &&
22776         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22777       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22778       DCI.AddToWorklist(Cond.getNode());
22779       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22780     }
22781   }
22782   // If this is a select between two integer constants, try to do some
22783   // optimizations.
22784   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22785     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22786       // Don't do this for crazy integer types.
22787       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22788         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22789         // so that TrueC (the true value) is larger than FalseC.
22790         bool NeedsCondInvert = false;
22791
22792         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22793             // Efficiently invertible.
22794             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22795              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22796               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22797           NeedsCondInvert = true;
22798           std::swap(TrueC, FalseC);
22799         }
22800
22801         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22802         if (FalseC->getAPIntValue() == 0 &&
22803             TrueC->getAPIntValue().isPowerOf2()) {
22804           if (NeedsCondInvert) // Invert the condition if needed.
22805             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22806                                DAG.getConstant(1, DL, Cond.getValueType()));
22807
22808           // Zero extend the condition if needed.
22809           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22810
22811           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22812           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22813                              DAG.getConstant(ShAmt, DL, MVT::i8));
22814         }
22815
22816         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22817         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22818           if (NeedsCondInvert) // Invert the condition if needed.
22819             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22820                                DAG.getConstant(1, DL, Cond.getValueType()));
22821
22822           // Zero extend the condition if needed.
22823           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22824                              FalseC->getValueType(0), Cond);
22825           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22826                              SDValue(FalseC, 0));
22827         }
22828
22829         // Optimize cases that will turn into an LEA instruction.  This requires
22830         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22831         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22832           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22833           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22834
22835           bool isFastMultiplier = false;
22836           if (Diff < 10) {
22837             switch ((unsigned char)Diff) {
22838               default: break;
22839               case 1:  // result = add base, cond
22840               case 2:  // result = lea base(    , cond*2)
22841               case 3:  // result = lea base(cond, cond*2)
22842               case 4:  // result = lea base(    , cond*4)
22843               case 5:  // result = lea base(cond, cond*4)
22844               case 8:  // result = lea base(    , cond*8)
22845               case 9:  // result = lea base(cond, cond*8)
22846                 isFastMultiplier = true;
22847                 break;
22848             }
22849           }
22850
22851           if (isFastMultiplier) {
22852             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22853             if (NeedsCondInvert) // Invert the condition if needed.
22854               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22855                                  DAG.getConstant(1, DL, Cond.getValueType()));
22856
22857             // Zero extend the condition if needed.
22858             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22859                                Cond);
22860             // Scale the condition by the difference.
22861             if (Diff != 1)
22862               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22863                                  DAG.getConstant(Diff, DL,
22864                                                  Cond.getValueType()));
22865
22866             // Add the base if non-zero.
22867             if (FalseC->getAPIntValue() != 0)
22868               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22869                                  SDValue(FalseC, 0));
22870             return Cond;
22871           }
22872         }
22873       }
22874   }
22875
22876   // Canonicalize max and min:
22877   // (x > y) ? x : y -> (x >= y) ? x : y
22878   // (x < y) ? x : y -> (x <= y) ? x : y
22879   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22880   // the need for an extra compare
22881   // against zero. e.g.
22882   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22883   // subl   %esi, %edi
22884   // testl  %edi, %edi
22885   // movl   $0, %eax
22886   // cmovgl %edi, %eax
22887   // =>
22888   // xorl   %eax, %eax
22889   // subl   %esi, $edi
22890   // cmovsl %eax, %edi
22891   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22892       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22893       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22894     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22895     switch (CC) {
22896     default: break;
22897     case ISD::SETLT:
22898     case ISD::SETGT: {
22899       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22900       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22901                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22902       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22903     }
22904     }
22905   }
22906
22907   // Early exit check
22908   if (!TLI.isTypeLegal(VT))
22909     return SDValue();
22910
22911   // Match VSELECTs into subs with unsigned saturation.
22912   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22913       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22914       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22915        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22916     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22917
22918     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22919     // left side invert the predicate to simplify logic below.
22920     SDValue Other;
22921     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22922       Other = RHS;
22923       CC = ISD::getSetCCInverse(CC, true);
22924     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22925       Other = LHS;
22926     }
22927
22928     if (Other.getNode() && Other->getNumOperands() == 2 &&
22929         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22930       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22931       SDValue CondRHS = Cond->getOperand(1);
22932
22933       // Look for a general sub with unsigned saturation first.
22934       // x >= y ? x-y : 0 --> subus x, y
22935       // x >  y ? x-y : 0 --> subus x, y
22936       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22937           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22938         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22939
22940       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22941         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22942           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22943             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22944               // If the RHS is a constant we have to reverse the const
22945               // canonicalization.
22946               // x > C-1 ? x+-C : 0 --> subus x, C
22947               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22948                   CondRHSConst->getAPIntValue() ==
22949                       (-OpRHSConst->getAPIntValue() - 1))
22950                 return DAG.getNode(
22951                     X86ISD::SUBUS, DL, VT, OpLHS,
22952                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22953
22954           // Another special case: If C was a sign bit, the sub has been
22955           // canonicalized into a xor.
22956           // FIXME: Would it be better to use computeKnownBits to determine
22957           //        whether it's safe to decanonicalize the xor?
22958           // x s< 0 ? x^C : 0 --> subus x, C
22959           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22960               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22961               OpRHSConst->getAPIntValue().isSignBit())
22962             // Note that we have to rebuild the RHS constant here to ensure we
22963             // don't rely on particular values of undef lanes.
22964             return DAG.getNode(
22965                 X86ISD::SUBUS, DL, VT, OpLHS,
22966                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22967         }
22968     }
22969   }
22970
22971   // Simplify vector selection if condition value type matches vselect
22972   // operand type
22973   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22974     assert(Cond.getValueType().isVector() &&
22975            "vector select expects a vector selector!");
22976
22977     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22978     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22979
22980     // Try invert the condition if true value is not all 1s and false value
22981     // is not all 0s.
22982     if (!TValIsAllOnes && !FValIsAllZeros &&
22983         // Check if the selector will be produced by CMPP*/PCMP*
22984         Cond.getOpcode() == ISD::SETCC &&
22985         // Check if SETCC has already been promoted
22986         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22987             CondVT) {
22988       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22989       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22990
22991       if (TValIsAllZeros || FValIsAllOnes) {
22992         SDValue CC = Cond.getOperand(2);
22993         ISD::CondCode NewCC =
22994           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22995                                Cond.getOperand(0).getValueType().isInteger());
22996         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22997         std::swap(LHS, RHS);
22998         TValIsAllOnes = FValIsAllOnes;
22999         FValIsAllZeros = TValIsAllZeros;
23000       }
23001     }
23002
23003     if (TValIsAllOnes || FValIsAllZeros) {
23004       SDValue Ret;
23005
23006       if (TValIsAllOnes && FValIsAllZeros)
23007         Ret = Cond;
23008       else if (TValIsAllOnes)
23009         Ret =
23010             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23011       else if (FValIsAllZeros)
23012         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23013                           DAG.getBitcast(CondVT, LHS));
23014
23015       return DAG.getBitcast(VT, Ret);
23016     }
23017   }
23018
23019   // We should generate an X86ISD::BLENDI from a vselect if its argument
23020   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23021   // constants. This specific pattern gets generated when we split a
23022   // selector for a 512 bit vector in a machine without AVX512 (but with
23023   // 256-bit vectors), during legalization:
23024   //
23025   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23026   //
23027   // Iff we find this pattern and the build_vectors are built from
23028   // constants, we translate the vselect into a shuffle_vector that we
23029   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23030   if ((N->getOpcode() == ISD::VSELECT ||
23031        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23032       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23033     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23034     if (Shuffle.getNode())
23035       return Shuffle;
23036   }
23037
23038   // If this is a *dynamic* select (non-constant condition) and we can match
23039   // this node with one of the variable blend instructions, restructure the
23040   // condition so that the blends can use the high bit of each element and use
23041   // SimplifyDemandedBits to simplify the condition operand.
23042   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23043       !DCI.isBeforeLegalize() &&
23044       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23045     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23046
23047     // Don't optimize vector selects that map to mask-registers.
23048     if (BitWidth == 1)
23049       return SDValue();
23050
23051     // We can only handle the cases where VSELECT is directly legal on the
23052     // subtarget. We custom lower VSELECT nodes with constant conditions and
23053     // this makes it hard to see whether a dynamic VSELECT will correctly
23054     // lower, so we both check the operation's status and explicitly handle the
23055     // cases where a *dynamic* blend will fail even though a constant-condition
23056     // blend could be custom lowered.
23057     // FIXME: We should find a better way to handle this class of problems.
23058     // Potentially, we should combine constant-condition vselect nodes
23059     // pre-legalization into shuffles and not mark as many types as custom
23060     // lowered.
23061     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23062       return SDValue();
23063     // FIXME: We don't support i16-element blends currently. We could and
23064     // should support them by making *all* the bits in the condition be set
23065     // rather than just the high bit and using an i8-element blend.
23066     if (VT.getScalarType() == MVT::i16)
23067       return SDValue();
23068     // Dynamic blending was only available from SSE4.1 onward.
23069     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23070       return SDValue();
23071     // Byte blends are only available in AVX2
23072     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23073         !Subtarget->hasAVX2())
23074       return SDValue();
23075
23076     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23077     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23078
23079     APInt KnownZero, KnownOne;
23080     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23081                                           DCI.isBeforeLegalizeOps());
23082     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23083         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23084                                  TLO)) {
23085       // If we changed the computation somewhere in the DAG, this change
23086       // will affect all users of Cond.
23087       // Make sure it is fine and update all the nodes so that we do not
23088       // use the generic VSELECT anymore. Otherwise, we may perform
23089       // wrong optimizations as we messed up with the actual expectation
23090       // for the vector boolean values.
23091       if (Cond != TLO.Old) {
23092         // Check all uses of that condition operand to check whether it will be
23093         // consumed by non-BLEND instructions, which may depend on all bits are
23094         // set properly.
23095         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23096              I != E; ++I)
23097           if (I->getOpcode() != ISD::VSELECT)
23098             // TODO: Add other opcodes eventually lowered into BLEND.
23099             return SDValue();
23100
23101         // Update all the users of the condition, before committing the change,
23102         // so that the VSELECT optimizations that expect the correct vector
23103         // boolean value will not be triggered.
23104         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23105              I != E; ++I)
23106           DAG.ReplaceAllUsesOfValueWith(
23107               SDValue(*I, 0),
23108               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23109                           Cond, I->getOperand(1), I->getOperand(2)));
23110         DCI.CommitTargetLoweringOpt(TLO);
23111         return SDValue();
23112       }
23113       // At this point, only Cond is changed. Change the condition
23114       // just for N to keep the opportunity to optimize all other
23115       // users their own way.
23116       DAG.ReplaceAllUsesOfValueWith(
23117           SDValue(N, 0),
23118           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23119                       TLO.New, N->getOperand(1), N->getOperand(2)));
23120       return SDValue();
23121     }
23122   }
23123
23124   return SDValue();
23125 }
23126
23127 // Check whether a boolean test is testing a boolean value generated by
23128 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23129 // code.
23130 //
23131 // Simplify the following patterns:
23132 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23133 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23134 // to (Op EFLAGS Cond)
23135 //
23136 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23137 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23138 // to (Op EFLAGS !Cond)
23139 //
23140 // where Op could be BRCOND or CMOV.
23141 //
23142 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23143   // Quit if not CMP and SUB with its value result used.
23144   if (Cmp.getOpcode() != X86ISD::CMP &&
23145       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23146       return SDValue();
23147
23148   // Quit if not used as a boolean value.
23149   if (CC != X86::COND_E && CC != X86::COND_NE)
23150     return SDValue();
23151
23152   // Check CMP operands. One of them should be 0 or 1 and the other should be
23153   // an SetCC or extended from it.
23154   SDValue Op1 = Cmp.getOperand(0);
23155   SDValue Op2 = Cmp.getOperand(1);
23156
23157   SDValue SetCC;
23158   const ConstantSDNode* C = nullptr;
23159   bool needOppositeCond = (CC == X86::COND_E);
23160   bool checkAgainstTrue = false; // Is it a comparison against 1?
23161
23162   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23163     SetCC = Op2;
23164   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23165     SetCC = Op1;
23166   else // Quit if all operands are not constants.
23167     return SDValue();
23168
23169   if (C->getZExtValue() == 1) {
23170     needOppositeCond = !needOppositeCond;
23171     checkAgainstTrue = true;
23172   } else if (C->getZExtValue() != 0)
23173     // Quit if the constant is neither 0 or 1.
23174     return SDValue();
23175
23176   bool truncatedToBoolWithAnd = false;
23177   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23178   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23179          SetCC.getOpcode() == ISD::TRUNCATE ||
23180          SetCC.getOpcode() == ISD::AND) {
23181     if (SetCC.getOpcode() == ISD::AND) {
23182       int OpIdx = -1;
23183       ConstantSDNode *CS;
23184       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23185           CS->getZExtValue() == 1)
23186         OpIdx = 1;
23187       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23188           CS->getZExtValue() == 1)
23189         OpIdx = 0;
23190       if (OpIdx == -1)
23191         break;
23192       SetCC = SetCC.getOperand(OpIdx);
23193       truncatedToBoolWithAnd = true;
23194     } else
23195       SetCC = SetCC.getOperand(0);
23196   }
23197
23198   switch (SetCC.getOpcode()) {
23199   case X86ISD::SETCC_CARRY:
23200     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23201     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23202     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23203     // truncated to i1 using 'and'.
23204     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23205       break;
23206     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23207            "Invalid use of SETCC_CARRY!");
23208     // FALL THROUGH
23209   case X86ISD::SETCC:
23210     // Set the condition code or opposite one if necessary.
23211     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23212     if (needOppositeCond)
23213       CC = X86::GetOppositeBranchCondition(CC);
23214     return SetCC.getOperand(1);
23215   case X86ISD::CMOV: {
23216     // Check whether false/true value has canonical one, i.e. 0 or 1.
23217     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23218     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23219     // Quit if true value is not a constant.
23220     if (!TVal)
23221       return SDValue();
23222     // Quit if false value is not a constant.
23223     if (!FVal) {
23224       SDValue Op = SetCC.getOperand(0);
23225       // Skip 'zext' or 'trunc' node.
23226       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23227           Op.getOpcode() == ISD::TRUNCATE)
23228         Op = Op.getOperand(0);
23229       // A special case for rdrand/rdseed, where 0 is set if false cond is
23230       // found.
23231       if ((Op.getOpcode() != X86ISD::RDRAND &&
23232            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23233         return SDValue();
23234     }
23235     // Quit if false value is not the constant 0 or 1.
23236     bool FValIsFalse = true;
23237     if (FVal && FVal->getZExtValue() != 0) {
23238       if (FVal->getZExtValue() != 1)
23239         return SDValue();
23240       // If FVal is 1, opposite cond is needed.
23241       needOppositeCond = !needOppositeCond;
23242       FValIsFalse = false;
23243     }
23244     // Quit if TVal is not the constant opposite of FVal.
23245     if (FValIsFalse && TVal->getZExtValue() != 1)
23246       return SDValue();
23247     if (!FValIsFalse && TVal->getZExtValue() != 0)
23248       return SDValue();
23249     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23250     if (needOppositeCond)
23251       CC = X86::GetOppositeBranchCondition(CC);
23252     return SetCC.getOperand(3);
23253   }
23254   }
23255
23256   return SDValue();
23257 }
23258
23259 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23260 /// Match:
23261 ///   (X86or (X86setcc) (X86setcc))
23262 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
23263 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23264                                            X86::CondCode &CC1, SDValue &Flags,
23265                                            bool &isAnd) {
23266   if (Cond->getOpcode() == X86ISD::CMP) {
23267     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23268     if (!CondOp1C || !CondOp1C->isNullValue())
23269       return false;
23270
23271     Cond = Cond->getOperand(0);
23272   }
23273
23274   isAnd = false;
23275
23276   SDValue SetCC0, SetCC1;
23277   switch (Cond->getOpcode()) {
23278   default: return false;
23279   case ISD::AND:
23280   case X86ISD::AND:
23281     isAnd = true;
23282     // fallthru
23283   case ISD::OR:
23284   case X86ISD::OR:
23285     SetCC0 = Cond->getOperand(0);
23286     SetCC1 = Cond->getOperand(1);
23287     break;
23288   };
23289
23290   // Make sure we have SETCC nodes, using the same flags value.
23291   if (SetCC0.getOpcode() != X86ISD::SETCC ||
23292       SetCC1.getOpcode() != X86ISD::SETCC ||
23293       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23294     return false;
23295
23296   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23297   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23298   Flags = SetCC0->getOperand(1);
23299   return true;
23300 }
23301
23302 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23303 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23304                                   TargetLowering::DAGCombinerInfo &DCI,
23305                                   const X86Subtarget *Subtarget) {
23306   SDLoc DL(N);
23307
23308   // If the flag operand isn't dead, don't touch this CMOV.
23309   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23310     return SDValue();
23311
23312   SDValue FalseOp = N->getOperand(0);
23313   SDValue TrueOp = N->getOperand(1);
23314   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23315   SDValue Cond = N->getOperand(3);
23316
23317   if (CC == X86::COND_E || CC == X86::COND_NE) {
23318     switch (Cond.getOpcode()) {
23319     default: break;
23320     case X86ISD::BSR:
23321     case X86ISD::BSF:
23322       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23323       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23324         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23325     }
23326   }
23327
23328   SDValue Flags;
23329
23330   Flags = checkBoolTestSetCCCombine(Cond, CC);
23331   if (Flags.getNode() &&
23332       // Extra check as FCMOV only supports a subset of X86 cond.
23333       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23334     SDValue Ops[] = { FalseOp, TrueOp,
23335                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23336     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23337   }
23338
23339   // If this is a select between two integer constants, try to do some
23340   // optimizations.  Note that the operands are ordered the opposite of SELECT
23341   // operands.
23342   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23343     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23344       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23345       // larger than FalseC (the false value).
23346       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23347         CC = X86::GetOppositeBranchCondition(CC);
23348         std::swap(TrueC, FalseC);
23349         std::swap(TrueOp, FalseOp);
23350       }
23351
23352       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23353       // This is efficient for any integer data type (including i8/i16) and
23354       // shift amount.
23355       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23356         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23357                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23358
23359         // Zero extend the condition if needed.
23360         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23361
23362         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23363         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23364                            DAG.getConstant(ShAmt, DL, MVT::i8));
23365         if (N->getNumValues() == 2)  // Dead flag value?
23366           return DCI.CombineTo(N, Cond, SDValue());
23367         return Cond;
23368       }
23369
23370       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23371       // for any integer data type, including i8/i16.
23372       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23373         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23374                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23375
23376         // Zero extend the condition if needed.
23377         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23378                            FalseC->getValueType(0), Cond);
23379         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23380                            SDValue(FalseC, 0));
23381
23382         if (N->getNumValues() == 2)  // Dead flag value?
23383           return DCI.CombineTo(N, Cond, SDValue());
23384         return Cond;
23385       }
23386
23387       // Optimize cases that will turn into an LEA instruction.  This requires
23388       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23389       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23390         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23391         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23392
23393         bool isFastMultiplier = false;
23394         if (Diff < 10) {
23395           switch ((unsigned char)Diff) {
23396           default: break;
23397           case 1:  // result = add base, cond
23398           case 2:  // result = lea base(    , cond*2)
23399           case 3:  // result = lea base(cond, cond*2)
23400           case 4:  // result = lea base(    , cond*4)
23401           case 5:  // result = lea base(cond, cond*4)
23402           case 8:  // result = lea base(    , cond*8)
23403           case 9:  // result = lea base(cond, cond*8)
23404             isFastMultiplier = true;
23405             break;
23406           }
23407         }
23408
23409         if (isFastMultiplier) {
23410           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23411           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23412                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23413           // Zero extend the condition if needed.
23414           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23415                              Cond);
23416           // Scale the condition by the difference.
23417           if (Diff != 1)
23418             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23419                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23420
23421           // Add the base if non-zero.
23422           if (FalseC->getAPIntValue() != 0)
23423             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23424                                SDValue(FalseC, 0));
23425           if (N->getNumValues() == 2)  // Dead flag value?
23426             return DCI.CombineTo(N, Cond, SDValue());
23427           return Cond;
23428         }
23429       }
23430     }
23431   }
23432
23433   // Handle these cases:
23434   //   (select (x != c), e, c) -> select (x != c), e, x),
23435   //   (select (x == c), c, e) -> select (x == c), x, e)
23436   // where the c is an integer constant, and the "select" is the combination
23437   // of CMOV and CMP.
23438   //
23439   // The rationale for this change is that the conditional-move from a constant
23440   // needs two instructions, however, conditional-move from a register needs
23441   // only one instruction.
23442   //
23443   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23444   //  some instruction-combining opportunities. This opt needs to be
23445   //  postponed as late as possible.
23446   //
23447   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23448     // the DCI.xxxx conditions are provided to postpone the optimization as
23449     // late as possible.
23450
23451     ConstantSDNode *CmpAgainst = nullptr;
23452     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23453         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23454         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23455
23456       if (CC == X86::COND_NE &&
23457           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23458         CC = X86::GetOppositeBranchCondition(CC);
23459         std::swap(TrueOp, FalseOp);
23460       }
23461
23462       if (CC == X86::COND_E &&
23463           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23464         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23465                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23466         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23467       }
23468     }
23469   }
23470
23471   // Fold and/or of setcc's to double CMOV:
23472   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23473   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23474   //
23475   // This combine lets us generate:
23476   //   cmovcc1 (jcc1 if we don't have CMOV)
23477   //   cmovcc2 (same)
23478   // instead of:
23479   //   setcc1
23480   //   setcc2
23481   //   and/or
23482   //   cmovne (jne if we don't have CMOV)
23483   // When we can't use the CMOV instruction, it might increase branch
23484   // mispredicts.
23485   // When we can use CMOV, or when there is no mispredict, this improves
23486   // throughput and reduces register pressure.
23487   //
23488   if (CC == X86::COND_NE) {
23489     SDValue Flags;
23490     X86::CondCode CC0, CC1;
23491     bool isAndSetCC;
23492     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23493       if (isAndSetCC) {
23494         std::swap(FalseOp, TrueOp);
23495         CC0 = X86::GetOppositeBranchCondition(CC0);
23496         CC1 = X86::GetOppositeBranchCondition(CC1);
23497       }
23498
23499       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23500         Flags};
23501       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23502       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23503       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23504       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23505       return CMOV;
23506     }
23507   }
23508
23509   return SDValue();
23510 }
23511
23512 /// PerformMulCombine - Optimize a single multiply with constant into two
23513 /// in order to implement it with two cheaper instructions, e.g.
23514 /// LEA + SHL, LEA + LEA.
23515 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23516                                  TargetLowering::DAGCombinerInfo &DCI) {
23517   // An imul is usually smaller than the alternative sequence.
23518   if (DAG.getMachineFunction().getFunction()->optForMinSize())
23519     return SDValue();
23520
23521   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23522     return SDValue();
23523
23524   EVT VT = N->getValueType(0);
23525   if (VT != MVT::i64 && VT != MVT::i32)
23526     return SDValue();
23527
23528   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23529   if (!C)
23530     return SDValue();
23531   uint64_t MulAmt = C->getZExtValue();
23532   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23533     return SDValue();
23534
23535   uint64_t MulAmt1 = 0;
23536   uint64_t MulAmt2 = 0;
23537   if ((MulAmt % 9) == 0) {
23538     MulAmt1 = 9;
23539     MulAmt2 = MulAmt / 9;
23540   } else if ((MulAmt % 5) == 0) {
23541     MulAmt1 = 5;
23542     MulAmt2 = MulAmt / 5;
23543   } else if ((MulAmt % 3) == 0) {
23544     MulAmt1 = 3;
23545     MulAmt2 = MulAmt / 3;
23546   }
23547   if (MulAmt2 &&
23548       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23549     SDLoc DL(N);
23550
23551     if (isPowerOf2_64(MulAmt2) &&
23552         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23553       // If second multiplifer is pow2, issue it first. We want the multiply by
23554       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23555       // is an add.
23556       std::swap(MulAmt1, MulAmt2);
23557
23558     SDValue NewMul;
23559     if (isPowerOf2_64(MulAmt1))
23560       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23561                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23562     else
23563       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23564                            DAG.getConstant(MulAmt1, DL, VT));
23565
23566     if (isPowerOf2_64(MulAmt2))
23567       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23568                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23569     else
23570       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23571                            DAG.getConstant(MulAmt2, DL, VT));
23572
23573     // Do not add new nodes to DAG combiner worklist.
23574     DCI.CombineTo(N, NewMul, false);
23575   }
23576   return SDValue();
23577 }
23578
23579 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23580   SDValue N0 = N->getOperand(0);
23581   SDValue N1 = N->getOperand(1);
23582   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23583   EVT VT = N0.getValueType();
23584
23585   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23586   // since the result of setcc_c is all zero's or all ones.
23587   if (VT.isInteger() && !VT.isVector() &&
23588       N1C && N0.getOpcode() == ISD::AND &&
23589       N0.getOperand(1).getOpcode() == ISD::Constant) {
23590     SDValue N00 = N0.getOperand(0);
23591     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23592     APInt ShAmt = N1C->getAPIntValue();
23593     Mask = Mask.shl(ShAmt);
23594     bool MaskOK = false;
23595     // We can handle cases concerning bit-widening nodes containing setcc_c if
23596     // we carefully interrogate the mask to make sure we are semantics
23597     // preserving.
23598     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
23599     // of the underlying setcc_c operation if the setcc_c was zero extended.
23600     // Consider the following example:
23601     //   zext(setcc_c)                 -> i32 0x0000FFFF
23602     //   c1                            -> i32 0x0000FFFF
23603     //   c2                            -> i32 0x00000001
23604     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
23605     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
23606     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23607       MaskOK = true;
23608     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
23609                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23610       MaskOK = true;
23611     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
23612                 N00.getOpcode() == ISD::ANY_EXTEND) &&
23613                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23614       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
23615     }
23616     if (MaskOK && Mask != 0) {
23617       SDLoc DL(N);
23618       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
23619     }
23620   }
23621
23622   // Hardware support for vector shifts is sparse which makes us scalarize the
23623   // vector operations in many cases. Also, on sandybridge ADD is faster than
23624   // shl.
23625   // (shl V, 1) -> add V,V
23626   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23627     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23628       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23629       // We shift all of the values by one. In many cases we do not have
23630       // hardware support for this operation. This is better expressed as an ADD
23631       // of two values.
23632       if (N1SplatC->getAPIntValue() == 1)
23633         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23634     }
23635
23636   return SDValue();
23637 }
23638
23639 /// \brief Returns a vector of 0s if the node in input is a vector logical
23640 /// shift by a constant amount which is known to be bigger than or equal
23641 /// to the vector element size in bits.
23642 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23643                                       const X86Subtarget *Subtarget) {
23644   EVT VT = N->getValueType(0);
23645
23646   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23647       (!Subtarget->hasInt256() ||
23648        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23649     return SDValue();
23650
23651   SDValue Amt = N->getOperand(1);
23652   SDLoc DL(N);
23653   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23654     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23655       APInt ShiftAmt = AmtSplat->getAPIntValue();
23656       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23657
23658       // SSE2/AVX2 logical shifts always return a vector of 0s
23659       // if the shift amount is bigger than or equal to
23660       // the element size. The constant shift amount will be
23661       // encoded as a 8-bit immediate.
23662       if (ShiftAmt.trunc(8).uge(MaxAmount))
23663         return getZeroVector(VT, Subtarget, DAG, DL);
23664     }
23665
23666   return SDValue();
23667 }
23668
23669 /// PerformShiftCombine - Combine shifts.
23670 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23671                                    TargetLowering::DAGCombinerInfo &DCI,
23672                                    const X86Subtarget *Subtarget) {
23673   if (N->getOpcode() == ISD::SHL)
23674     if (SDValue V = PerformSHLCombine(N, DAG))
23675       return V;
23676
23677   // Try to fold this logical shift into a zero vector.
23678   if (N->getOpcode() != ISD::SRA)
23679     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23680       return V;
23681
23682   return SDValue();
23683 }
23684
23685 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23686 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23687 // and friends.  Likewise for OR -> CMPNEQSS.
23688 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23689                             TargetLowering::DAGCombinerInfo &DCI,
23690                             const X86Subtarget *Subtarget) {
23691   unsigned opcode;
23692
23693   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23694   // we're requiring SSE2 for both.
23695   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23696     SDValue N0 = N->getOperand(0);
23697     SDValue N1 = N->getOperand(1);
23698     SDValue CMP0 = N0->getOperand(1);
23699     SDValue CMP1 = N1->getOperand(1);
23700     SDLoc DL(N);
23701
23702     // The SETCCs should both refer to the same CMP.
23703     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23704       return SDValue();
23705
23706     SDValue CMP00 = CMP0->getOperand(0);
23707     SDValue CMP01 = CMP0->getOperand(1);
23708     EVT     VT    = CMP00.getValueType();
23709
23710     if (VT == MVT::f32 || VT == MVT::f64) {
23711       bool ExpectingFlags = false;
23712       // Check for any users that want flags:
23713       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23714            !ExpectingFlags && UI != UE; ++UI)
23715         switch (UI->getOpcode()) {
23716         default:
23717         case ISD::BR_CC:
23718         case ISD::BRCOND:
23719         case ISD::SELECT:
23720           ExpectingFlags = true;
23721           break;
23722         case ISD::CopyToReg:
23723         case ISD::SIGN_EXTEND:
23724         case ISD::ZERO_EXTEND:
23725         case ISD::ANY_EXTEND:
23726           break;
23727         }
23728
23729       if (!ExpectingFlags) {
23730         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23731         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23732
23733         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23734           X86::CondCode tmp = cc0;
23735           cc0 = cc1;
23736           cc1 = tmp;
23737         }
23738
23739         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23740             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23741           // FIXME: need symbolic constants for these magic numbers.
23742           // See X86ATTInstPrinter.cpp:printSSECC().
23743           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23744           if (Subtarget->hasAVX512()) {
23745             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23746                                          CMP01,
23747                                          DAG.getConstant(x86cc, DL, MVT::i8));
23748             if (N->getValueType(0) != MVT::i1)
23749               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23750                                  FSetCC);
23751             return FSetCC;
23752           }
23753           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23754                                               CMP00.getValueType(), CMP00, CMP01,
23755                                               DAG.getConstant(x86cc, DL,
23756                                                               MVT::i8));
23757
23758           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23759           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23760
23761           if (is64BitFP && !Subtarget->is64Bit()) {
23762             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23763             // 64-bit integer, since that's not a legal type. Since
23764             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23765             // bits, but can do this little dance to extract the lowest 32 bits
23766             // and work with those going forward.
23767             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23768                                            OnesOrZeroesF);
23769             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23770             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23771                                         Vector32, DAG.getIntPtrConstant(0, DL));
23772             IntVT = MVT::i32;
23773           }
23774
23775           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23776           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23777                                       DAG.getConstant(1, DL, IntVT));
23778           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23779                                               ANDed);
23780           return OneBitOfTruth;
23781         }
23782       }
23783     }
23784   }
23785   return SDValue();
23786 }
23787
23788 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23789 /// so it can be folded inside ANDNP.
23790 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23791   EVT VT = N->getValueType(0);
23792
23793   // Match direct AllOnes for 128 and 256-bit vectors
23794   if (ISD::isBuildVectorAllOnes(N))
23795     return true;
23796
23797   // Look through a bit convert.
23798   if (N->getOpcode() == ISD::BITCAST)
23799     N = N->getOperand(0).getNode();
23800
23801   // Sometimes the operand may come from a insert_subvector building a 256-bit
23802   // allones vector
23803   if (VT.is256BitVector() &&
23804       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23805     SDValue V1 = N->getOperand(0);
23806     SDValue V2 = N->getOperand(1);
23807
23808     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23809         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23810         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23811         ISD::isBuildVectorAllOnes(V2.getNode()))
23812       return true;
23813   }
23814
23815   return false;
23816 }
23817
23818 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23819 // register. In most cases we actually compare or select YMM-sized registers
23820 // and mixing the two types creates horrible code. This method optimizes
23821 // some of the transition sequences.
23822 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23823                                  TargetLowering::DAGCombinerInfo &DCI,
23824                                  const X86Subtarget *Subtarget) {
23825   EVT VT = N->getValueType(0);
23826   if (!VT.is256BitVector())
23827     return SDValue();
23828
23829   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23830           N->getOpcode() == ISD::ZERO_EXTEND ||
23831           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23832
23833   SDValue Narrow = N->getOperand(0);
23834   EVT NarrowVT = Narrow->getValueType(0);
23835   if (!NarrowVT.is128BitVector())
23836     return SDValue();
23837
23838   if (Narrow->getOpcode() != ISD::XOR &&
23839       Narrow->getOpcode() != ISD::AND &&
23840       Narrow->getOpcode() != ISD::OR)
23841     return SDValue();
23842
23843   SDValue N0  = Narrow->getOperand(0);
23844   SDValue N1  = Narrow->getOperand(1);
23845   SDLoc DL(Narrow);
23846
23847   // The Left side has to be a trunc.
23848   if (N0.getOpcode() != ISD::TRUNCATE)
23849     return SDValue();
23850
23851   // The type of the truncated inputs.
23852   EVT WideVT = N0->getOperand(0)->getValueType(0);
23853   if (WideVT != VT)
23854     return SDValue();
23855
23856   // The right side has to be a 'trunc' or a constant vector.
23857   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23858   ConstantSDNode *RHSConstSplat = nullptr;
23859   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23860     RHSConstSplat = RHSBV->getConstantSplatNode();
23861   if (!RHSTrunc && !RHSConstSplat)
23862     return SDValue();
23863
23864   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23865
23866   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23867     return SDValue();
23868
23869   // Set N0 and N1 to hold the inputs to the new wide operation.
23870   N0 = N0->getOperand(0);
23871   if (RHSConstSplat) {
23872     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23873                      SDValue(RHSConstSplat, 0));
23874     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23875     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23876   } else if (RHSTrunc) {
23877     N1 = N1->getOperand(0);
23878   }
23879
23880   // Generate the wide operation.
23881   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23882   unsigned Opcode = N->getOpcode();
23883   switch (Opcode) {
23884   case ISD::ANY_EXTEND:
23885     return Op;
23886   case ISD::ZERO_EXTEND: {
23887     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23888     APInt Mask = APInt::getAllOnesValue(InBits);
23889     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23890     return DAG.getNode(ISD::AND, DL, VT,
23891                        Op, DAG.getConstant(Mask, DL, VT));
23892   }
23893   case ISD::SIGN_EXTEND:
23894     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23895                        Op, DAG.getValueType(NarrowVT));
23896   default:
23897     llvm_unreachable("Unexpected opcode");
23898   }
23899 }
23900
23901 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23902                                  TargetLowering::DAGCombinerInfo &DCI,
23903                                  const X86Subtarget *Subtarget) {
23904   SDValue N0 = N->getOperand(0);
23905   SDValue N1 = N->getOperand(1);
23906   SDLoc DL(N);
23907
23908   // A vector zext_in_reg may be represented as a shuffle,
23909   // feeding into a bitcast (this represents anyext) feeding into
23910   // an and with a mask.
23911   // We'd like to try to combine that into a shuffle with zero
23912   // plus a bitcast, removing the and.
23913   if (N0.getOpcode() != ISD::BITCAST ||
23914       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23915     return SDValue();
23916
23917   // The other side of the AND should be a splat of 2^C, where C
23918   // is the number of bits in the source type.
23919   if (N1.getOpcode() == ISD::BITCAST)
23920     N1 = N1.getOperand(0);
23921   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23922     return SDValue();
23923   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23924
23925   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23926   EVT SrcType = Shuffle->getValueType(0);
23927
23928   // We expect a single-source shuffle
23929   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23930     return SDValue();
23931
23932   unsigned SrcSize = SrcType.getScalarSizeInBits();
23933
23934   APInt SplatValue, SplatUndef;
23935   unsigned SplatBitSize;
23936   bool HasAnyUndefs;
23937   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23938                                 SplatBitSize, HasAnyUndefs))
23939     return SDValue();
23940
23941   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23942   // Make sure the splat matches the mask we expect
23943   if (SplatBitSize > ResSize ||
23944       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23945     return SDValue();
23946
23947   // Make sure the input and output size make sense
23948   if (SrcSize >= ResSize || ResSize % SrcSize)
23949     return SDValue();
23950
23951   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23952   // The number of u's between each two values depends on the ratio between
23953   // the source and dest type.
23954   unsigned ZextRatio = ResSize / SrcSize;
23955   bool IsZext = true;
23956   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23957     if (i % ZextRatio) {
23958       if (Shuffle->getMaskElt(i) > 0) {
23959         // Expected undef
23960         IsZext = false;
23961         break;
23962       }
23963     } else {
23964       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23965         // Expected element number
23966         IsZext = false;
23967         break;
23968       }
23969     }
23970   }
23971
23972   if (!IsZext)
23973     return SDValue();
23974
23975   // Ok, perform the transformation - replace the shuffle with
23976   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23977   // (instead of undef) where the k elements come from the zero vector.
23978   SmallVector<int, 8> Mask;
23979   unsigned NumElems = SrcType.getVectorNumElements();
23980   for (unsigned i = 0; i < NumElems; ++i)
23981     if (i % ZextRatio)
23982       Mask.push_back(NumElems);
23983     else
23984       Mask.push_back(i / ZextRatio);
23985
23986   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23987     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23988   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23989 }
23990
23991 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23992                                  TargetLowering::DAGCombinerInfo &DCI,
23993                                  const X86Subtarget *Subtarget) {
23994   if (DCI.isBeforeLegalizeOps())
23995     return SDValue();
23996
23997   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23998     return Zext;
23999
24000   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24001     return R;
24002
24003   EVT VT = N->getValueType(0);
24004   SDValue N0 = N->getOperand(0);
24005   SDValue N1 = N->getOperand(1);
24006   SDLoc DL(N);
24007
24008   // Create BEXTR instructions
24009   // BEXTR is ((X >> imm) & (2**size-1))
24010   if (VT == MVT::i32 || VT == MVT::i64) {
24011     // Check for BEXTR.
24012     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24013         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24014       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24015       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24016       if (MaskNode && ShiftNode) {
24017         uint64_t Mask = MaskNode->getZExtValue();
24018         uint64_t Shift = ShiftNode->getZExtValue();
24019         if (isMask_64(Mask)) {
24020           uint64_t MaskSize = countPopulation(Mask);
24021           if (Shift + MaskSize <= VT.getSizeInBits())
24022             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24023                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24024                                                VT));
24025         }
24026       }
24027     } // BEXTR
24028
24029     return SDValue();
24030   }
24031
24032   // Want to form ANDNP nodes:
24033   // 1) In the hopes of then easily combining them with OR and AND nodes
24034   //    to form PBLEND/PSIGN.
24035   // 2) To match ANDN packed intrinsics
24036   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24037     return SDValue();
24038
24039   // Check LHS for vnot
24040   if (N0.getOpcode() == ISD::XOR &&
24041       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24042       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24043     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24044
24045   // Check RHS for vnot
24046   if (N1.getOpcode() == ISD::XOR &&
24047       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24048       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24049     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24050
24051   return SDValue();
24052 }
24053
24054 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24055                                 TargetLowering::DAGCombinerInfo &DCI,
24056                                 const X86Subtarget *Subtarget) {
24057   if (DCI.isBeforeLegalizeOps())
24058     return SDValue();
24059
24060   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24061     return R;
24062
24063   SDValue N0 = N->getOperand(0);
24064   SDValue N1 = N->getOperand(1);
24065   EVT VT = N->getValueType(0);
24066
24067   // look for psign/blend
24068   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24069     if (!Subtarget->hasSSSE3() ||
24070         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24071       return SDValue();
24072
24073     // Canonicalize pandn to RHS
24074     if (N0.getOpcode() == X86ISD::ANDNP)
24075       std::swap(N0, N1);
24076     // or (and (m, y), (pandn m, x))
24077     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24078       SDValue Mask = N1.getOperand(0);
24079       SDValue X    = N1.getOperand(1);
24080       SDValue Y;
24081       if (N0.getOperand(0) == Mask)
24082         Y = N0.getOperand(1);
24083       if (N0.getOperand(1) == Mask)
24084         Y = N0.getOperand(0);
24085
24086       // Check to see if the mask appeared in both the AND and ANDNP and
24087       if (!Y.getNode())
24088         return SDValue();
24089
24090       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24091       // Look through mask bitcast.
24092       if (Mask.getOpcode() == ISD::BITCAST)
24093         Mask = Mask.getOperand(0);
24094       if (X.getOpcode() == ISD::BITCAST)
24095         X = X.getOperand(0);
24096       if (Y.getOpcode() == ISD::BITCAST)
24097         Y = Y.getOperand(0);
24098
24099       EVT MaskVT = Mask.getValueType();
24100
24101       // Validate that the Mask operand is a vector sra node.
24102       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24103       // there is no psrai.b
24104       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24105       unsigned SraAmt = ~0;
24106       if (Mask.getOpcode() == ISD::SRA) {
24107         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24108           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24109             SraAmt = AmtConst->getZExtValue();
24110       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24111         SDValue SraC = Mask.getOperand(1);
24112         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24113       }
24114       if ((SraAmt + 1) != EltBits)
24115         return SDValue();
24116
24117       SDLoc DL(N);
24118
24119       // Now we know we at least have a plendvb with the mask val.  See if
24120       // we can form a psignb/w/d.
24121       // psign = x.type == y.type == mask.type && y = sub(0, x);
24122       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24123           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24124           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24125         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24126                "Unsupported VT for PSIGN");
24127         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24128         return DAG.getBitcast(VT, Mask);
24129       }
24130       // PBLENDVB only available on SSE 4.1
24131       if (!Subtarget->hasSSE41())
24132         return SDValue();
24133
24134       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24135
24136       X = DAG.getBitcast(BlendVT, X);
24137       Y = DAG.getBitcast(BlendVT, Y);
24138       Mask = DAG.getBitcast(BlendVT, Mask);
24139       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24140       return DAG.getBitcast(VT, Mask);
24141     }
24142   }
24143
24144   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24145     return SDValue();
24146
24147   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24148   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24149
24150   // SHLD/SHRD instructions have lower register pressure, but on some
24151   // platforms they have higher latency than the equivalent
24152   // series of shifts/or that would otherwise be generated.
24153   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24154   // have higher latencies and we are not optimizing for size.
24155   if (!OptForSize && Subtarget->isSHLDSlow())
24156     return SDValue();
24157
24158   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24159     std::swap(N0, N1);
24160   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24161     return SDValue();
24162   if (!N0.hasOneUse() || !N1.hasOneUse())
24163     return SDValue();
24164
24165   SDValue ShAmt0 = N0.getOperand(1);
24166   if (ShAmt0.getValueType() != MVT::i8)
24167     return SDValue();
24168   SDValue ShAmt1 = N1.getOperand(1);
24169   if (ShAmt1.getValueType() != MVT::i8)
24170     return SDValue();
24171   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24172     ShAmt0 = ShAmt0.getOperand(0);
24173   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24174     ShAmt1 = ShAmt1.getOperand(0);
24175
24176   SDLoc DL(N);
24177   unsigned Opc = X86ISD::SHLD;
24178   SDValue Op0 = N0.getOperand(0);
24179   SDValue Op1 = N1.getOperand(0);
24180   if (ShAmt0.getOpcode() == ISD::SUB) {
24181     Opc = X86ISD::SHRD;
24182     std::swap(Op0, Op1);
24183     std::swap(ShAmt0, ShAmt1);
24184   }
24185
24186   unsigned Bits = VT.getSizeInBits();
24187   if (ShAmt1.getOpcode() == ISD::SUB) {
24188     SDValue Sum = ShAmt1.getOperand(0);
24189     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24190       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24191       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24192         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24193       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24194         return DAG.getNode(Opc, DL, VT,
24195                            Op0, Op1,
24196                            DAG.getNode(ISD::TRUNCATE, DL,
24197                                        MVT::i8, ShAmt0));
24198     }
24199   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24200     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24201     if (ShAmt0C &&
24202         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24203       return DAG.getNode(Opc, DL, VT,
24204                          N0.getOperand(0), N1.getOperand(0),
24205                          DAG.getNode(ISD::TRUNCATE, DL,
24206                                        MVT::i8, ShAmt0));
24207   }
24208
24209   return SDValue();
24210 }
24211
24212 // Generate NEG and CMOV for integer abs.
24213 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24214   EVT VT = N->getValueType(0);
24215
24216   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24217   // 8-bit integer abs to NEG and CMOV.
24218   if (VT.isInteger() && VT.getSizeInBits() == 8)
24219     return SDValue();
24220
24221   SDValue N0 = N->getOperand(0);
24222   SDValue N1 = N->getOperand(1);
24223   SDLoc DL(N);
24224
24225   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24226   // and change it to SUB and CMOV.
24227   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24228       N0.getOpcode() == ISD::ADD &&
24229       N0.getOperand(1) == N1 &&
24230       N1.getOpcode() == ISD::SRA &&
24231       N1.getOperand(0) == N0.getOperand(0))
24232     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24233       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24234         // Generate SUB & CMOV.
24235         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24236                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24237
24238         SDValue Ops[] = { N0.getOperand(0), Neg,
24239                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24240                           SDValue(Neg.getNode(), 1) };
24241         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24242       }
24243   return SDValue();
24244 }
24245
24246 // Try to turn tests against the signbit in the form of:
24247 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24248 // into:
24249 //   SETGT(X, -1)
24250 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24251   // This is only worth doing if the output type is i8.
24252   if (N->getValueType(0) != MVT::i8)
24253     return SDValue();
24254
24255   SDValue N0 = N->getOperand(0);
24256   SDValue N1 = N->getOperand(1);
24257
24258   // We should be performing an xor against a truncated shift.
24259   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24260     return SDValue();
24261
24262   // Make sure we are performing an xor against one.
24263   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24264     return SDValue();
24265
24266   // SetCC on x86 zero extends so only act on this if it's a logical shift.
24267   SDValue Shift = N0.getOperand(0);
24268   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24269     return SDValue();
24270
24271   // Make sure we are truncating from one of i16, i32 or i64.
24272   EVT ShiftTy = Shift.getValueType();
24273   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24274     return SDValue();
24275
24276   // Make sure the shift amount extracts the sign bit.
24277   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24278       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24279     return SDValue();
24280
24281   // Create a greater-than comparison against -1.
24282   // N.B. Using SETGE against 0 works but we want a canonical looking
24283   // comparison, using SETGT matches up with what TranslateX86CC.
24284   SDLoc DL(N);
24285   SDValue ShiftOp = Shift.getOperand(0);
24286   EVT ShiftOpTy = ShiftOp.getValueType();
24287   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24288                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24289   return Cond;
24290 }
24291
24292 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24293                                  TargetLowering::DAGCombinerInfo &DCI,
24294                                  const X86Subtarget *Subtarget) {
24295   if (DCI.isBeforeLegalizeOps())
24296     return SDValue();
24297
24298   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24299     return RV;
24300
24301   if (Subtarget->hasCMov())
24302     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24303       return RV;
24304
24305   return SDValue();
24306 }
24307
24308 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24309 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24310                                   TargetLowering::DAGCombinerInfo &DCI,
24311                                   const X86Subtarget *Subtarget) {
24312   LoadSDNode *Ld = cast<LoadSDNode>(N);
24313   EVT RegVT = Ld->getValueType(0);
24314   EVT MemVT = Ld->getMemoryVT();
24315   SDLoc dl(Ld);
24316   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24317
24318   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24319   // into two 16-byte operations.
24320   ISD::LoadExtType Ext = Ld->getExtensionType();
24321   bool Fast;
24322   unsigned AddressSpace = Ld->getAddressSpace();
24323   unsigned Alignment = Ld->getAlignment();
24324   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24325       Ext == ISD::NON_EXTLOAD &&
24326       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24327                              AddressSpace, Alignment, &Fast) && !Fast) {
24328     unsigned NumElems = RegVT.getVectorNumElements();
24329     if (NumElems < 2)
24330       return SDValue();
24331
24332     SDValue Ptr = Ld->getBasePtr();
24333     SDValue Increment =
24334         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24335
24336     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24337                                   NumElems/2);
24338     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24339                                 Ld->getPointerInfo(), Ld->isVolatile(),
24340                                 Ld->isNonTemporal(), Ld->isInvariant(),
24341                                 Alignment);
24342     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24343     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24344                                 Ld->getPointerInfo(), Ld->isVolatile(),
24345                                 Ld->isNonTemporal(), Ld->isInvariant(),
24346                                 std::min(16U, Alignment));
24347     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24348                              Load1.getValue(1),
24349                              Load2.getValue(1));
24350
24351     SDValue NewVec = DAG.getUNDEF(RegVT);
24352     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24353     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24354     return DCI.CombineTo(N, NewVec, TF, true);
24355   }
24356
24357   return SDValue();
24358 }
24359
24360 /// PerformMLOADCombine - Resolve extending loads
24361 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24362                                    TargetLowering::DAGCombinerInfo &DCI,
24363                                    const X86Subtarget *Subtarget) {
24364   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24365   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24366     return SDValue();
24367
24368   EVT VT = Mld->getValueType(0);
24369   unsigned NumElems = VT.getVectorNumElements();
24370   EVT LdVT = Mld->getMemoryVT();
24371   SDLoc dl(Mld);
24372
24373   assert(LdVT != VT && "Cannot extend to the same type");
24374   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24375   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24376   // From, To sizes and ElemCount must be pow of two
24377   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24378     "Unexpected size for extending masked load");
24379
24380   unsigned SizeRatio  = ToSz / FromSz;
24381   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24382
24383   // Create a type on which we perform the shuffle
24384   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24385           LdVT.getScalarType(), NumElems*SizeRatio);
24386   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24387
24388   // Convert Src0 value
24389   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24390   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24391     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24392     for (unsigned i = 0; i != NumElems; ++i)
24393       ShuffleVec[i] = i * SizeRatio;
24394
24395     // Can't shuffle using an illegal type.
24396     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24397             && "WideVecVT should be legal");
24398     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24399                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24400   }
24401   // Prepare the new mask
24402   SDValue NewMask;
24403   SDValue Mask = Mld->getMask();
24404   if (Mask.getValueType() == VT) {
24405     // Mask and original value have the same type
24406     NewMask = DAG.getBitcast(WideVecVT, Mask);
24407     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24408     for (unsigned i = 0; i != NumElems; ++i)
24409       ShuffleVec[i] = i * SizeRatio;
24410     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24411       ShuffleVec[i] = NumElems*SizeRatio;
24412     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24413                                    DAG.getConstant(0, dl, WideVecVT),
24414                                    &ShuffleVec[0]);
24415   }
24416   else {
24417     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24418     unsigned WidenNumElts = NumElems*SizeRatio;
24419     unsigned MaskNumElts = VT.getVectorNumElements();
24420     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24421                                      WidenNumElts);
24422
24423     unsigned NumConcat = WidenNumElts / MaskNumElts;
24424     SmallVector<SDValue, 16> Ops(NumConcat);
24425     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24426     Ops[0] = Mask;
24427     for (unsigned i = 1; i != NumConcat; ++i)
24428       Ops[i] = ZeroVal;
24429
24430     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24431   }
24432
24433   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24434                                      Mld->getBasePtr(), NewMask, WideSrc0,
24435                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24436                                      ISD::NON_EXTLOAD);
24437   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24438   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24439
24440 }
24441 /// PerformMSTORECombine - Resolve truncating stores
24442 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24443                                     const X86Subtarget *Subtarget) {
24444   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24445   if (!Mst->isTruncatingStore())
24446     return SDValue();
24447
24448   EVT VT = Mst->getValue().getValueType();
24449   unsigned NumElems = VT.getVectorNumElements();
24450   EVT StVT = Mst->getMemoryVT();
24451   SDLoc dl(Mst);
24452
24453   assert(StVT != VT && "Cannot truncate to the same type");
24454   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24455   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24456
24457   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24458
24459   // The truncating store is legal in some cases. For example
24460   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24461   // are designated for truncate store.
24462   // In this case we don't need any further transformations.
24463   if (TLI.isTruncStoreLegal(VT, StVT))
24464     return SDValue();
24465
24466   // From, To sizes and ElemCount must be pow of two
24467   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24468     "Unexpected size for truncating masked store");
24469   // We are going to use the original vector elt for storing.
24470   // Accumulated smaller vector elements must be a multiple of the store size.
24471   assert (((NumElems * FromSz) % ToSz) == 0 &&
24472           "Unexpected ratio for truncating masked store");
24473
24474   unsigned SizeRatio  = FromSz / ToSz;
24475   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24476
24477   // Create a type on which we perform the shuffle
24478   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24479           StVT.getScalarType(), NumElems*SizeRatio);
24480
24481   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24482
24483   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24484   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24485   for (unsigned i = 0; i != NumElems; ++i)
24486     ShuffleVec[i] = i * SizeRatio;
24487
24488   // Can't shuffle using an illegal type.
24489   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24490           && "WideVecVT should be legal");
24491
24492   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24493                                         DAG.getUNDEF(WideVecVT),
24494                                         &ShuffleVec[0]);
24495
24496   SDValue NewMask;
24497   SDValue Mask = Mst->getMask();
24498   if (Mask.getValueType() == VT) {
24499     // Mask and original value have the same type
24500     NewMask = DAG.getBitcast(WideVecVT, Mask);
24501     for (unsigned i = 0; i != NumElems; ++i)
24502       ShuffleVec[i] = i * SizeRatio;
24503     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24504       ShuffleVec[i] = NumElems*SizeRatio;
24505     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24506                                    DAG.getConstant(0, dl, WideVecVT),
24507                                    &ShuffleVec[0]);
24508   }
24509   else {
24510     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24511     unsigned WidenNumElts = NumElems*SizeRatio;
24512     unsigned MaskNumElts = VT.getVectorNumElements();
24513     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24514                                      WidenNumElts);
24515
24516     unsigned NumConcat = WidenNumElts / MaskNumElts;
24517     SmallVector<SDValue, 16> Ops(NumConcat);
24518     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24519     Ops[0] = Mask;
24520     for (unsigned i = 1; i != NumConcat; ++i)
24521       Ops[i] = ZeroVal;
24522
24523     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24524   }
24525
24526   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24527                             NewMask, StVT, Mst->getMemOperand(), false);
24528 }
24529 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24530 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24531                                    const X86Subtarget *Subtarget) {
24532   StoreSDNode *St = cast<StoreSDNode>(N);
24533   EVT VT = St->getValue().getValueType();
24534   EVT StVT = St->getMemoryVT();
24535   SDLoc dl(St);
24536   SDValue StoredVal = St->getOperand(1);
24537   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24538
24539   // If we are saving a concatenation of two XMM registers and 32-byte stores
24540   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24541   bool Fast;
24542   unsigned AddressSpace = St->getAddressSpace();
24543   unsigned Alignment = St->getAlignment();
24544   if (VT.is256BitVector() && StVT == VT &&
24545       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24546                              AddressSpace, Alignment, &Fast) && !Fast) {
24547     unsigned NumElems = VT.getVectorNumElements();
24548     if (NumElems < 2)
24549       return SDValue();
24550
24551     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24552     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24553
24554     SDValue Stride =
24555         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24556     SDValue Ptr0 = St->getBasePtr();
24557     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24558
24559     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24560                                 St->getPointerInfo(), St->isVolatile(),
24561                                 St->isNonTemporal(), Alignment);
24562     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24563                                 St->getPointerInfo(), St->isVolatile(),
24564                                 St->isNonTemporal(),
24565                                 std::min(16U, Alignment));
24566     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24567   }
24568
24569   // Optimize trunc store (of multiple scalars) to shuffle and store.
24570   // First, pack all of the elements in one place. Next, store to memory
24571   // in fewer chunks.
24572   if (St->isTruncatingStore() && VT.isVector()) {
24573     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24574     unsigned NumElems = VT.getVectorNumElements();
24575     assert(StVT != VT && "Cannot truncate to the same type");
24576     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24577     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24578
24579     // The truncating store is legal in some cases. For example
24580     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24581     // are designated for truncate store.
24582     // In this case we don't need any further transformations.
24583     if (TLI.isTruncStoreLegal(VT, StVT))
24584       return SDValue();
24585
24586     // From, To sizes and ElemCount must be pow of two
24587     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24588     // We are going to use the original vector elt for storing.
24589     // Accumulated smaller vector elements must be a multiple of the store size.
24590     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24591
24592     unsigned SizeRatio  = FromSz / ToSz;
24593
24594     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24595
24596     // Create a type on which we perform the shuffle
24597     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24598             StVT.getScalarType(), NumElems*SizeRatio);
24599
24600     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24601
24602     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24603     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24604     for (unsigned i = 0; i != NumElems; ++i)
24605       ShuffleVec[i] = i * SizeRatio;
24606
24607     // Can't shuffle using an illegal type.
24608     if (!TLI.isTypeLegal(WideVecVT))
24609       return SDValue();
24610
24611     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24612                                          DAG.getUNDEF(WideVecVT),
24613                                          &ShuffleVec[0]);
24614     // At this point all of the data is stored at the bottom of the
24615     // register. We now need to save it to mem.
24616
24617     // Find the largest store unit
24618     MVT StoreType = MVT::i8;
24619     for (MVT Tp : MVT::integer_valuetypes()) {
24620       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24621         StoreType = Tp;
24622     }
24623
24624     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24625     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24626         (64 <= NumElems * ToSz))
24627       StoreType = MVT::f64;
24628
24629     // Bitcast the original vector into a vector of store-size units
24630     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24631             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24632     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24633     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24634     SmallVector<SDValue, 8> Chains;
24635     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24636                                         TLI.getPointerTy(DAG.getDataLayout()));
24637     SDValue Ptr = St->getBasePtr();
24638
24639     // Perform one or more big stores into memory.
24640     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24641       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24642                                    StoreType, ShuffWide,
24643                                    DAG.getIntPtrConstant(i, dl));
24644       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24645                                 St->getPointerInfo(), St->isVolatile(),
24646                                 St->isNonTemporal(), St->getAlignment());
24647       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24648       Chains.push_back(Ch);
24649     }
24650
24651     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24652   }
24653
24654   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24655   // the FP state in cases where an emms may be missing.
24656   // A preferable solution to the general problem is to figure out the right
24657   // places to insert EMMS.  This qualifies as a quick hack.
24658
24659   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24660   if (VT.getSizeInBits() != 64)
24661     return SDValue();
24662
24663   const Function *F = DAG.getMachineFunction().getFunction();
24664   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24665   bool F64IsLegal =
24666       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24667   if ((VT.isVector() ||
24668        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24669       isa<LoadSDNode>(St->getValue()) &&
24670       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24671       St->getChain().hasOneUse() && !St->isVolatile()) {
24672     SDNode* LdVal = St->getValue().getNode();
24673     LoadSDNode *Ld = nullptr;
24674     int TokenFactorIndex = -1;
24675     SmallVector<SDValue, 8> Ops;
24676     SDNode* ChainVal = St->getChain().getNode();
24677     // Must be a store of a load.  We currently handle two cases:  the load
24678     // is a direct child, and it's under an intervening TokenFactor.  It is
24679     // possible to dig deeper under nested TokenFactors.
24680     if (ChainVal == LdVal)
24681       Ld = cast<LoadSDNode>(St->getChain());
24682     else if (St->getValue().hasOneUse() &&
24683              ChainVal->getOpcode() == ISD::TokenFactor) {
24684       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24685         if (ChainVal->getOperand(i).getNode() == LdVal) {
24686           TokenFactorIndex = i;
24687           Ld = cast<LoadSDNode>(St->getValue());
24688         } else
24689           Ops.push_back(ChainVal->getOperand(i));
24690       }
24691     }
24692
24693     if (!Ld || !ISD::isNormalLoad(Ld))
24694       return SDValue();
24695
24696     // If this is not the MMX case, i.e. we are just turning i64 load/store
24697     // into f64 load/store, avoid the transformation if there are multiple
24698     // uses of the loaded value.
24699     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24700       return SDValue();
24701
24702     SDLoc LdDL(Ld);
24703     SDLoc StDL(N);
24704     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24705     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24706     // pair instead.
24707     if (Subtarget->is64Bit() || F64IsLegal) {
24708       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24709       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24710                                   Ld->getPointerInfo(), Ld->isVolatile(),
24711                                   Ld->isNonTemporal(), Ld->isInvariant(),
24712                                   Ld->getAlignment());
24713       SDValue NewChain = NewLd.getValue(1);
24714       if (TokenFactorIndex != -1) {
24715         Ops.push_back(NewChain);
24716         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24717       }
24718       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24719                           St->getPointerInfo(),
24720                           St->isVolatile(), St->isNonTemporal(),
24721                           St->getAlignment());
24722     }
24723
24724     // Otherwise, lower to two pairs of 32-bit loads / stores.
24725     SDValue LoAddr = Ld->getBasePtr();
24726     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24727                                  DAG.getConstant(4, LdDL, MVT::i32));
24728
24729     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24730                                Ld->getPointerInfo(),
24731                                Ld->isVolatile(), Ld->isNonTemporal(),
24732                                Ld->isInvariant(), Ld->getAlignment());
24733     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24734                                Ld->getPointerInfo().getWithOffset(4),
24735                                Ld->isVolatile(), Ld->isNonTemporal(),
24736                                Ld->isInvariant(),
24737                                MinAlign(Ld->getAlignment(), 4));
24738
24739     SDValue NewChain = LoLd.getValue(1);
24740     if (TokenFactorIndex != -1) {
24741       Ops.push_back(LoLd);
24742       Ops.push_back(HiLd);
24743       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24744     }
24745
24746     LoAddr = St->getBasePtr();
24747     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24748                          DAG.getConstant(4, StDL, MVT::i32));
24749
24750     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24751                                 St->getPointerInfo(),
24752                                 St->isVolatile(), St->isNonTemporal(),
24753                                 St->getAlignment());
24754     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24755                                 St->getPointerInfo().getWithOffset(4),
24756                                 St->isVolatile(),
24757                                 St->isNonTemporal(),
24758                                 MinAlign(St->getAlignment(), 4));
24759     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24760   }
24761
24762   // This is similar to the above case, but here we handle a scalar 64-bit
24763   // integer store that is extracted from a vector on a 32-bit target.
24764   // If we have SSE2, then we can treat it like a floating-point double
24765   // to get past legalization. The execution dependencies fixup pass will
24766   // choose the optimal machine instruction for the store if this really is
24767   // an integer or v2f32 rather than an f64.
24768   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24769       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24770     SDValue OldExtract = St->getOperand(1);
24771     SDValue ExtOp0 = OldExtract.getOperand(0);
24772     unsigned VecSize = ExtOp0.getValueSizeInBits();
24773     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24774     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24775     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24776                                      BitCast, OldExtract.getOperand(1));
24777     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24778                         St->getPointerInfo(), St->isVolatile(),
24779                         St->isNonTemporal(), St->getAlignment());
24780   }
24781
24782   return SDValue();
24783 }
24784
24785 /// Return 'true' if this vector operation is "horizontal"
24786 /// and return the operands for the horizontal operation in LHS and RHS.  A
24787 /// horizontal operation performs the binary operation on successive elements
24788 /// of its first operand, then on successive elements of its second operand,
24789 /// returning the resulting values in a vector.  For example, if
24790 ///   A = < float a0, float a1, float a2, float a3 >
24791 /// and
24792 ///   B = < float b0, float b1, float b2, float b3 >
24793 /// then the result of doing a horizontal operation on A and B is
24794 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24795 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24796 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24797 /// set to A, RHS to B, and the routine returns 'true'.
24798 /// Note that the binary operation should have the property that if one of the
24799 /// operands is UNDEF then the result is UNDEF.
24800 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24801   // Look for the following pattern: if
24802   //   A = < float a0, float a1, float a2, float a3 >
24803   //   B = < float b0, float b1, float b2, float b3 >
24804   // and
24805   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24806   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24807   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24808   // which is A horizontal-op B.
24809
24810   // At least one of the operands should be a vector shuffle.
24811   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24812       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24813     return false;
24814
24815   MVT VT = LHS.getSimpleValueType();
24816
24817   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24818          "Unsupported vector type for horizontal add/sub");
24819
24820   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24821   // operate independently on 128-bit lanes.
24822   unsigned NumElts = VT.getVectorNumElements();
24823   unsigned NumLanes = VT.getSizeInBits()/128;
24824   unsigned NumLaneElts = NumElts / NumLanes;
24825   assert((NumLaneElts % 2 == 0) &&
24826          "Vector type should have an even number of elements in each lane");
24827   unsigned HalfLaneElts = NumLaneElts/2;
24828
24829   // View LHS in the form
24830   //   LHS = VECTOR_SHUFFLE A, B, LMask
24831   // If LHS is not a shuffle then pretend it is the shuffle
24832   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24833   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24834   // type VT.
24835   SDValue A, B;
24836   SmallVector<int, 16> LMask(NumElts);
24837   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24838     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24839       A = LHS.getOperand(0);
24840     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24841       B = LHS.getOperand(1);
24842     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24843     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24844   } else {
24845     if (LHS.getOpcode() != ISD::UNDEF)
24846       A = LHS;
24847     for (unsigned i = 0; i != NumElts; ++i)
24848       LMask[i] = i;
24849   }
24850
24851   // Likewise, view RHS in the form
24852   //   RHS = VECTOR_SHUFFLE C, D, RMask
24853   SDValue C, D;
24854   SmallVector<int, 16> RMask(NumElts);
24855   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24856     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24857       C = RHS.getOperand(0);
24858     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24859       D = RHS.getOperand(1);
24860     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24861     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24862   } else {
24863     if (RHS.getOpcode() != ISD::UNDEF)
24864       C = RHS;
24865     for (unsigned i = 0; i != NumElts; ++i)
24866       RMask[i] = i;
24867   }
24868
24869   // Check that the shuffles are both shuffling the same vectors.
24870   if (!(A == C && B == D) && !(A == D && B == C))
24871     return false;
24872
24873   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24874   if (!A.getNode() && !B.getNode())
24875     return false;
24876
24877   // If A and B occur in reverse order in RHS, then "swap" them (which means
24878   // rewriting the mask).
24879   if (A != C)
24880     ShuffleVectorSDNode::commuteMask(RMask);
24881
24882   // At this point LHS and RHS are equivalent to
24883   //   LHS = VECTOR_SHUFFLE A, B, LMask
24884   //   RHS = VECTOR_SHUFFLE A, B, RMask
24885   // Check that the masks correspond to performing a horizontal operation.
24886   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24887     for (unsigned i = 0; i != NumLaneElts; ++i) {
24888       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24889
24890       // Ignore any UNDEF components.
24891       if (LIdx < 0 || RIdx < 0 ||
24892           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24893           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24894         continue;
24895
24896       // Check that successive elements are being operated on.  If not, this is
24897       // not a horizontal operation.
24898       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24899       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24900       if (!(LIdx == Index && RIdx == Index + 1) &&
24901           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24902         return false;
24903     }
24904   }
24905
24906   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24907   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24908   return true;
24909 }
24910
24911 /// Do target-specific dag combines on floating point adds.
24912 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24913                                   const X86Subtarget *Subtarget) {
24914   EVT VT = N->getValueType(0);
24915   SDValue LHS = N->getOperand(0);
24916   SDValue RHS = N->getOperand(1);
24917
24918   // Try to synthesize horizontal adds from adds of shuffles.
24919   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24920        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24921       isHorizontalBinOp(LHS, RHS, true))
24922     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24923   return SDValue();
24924 }
24925
24926 /// Do target-specific dag combines on floating point subs.
24927 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24928                                   const X86Subtarget *Subtarget) {
24929   EVT VT = N->getValueType(0);
24930   SDValue LHS = N->getOperand(0);
24931   SDValue RHS = N->getOperand(1);
24932
24933   // Try to synthesize horizontal subs from subs of shuffles.
24934   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24935        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24936       isHorizontalBinOp(LHS, RHS, false))
24937     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24938   return SDValue();
24939 }
24940
24941 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24942 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24943   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24944
24945   // F[X]OR(0.0, x) -> x
24946   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24947     if (C->getValueAPF().isPosZero())
24948       return N->getOperand(1);
24949
24950   // F[X]OR(x, 0.0) -> x
24951   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24952     if (C->getValueAPF().isPosZero())
24953       return N->getOperand(0);
24954   return SDValue();
24955 }
24956
24957 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24958 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24959   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24960
24961   // Only perform optimizations if UnsafeMath is used.
24962   if (!DAG.getTarget().Options.UnsafeFPMath)
24963     return SDValue();
24964
24965   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24966   // into FMINC and FMAXC, which are Commutative operations.
24967   unsigned NewOp = 0;
24968   switch (N->getOpcode()) {
24969     default: llvm_unreachable("unknown opcode");
24970     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24971     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24972   }
24973
24974   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24975                      N->getOperand(0), N->getOperand(1));
24976 }
24977
24978 /// Do target-specific dag combines on X86ISD::FAND nodes.
24979 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24980   // FAND(0.0, x) -> 0.0
24981   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24982     if (C->getValueAPF().isPosZero())
24983       return N->getOperand(0);
24984
24985   // FAND(x, 0.0) -> 0.0
24986   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24987     if (C->getValueAPF().isPosZero())
24988       return N->getOperand(1);
24989
24990   return SDValue();
24991 }
24992
24993 /// Do target-specific dag combines on X86ISD::FANDN nodes
24994 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24995   // FANDN(0.0, x) -> x
24996   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24997     if (C->getValueAPF().isPosZero())
24998       return N->getOperand(1);
24999
25000   // FANDN(x, 0.0) -> 0.0
25001   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25002     if (C->getValueAPF().isPosZero())
25003       return N->getOperand(1);
25004
25005   return SDValue();
25006 }
25007
25008 static SDValue PerformBTCombine(SDNode *N,
25009                                 SelectionDAG &DAG,
25010                                 TargetLowering::DAGCombinerInfo &DCI) {
25011   // BT ignores high bits in the bit index operand.
25012   SDValue Op1 = N->getOperand(1);
25013   if (Op1.hasOneUse()) {
25014     unsigned BitWidth = Op1.getValueSizeInBits();
25015     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25016     APInt KnownZero, KnownOne;
25017     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25018                                           !DCI.isBeforeLegalizeOps());
25019     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25020     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25021         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25022       DCI.CommitTargetLoweringOpt(TLO);
25023   }
25024   return SDValue();
25025 }
25026
25027 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25028   SDValue Op = N->getOperand(0);
25029   if (Op.getOpcode() == ISD::BITCAST)
25030     Op = Op.getOperand(0);
25031   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25032   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25033       VT.getVectorElementType().getSizeInBits() ==
25034       OpVT.getVectorElementType().getSizeInBits()) {
25035     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25036   }
25037   return SDValue();
25038 }
25039
25040 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25041                                                const X86Subtarget *Subtarget) {
25042   EVT VT = N->getValueType(0);
25043   if (!VT.isVector())
25044     return SDValue();
25045
25046   SDValue N0 = N->getOperand(0);
25047   SDValue N1 = N->getOperand(1);
25048   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25049   SDLoc dl(N);
25050
25051   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25052   // both SSE and AVX2 since there is no sign-extended shift right
25053   // operation on a vector with 64-bit elements.
25054   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25055   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25056   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25057       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25058     SDValue N00 = N0.getOperand(0);
25059
25060     // EXTLOAD has a better solution on AVX2,
25061     // it may be replaced with X86ISD::VSEXT node.
25062     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25063       if (!ISD::isNormalLoad(N00.getNode()))
25064         return SDValue();
25065
25066     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25067         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25068                                   N00, N1);
25069       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25070     }
25071   }
25072   return SDValue();
25073 }
25074
25075 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25076                                   TargetLowering::DAGCombinerInfo &DCI,
25077                                   const X86Subtarget *Subtarget) {
25078   SDValue N0 = N->getOperand(0);
25079   EVT VT = N->getValueType(0);
25080   EVT SVT = VT.getScalarType();
25081   EVT InVT = N0.getValueType();
25082   EVT InSVT = InVT.getScalarType();
25083   SDLoc DL(N);
25084
25085   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25086   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25087   // This exposes the sext to the sdivrem lowering, so that it directly extends
25088   // from AH (which we otherwise need to do contortions to access).
25089   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25090       InVT == MVT::i8 && VT == MVT::i32) {
25091     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25092     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25093                             N0.getOperand(0), N0.getOperand(1));
25094     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25095     return R.getValue(1);
25096   }
25097
25098   if (!DCI.isBeforeLegalizeOps()) {
25099     if (InVT == MVT::i1) {
25100       SDValue Zero = DAG.getConstant(0, DL, VT);
25101       SDValue AllOnes =
25102         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25103       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25104     }
25105     return SDValue();
25106   }
25107
25108   if (VT.isVector() && Subtarget->hasSSE2()) {
25109     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25110       EVT InVT = N.getValueType();
25111       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25112                                    Size / InVT.getScalarSizeInBits());
25113       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25114                                     DAG.getUNDEF(InVT));
25115       Opnds[0] = N;
25116       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25117     };
25118
25119     // If target-size is less than 128-bits, extend to a type that would extend
25120     // to 128 bits, extend that and extract the original target vector.
25121     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25122         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25123         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25124       unsigned Scale = 128 / VT.getSizeInBits();
25125       EVT ExVT =
25126           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25127       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25128       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25129       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25130                          DAG.getIntPtrConstant(0, DL));
25131     }
25132
25133     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25134     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25135     if (VT.getSizeInBits() == 128 &&
25136         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25137         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25138       SDValue ExOp = ExtendVecSize(DL, N0, 128);
25139       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25140     }
25141
25142     // On pre-AVX2 targets, split into 128-bit nodes of
25143     // ISD::SIGN_EXTEND_VECTOR_INREG.
25144     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25145         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25146         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25147       unsigned NumVecs = VT.getSizeInBits() / 128;
25148       unsigned NumSubElts = 128 / SVT.getSizeInBits();
25149       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25150       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25151
25152       SmallVector<SDValue, 8> Opnds;
25153       for (unsigned i = 0, Offset = 0; i != NumVecs;
25154            ++i, Offset += NumSubElts) {
25155         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25156                                      DAG.getIntPtrConstant(Offset, DL));
25157         SrcVec = ExtendVecSize(DL, SrcVec, 128);
25158         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25159         Opnds.push_back(SrcVec);
25160       }
25161       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25162     }
25163   }
25164
25165   if (!Subtarget->hasFp256())
25166     return SDValue();
25167
25168   if (VT.isVector() && VT.getSizeInBits() == 256)
25169     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25170       return R;
25171
25172   return SDValue();
25173 }
25174
25175 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25176                                  const X86Subtarget* Subtarget) {
25177   SDLoc dl(N);
25178   EVT VT = N->getValueType(0);
25179
25180   // Let legalize expand this if it isn't a legal type yet.
25181   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25182     return SDValue();
25183
25184   EVT ScalarVT = VT.getScalarType();
25185   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25186       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25187        !Subtarget->hasAVX512()))
25188     return SDValue();
25189
25190   SDValue A = N->getOperand(0);
25191   SDValue B = N->getOperand(1);
25192   SDValue C = N->getOperand(2);
25193
25194   bool NegA = (A.getOpcode() == ISD::FNEG);
25195   bool NegB = (B.getOpcode() == ISD::FNEG);
25196   bool NegC = (C.getOpcode() == ISD::FNEG);
25197
25198   // Negative multiplication when NegA xor NegB
25199   bool NegMul = (NegA != NegB);
25200   if (NegA)
25201     A = A.getOperand(0);
25202   if (NegB)
25203     B = B.getOperand(0);
25204   if (NegC)
25205     C = C.getOperand(0);
25206
25207   unsigned Opcode;
25208   if (!NegMul)
25209     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25210   else
25211     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25212
25213   return DAG.getNode(Opcode, dl, VT, A, B, C);
25214 }
25215
25216 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25217                                   TargetLowering::DAGCombinerInfo &DCI,
25218                                   const X86Subtarget *Subtarget) {
25219   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25220   //           (and (i32 x86isd::setcc_carry), 1)
25221   // This eliminates the zext. This transformation is necessary because
25222   // ISD::SETCC is always legalized to i8.
25223   SDLoc dl(N);
25224   SDValue N0 = N->getOperand(0);
25225   EVT VT = N->getValueType(0);
25226
25227   if (N0.getOpcode() == ISD::AND &&
25228       N0.hasOneUse() &&
25229       N0.getOperand(0).hasOneUse()) {
25230     SDValue N00 = N0.getOperand(0);
25231     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25232       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25233       if (!C || C->getZExtValue() != 1)
25234         return SDValue();
25235       return DAG.getNode(ISD::AND, dl, VT,
25236                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25237                                      N00.getOperand(0), N00.getOperand(1)),
25238                          DAG.getConstant(1, dl, VT));
25239     }
25240   }
25241
25242   if (N0.getOpcode() == ISD::TRUNCATE &&
25243       N0.hasOneUse() &&
25244       N0.getOperand(0).hasOneUse()) {
25245     SDValue N00 = N0.getOperand(0);
25246     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25247       return DAG.getNode(ISD::AND, dl, VT,
25248                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25249                                      N00.getOperand(0), N00.getOperand(1)),
25250                          DAG.getConstant(1, dl, VT));
25251     }
25252   }
25253
25254   if (VT.is256BitVector())
25255     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25256       return R;
25257
25258   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25259   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25260   // This exposes the zext to the udivrem lowering, so that it directly extends
25261   // from AH (which we otherwise need to do contortions to access).
25262   if (N0.getOpcode() == ISD::UDIVREM &&
25263       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25264       (VT == MVT::i32 || VT == MVT::i64)) {
25265     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25266     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25267                             N0.getOperand(0), N0.getOperand(1));
25268     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25269     return R.getValue(1);
25270   }
25271
25272   return SDValue();
25273 }
25274
25275 // Optimize x == -y --> x+y == 0
25276 //          x != -y --> x+y != 0
25277 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25278                                       const X86Subtarget* Subtarget) {
25279   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25280   SDValue LHS = N->getOperand(0);
25281   SDValue RHS = N->getOperand(1);
25282   EVT VT = N->getValueType(0);
25283   SDLoc DL(N);
25284
25285   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25286     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25287       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25288         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25289                                    LHS.getOperand(1));
25290         return DAG.getSetCC(DL, N->getValueType(0), addV,
25291                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25292       }
25293   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25294     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25295       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25296         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25297                                    RHS.getOperand(1));
25298         return DAG.getSetCC(DL, N->getValueType(0), addV,
25299                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25300       }
25301
25302   if (VT.getScalarType() == MVT::i1 &&
25303       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25304     bool IsSEXT0 =
25305         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25306         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25307     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25308
25309     if (!IsSEXT0 || !IsVZero1) {
25310       // Swap the operands and update the condition code.
25311       std::swap(LHS, RHS);
25312       CC = ISD::getSetCCSwappedOperands(CC);
25313
25314       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25315                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25316       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25317     }
25318
25319     if (IsSEXT0 && IsVZero1) {
25320       assert(VT == LHS.getOperand(0).getValueType() &&
25321              "Uexpected operand type");
25322       if (CC == ISD::SETGT)
25323         return DAG.getConstant(0, DL, VT);
25324       if (CC == ISD::SETLE)
25325         return DAG.getConstant(1, DL, VT);
25326       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25327         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25328
25329       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25330              "Unexpected condition code!");
25331       return LHS.getOperand(0);
25332     }
25333   }
25334
25335   return SDValue();
25336 }
25337
25338 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25339                                          SelectionDAG &DAG) {
25340   SDLoc dl(Load);
25341   MVT VT = Load->getSimpleValueType(0);
25342   MVT EVT = VT.getVectorElementType();
25343   SDValue Addr = Load->getOperand(1);
25344   SDValue NewAddr = DAG.getNode(
25345       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25346       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25347                       Addr.getSimpleValueType()));
25348
25349   SDValue NewLoad =
25350       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25351                   DAG.getMachineFunction().getMachineMemOperand(
25352                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25353   return NewLoad;
25354 }
25355
25356 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25357                                       const X86Subtarget *Subtarget) {
25358   SDLoc dl(N);
25359   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25360   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25361          "X86insertps is only defined for v4x32");
25362
25363   SDValue Ld = N->getOperand(1);
25364   if (MayFoldLoad(Ld)) {
25365     // Extract the countS bits from the immediate so we can get the proper
25366     // address when narrowing the vector load to a specific element.
25367     // When the second source op is a memory address, insertps doesn't use
25368     // countS and just gets an f32 from that address.
25369     unsigned DestIndex =
25370         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25371
25372     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25373
25374     // Create this as a scalar to vector to match the instruction pattern.
25375     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25376     // countS bits are ignored when loading from memory on insertps, which
25377     // means we don't need to explicitly set them to 0.
25378     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25379                        LoadScalarToVector, N->getOperand(2));
25380   }
25381   return SDValue();
25382 }
25383
25384 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25385   SDValue V0 = N->getOperand(0);
25386   SDValue V1 = N->getOperand(1);
25387   SDLoc DL(N);
25388   EVT VT = N->getValueType(0);
25389
25390   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25391   // operands and changing the mask to 1. This saves us a bunch of
25392   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25393   // x86InstrInfo knows how to commute this back after instruction selection
25394   // if it would help register allocation.
25395
25396   // TODO: If optimizing for size or a processor that doesn't suffer from
25397   // partial register update stalls, this should be transformed into a MOVSD
25398   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25399
25400   if (VT == MVT::v2f64)
25401     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25402       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25403         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25404         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25405       }
25406
25407   return SDValue();
25408 }
25409
25410 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25411 // as "sbb reg,reg", since it can be extended without zext and produces
25412 // an all-ones bit which is more useful than 0/1 in some cases.
25413 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25414                                MVT VT) {
25415   if (VT == MVT::i8)
25416     return DAG.getNode(ISD::AND, DL, VT,
25417                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25418                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25419                                    EFLAGS),
25420                        DAG.getConstant(1, DL, VT));
25421   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25422   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25423                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25424                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25425                                  EFLAGS));
25426 }
25427
25428 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25429 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25430                                    TargetLowering::DAGCombinerInfo &DCI,
25431                                    const X86Subtarget *Subtarget) {
25432   SDLoc DL(N);
25433   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25434   SDValue EFLAGS = N->getOperand(1);
25435
25436   if (CC == X86::COND_A) {
25437     // Try to convert COND_A into COND_B in an attempt to facilitate
25438     // materializing "setb reg".
25439     //
25440     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25441     // cannot take an immediate as its first operand.
25442     //
25443     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25444         EFLAGS.getValueType().isInteger() &&
25445         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25446       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25447                                    EFLAGS.getNode()->getVTList(),
25448                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25449       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25450       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25451     }
25452   }
25453
25454   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25455   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25456   // cases.
25457   if (CC == X86::COND_B)
25458     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25459
25460   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25461     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25462     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25463   }
25464
25465   return SDValue();
25466 }
25467
25468 // Optimize branch condition evaluation.
25469 //
25470 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25471                                     TargetLowering::DAGCombinerInfo &DCI,
25472                                     const X86Subtarget *Subtarget) {
25473   SDLoc DL(N);
25474   SDValue Chain = N->getOperand(0);
25475   SDValue Dest = N->getOperand(1);
25476   SDValue EFLAGS = N->getOperand(3);
25477   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25478
25479   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25480     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25481     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25482                        Flags);
25483   }
25484
25485   return SDValue();
25486 }
25487
25488 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25489                                                          SelectionDAG &DAG) {
25490   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25491   // optimize away operation when it's from a constant.
25492   //
25493   // The general transformation is:
25494   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25495   //       AND(VECTOR_CMP(x,y), constant2)
25496   //    constant2 = UNARYOP(constant)
25497
25498   // Early exit if this isn't a vector operation, the operand of the
25499   // unary operation isn't a bitwise AND, or if the sizes of the operations
25500   // aren't the same.
25501   EVT VT = N->getValueType(0);
25502   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25503       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25504       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25505     return SDValue();
25506
25507   // Now check that the other operand of the AND is a constant. We could
25508   // make the transformation for non-constant splats as well, but it's unclear
25509   // that would be a benefit as it would not eliminate any operations, just
25510   // perform one more step in scalar code before moving to the vector unit.
25511   if (BuildVectorSDNode *BV =
25512           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25513     // Bail out if the vector isn't a constant.
25514     if (!BV->isConstant())
25515       return SDValue();
25516
25517     // Everything checks out. Build up the new and improved node.
25518     SDLoc DL(N);
25519     EVT IntVT = BV->getValueType(0);
25520     // Create a new constant of the appropriate type for the transformed
25521     // DAG.
25522     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25523     // The AND node needs bitcasts to/from an integer vector type around it.
25524     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25525     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25526                                  N->getOperand(0)->getOperand(0), MaskConst);
25527     SDValue Res = DAG.getBitcast(VT, NewAnd);
25528     return Res;
25529   }
25530
25531   return SDValue();
25532 }
25533
25534 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25535                                         const X86Subtarget *Subtarget) {
25536   SDValue Op0 = N->getOperand(0);
25537   EVT VT = N->getValueType(0);
25538   EVT InVT = Op0.getValueType();
25539   EVT InSVT = InVT.getScalarType();
25540   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25541
25542   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25543   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25544   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25545     SDLoc dl(N);
25546     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25547                                  InVT.getVectorNumElements());
25548     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25549
25550     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25551       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25552
25553     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25554   }
25555
25556   return SDValue();
25557 }
25558
25559 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25560                                         const X86Subtarget *Subtarget) {
25561   // First try to optimize away the conversion entirely when it's
25562   // conditionally from a constant. Vectors only.
25563   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25564     return Res;
25565
25566   // Now move on to more general possibilities.
25567   SDValue Op0 = N->getOperand(0);
25568   EVT VT = N->getValueType(0);
25569   EVT InVT = Op0.getValueType();
25570   EVT InSVT = InVT.getScalarType();
25571
25572   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25573   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25574   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25575     SDLoc dl(N);
25576     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25577                                  InVT.getVectorNumElements());
25578     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25579     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25580   }
25581
25582   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25583   // a 32-bit target where SSE doesn't support i64->FP operations.
25584   if (Op0.getOpcode() == ISD::LOAD) {
25585     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25586     EVT LdVT = Ld->getValueType(0);
25587
25588     // This transformation is not supported if the result type is f16
25589     if (VT == MVT::f16)
25590       return SDValue();
25591
25592     if (!Ld->isVolatile() && !VT.isVector() &&
25593         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25594         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25595       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25596           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25597       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25598       return FILDChain;
25599     }
25600   }
25601   return SDValue();
25602 }
25603
25604 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25605 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25606                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25607   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25608   // the result is either zero or one (depending on the input carry bit).
25609   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25610   if (X86::isZeroNode(N->getOperand(0)) &&
25611       X86::isZeroNode(N->getOperand(1)) &&
25612       // We don't have a good way to replace an EFLAGS use, so only do this when
25613       // dead right now.
25614       SDValue(N, 1).use_empty()) {
25615     SDLoc DL(N);
25616     EVT VT = N->getValueType(0);
25617     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25618     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25619                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25620                                            DAG.getConstant(X86::COND_B, DL,
25621                                                            MVT::i8),
25622                                            N->getOperand(2)),
25623                                DAG.getConstant(1, DL, VT));
25624     return DCI.CombineTo(N, Res1, CarryOut);
25625   }
25626
25627   return SDValue();
25628 }
25629
25630 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25631 //      (add Y, (setne X, 0)) -> sbb -1, Y
25632 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25633 //      (sub (setne X, 0), Y) -> adc -1, Y
25634 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25635   SDLoc DL(N);
25636
25637   // Look through ZExts.
25638   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25639   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25640     return SDValue();
25641
25642   SDValue SetCC = Ext.getOperand(0);
25643   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25644     return SDValue();
25645
25646   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25647   if (CC != X86::COND_E && CC != X86::COND_NE)
25648     return SDValue();
25649
25650   SDValue Cmp = SetCC.getOperand(1);
25651   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25652       !X86::isZeroNode(Cmp.getOperand(1)) ||
25653       !Cmp.getOperand(0).getValueType().isInteger())
25654     return SDValue();
25655
25656   SDValue CmpOp0 = Cmp.getOperand(0);
25657   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25658                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25659
25660   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25661   if (CC == X86::COND_NE)
25662     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25663                        DL, OtherVal.getValueType(), OtherVal,
25664                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25665                        NewCmp);
25666   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25667                      DL, OtherVal.getValueType(), OtherVal,
25668                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25669 }
25670
25671 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25672 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25673                                  const X86Subtarget *Subtarget) {
25674   EVT VT = N->getValueType(0);
25675   SDValue Op0 = N->getOperand(0);
25676   SDValue Op1 = N->getOperand(1);
25677
25678   // Try to synthesize horizontal adds from adds of shuffles.
25679   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25680        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25681       isHorizontalBinOp(Op0, Op1, true))
25682     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25683
25684   return OptimizeConditionalInDecrement(N, DAG);
25685 }
25686
25687 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25688                                  const X86Subtarget *Subtarget) {
25689   SDValue Op0 = N->getOperand(0);
25690   SDValue Op1 = N->getOperand(1);
25691
25692   // X86 can't encode an immediate LHS of a sub. See if we can push the
25693   // negation into a preceding instruction.
25694   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25695     // If the RHS of the sub is a XOR with one use and a constant, invert the
25696     // immediate. Then add one to the LHS of the sub so we can turn
25697     // X-Y -> X+~Y+1, saving one register.
25698     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25699         isa<ConstantSDNode>(Op1.getOperand(1))) {
25700       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25701       EVT VT = Op0.getValueType();
25702       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25703                                    Op1.getOperand(0),
25704                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25705       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25706                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25707     }
25708   }
25709
25710   // Try to synthesize horizontal adds from adds of shuffles.
25711   EVT VT = N->getValueType(0);
25712   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25713        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25714       isHorizontalBinOp(Op0, Op1, true))
25715     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25716
25717   return OptimizeConditionalInDecrement(N, DAG);
25718 }
25719
25720 /// performVZEXTCombine - Performs build vector combines
25721 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25722                                    TargetLowering::DAGCombinerInfo &DCI,
25723                                    const X86Subtarget *Subtarget) {
25724   SDLoc DL(N);
25725   MVT VT = N->getSimpleValueType(0);
25726   SDValue Op = N->getOperand(0);
25727   MVT OpVT = Op.getSimpleValueType();
25728   MVT OpEltVT = OpVT.getVectorElementType();
25729   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25730
25731   // (vzext (bitcast (vzext (x)) -> (vzext x)
25732   SDValue V = Op;
25733   while (V.getOpcode() == ISD::BITCAST)
25734     V = V.getOperand(0);
25735
25736   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25737     MVT InnerVT = V.getSimpleValueType();
25738     MVT InnerEltVT = InnerVT.getVectorElementType();
25739
25740     // If the element sizes match exactly, we can just do one larger vzext. This
25741     // is always an exact type match as vzext operates on integer types.
25742     if (OpEltVT == InnerEltVT) {
25743       assert(OpVT == InnerVT && "Types must match for vzext!");
25744       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25745     }
25746
25747     // The only other way we can combine them is if only a single element of the
25748     // inner vzext is used in the input to the outer vzext.
25749     if (InnerEltVT.getSizeInBits() < InputBits)
25750       return SDValue();
25751
25752     // In this case, the inner vzext is completely dead because we're going to
25753     // only look at bits inside of the low element. Just do the outer vzext on
25754     // a bitcast of the input to the inner.
25755     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25756   }
25757
25758   // Check if we can bypass extracting and re-inserting an element of an input
25759   // vector. Essentially:
25760   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25761   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25762       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25763       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25764     SDValue ExtractedV = V.getOperand(0);
25765     SDValue OrigV = ExtractedV.getOperand(0);
25766     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25767       if (ExtractIdx->getZExtValue() == 0) {
25768         MVT OrigVT = OrigV.getSimpleValueType();
25769         // Extract a subvector if necessary...
25770         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25771           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25772           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25773                                     OrigVT.getVectorNumElements() / Ratio);
25774           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25775                               DAG.getIntPtrConstant(0, DL));
25776         }
25777         Op = DAG.getBitcast(OpVT, OrigV);
25778         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25779       }
25780   }
25781
25782   return SDValue();
25783 }
25784
25785 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25786                                              DAGCombinerInfo &DCI) const {
25787   SelectionDAG &DAG = DCI.DAG;
25788   switch (N->getOpcode()) {
25789   default: break;
25790   case ISD::EXTRACT_VECTOR_ELT:
25791     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25792   case ISD::VSELECT:
25793   case ISD::SELECT:
25794   case X86ISD::SHRUNKBLEND:
25795     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25796   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25797   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25798   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25799   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25800   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25801   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25802   case ISD::SHL:
25803   case ISD::SRA:
25804   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25805   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25806   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25807   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25808   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25809   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25810   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25811   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25812   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25813   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25814   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25815   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25816   case X86ISD::FXOR:
25817   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25818   case X86ISD::FMIN:
25819   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25820   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25821   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25822   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25823   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25824   case ISD::ANY_EXTEND:
25825   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25826   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25827   case ISD::SIGN_EXTEND_INREG:
25828     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25829   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25830   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25831   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25832   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25833   case X86ISD::SHUFP:       // Handle all target specific shuffles
25834   case X86ISD::PALIGNR:
25835   case X86ISD::UNPCKH:
25836   case X86ISD::UNPCKL:
25837   case X86ISD::MOVHLPS:
25838   case X86ISD::MOVLHPS:
25839   case X86ISD::PSHUFB:
25840   case X86ISD::PSHUFD:
25841   case X86ISD::PSHUFHW:
25842   case X86ISD::PSHUFLW:
25843   case X86ISD::MOVSS:
25844   case X86ISD::MOVSD:
25845   case X86ISD::VPERMILPI:
25846   case X86ISD::VPERM2X128:
25847   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25848   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25849   case X86ISD::INSERTPS: {
25850     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25851       return PerformINSERTPSCombine(N, DAG, Subtarget);
25852     break;
25853   }
25854   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25855   }
25856
25857   return SDValue();
25858 }
25859
25860 /// isTypeDesirableForOp - Return true if the target has native support for
25861 /// the specified value type and it is 'desirable' to use the type for the
25862 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25863 /// instruction encodings are longer and some i16 instructions are slow.
25864 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25865   if (!isTypeLegal(VT))
25866     return false;
25867   if (VT != MVT::i16)
25868     return true;
25869
25870   switch (Opc) {
25871   default:
25872     return true;
25873   case ISD::LOAD:
25874   case ISD::SIGN_EXTEND:
25875   case ISD::ZERO_EXTEND:
25876   case ISD::ANY_EXTEND:
25877   case ISD::SHL:
25878   case ISD::SRL:
25879   case ISD::SUB:
25880   case ISD::ADD:
25881   case ISD::MUL:
25882   case ISD::AND:
25883   case ISD::OR:
25884   case ISD::XOR:
25885     return false;
25886   }
25887 }
25888
25889 /// IsDesirableToPromoteOp - This method query the target whether it is
25890 /// beneficial for dag combiner to promote the specified node. If true, it
25891 /// should return the desired promotion type by reference.
25892 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25893   EVT VT = Op.getValueType();
25894   if (VT != MVT::i16)
25895     return false;
25896
25897   bool Promote = false;
25898   bool Commute = false;
25899   switch (Op.getOpcode()) {
25900   default: break;
25901   case ISD::LOAD: {
25902     LoadSDNode *LD = cast<LoadSDNode>(Op);
25903     // If the non-extending load has a single use and it's not live out, then it
25904     // might be folded.
25905     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25906                                                      Op.hasOneUse()*/) {
25907       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25908              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25909         // The only case where we'd want to promote LOAD (rather then it being
25910         // promoted as an operand is when it's only use is liveout.
25911         if (UI->getOpcode() != ISD::CopyToReg)
25912           return false;
25913       }
25914     }
25915     Promote = true;
25916     break;
25917   }
25918   case ISD::SIGN_EXTEND:
25919   case ISD::ZERO_EXTEND:
25920   case ISD::ANY_EXTEND:
25921     Promote = true;
25922     break;
25923   case ISD::SHL:
25924   case ISD::SRL: {
25925     SDValue N0 = Op.getOperand(0);
25926     // Look out for (store (shl (load), x)).
25927     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25928       return false;
25929     Promote = true;
25930     break;
25931   }
25932   case ISD::ADD:
25933   case ISD::MUL:
25934   case ISD::AND:
25935   case ISD::OR:
25936   case ISD::XOR:
25937     Commute = true;
25938     // fallthrough
25939   case ISD::SUB: {
25940     SDValue N0 = Op.getOperand(0);
25941     SDValue N1 = Op.getOperand(1);
25942     if (!Commute && MayFoldLoad(N1))
25943       return false;
25944     // Avoid disabling potential load folding opportunities.
25945     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25946       return false;
25947     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25948       return false;
25949     Promote = true;
25950   }
25951   }
25952
25953   PVT = MVT::i32;
25954   return Promote;
25955 }
25956
25957 //===----------------------------------------------------------------------===//
25958 //                           X86 Inline Assembly Support
25959 //===----------------------------------------------------------------------===//
25960
25961 // Helper to match a string separated by whitespace.
25962 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25963   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25964
25965   for (StringRef Piece : Pieces) {
25966     if (!S.startswith(Piece)) // Check if the piece matches.
25967       return false;
25968
25969     S = S.substr(Piece.size());
25970     StringRef::size_type Pos = S.find_first_not_of(" \t");
25971     if (Pos == 0) // We matched a prefix.
25972       return false;
25973
25974     S = S.substr(Pos);
25975   }
25976
25977   return S.empty();
25978 }
25979
25980 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25981
25982   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25983     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25984         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25985         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25986
25987       if (AsmPieces.size() == 3)
25988         return true;
25989       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25990         return true;
25991     }
25992   }
25993   return false;
25994 }
25995
25996 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25997   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25998
25999   std::string AsmStr = IA->getAsmString();
26000
26001   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26002   if (!Ty || Ty->getBitWidth() % 16 != 0)
26003     return false;
26004
26005   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26006   SmallVector<StringRef, 4> AsmPieces;
26007   SplitString(AsmStr, AsmPieces, ";\n");
26008
26009   switch (AsmPieces.size()) {
26010   default: return false;
26011   case 1:
26012     // FIXME: this should verify that we are targeting a 486 or better.  If not,
26013     // we will turn this bswap into something that will be lowered to logical
26014     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26015     // lower so don't worry about this.
26016     // bswap $0
26017     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26018         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26019         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26020         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26021         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26022         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26023       // No need to check constraints, nothing other than the equivalent of
26024       // "=r,0" would be valid here.
26025       return IntrinsicLowering::LowerToByteSwap(CI);
26026     }
26027
26028     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26029     if (CI->getType()->isIntegerTy(16) &&
26030         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26031         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26032          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26033       AsmPieces.clear();
26034       StringRef ConstraintsStr = IA->getConstraintString();
26035       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26036       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26037       if (clobbersFlagRegisters(AsmPieces))
26038         return IntrinsicLowering::LowerToByteSwap(CI);
26039     }
26040     break;
26041   case 3:
26042     if (CI->getType()->isIntegerTy(32) &&
26043         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26044         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26045         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26046         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26047       AsmPieces.clear();
26048       StringRef ConstraintsStr = IA->getConstraintString();
26049       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26050       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26051       if (clobbersFlagRegisters(AsmPieces))
26052         return IntrinsicLowering::LowerToByteSwap(CI);
26053     }
26054
26055     if (CI->getType()->isIntegerTy(64)) {
26056       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26057       if (Constraints.size() >= 2 &&
26058           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26059           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26060         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
26061         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26062             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26063             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26064           return IntrinsicLowering::LowerToByteSwap(CI);
26065       }
26066     }
26067     break;
26068   }
26069   return false;
26070 }
26071
26072 /// getConstraintType - Given a constraint letter, return the type of
26073 /// constraint it is for this target.
26074 X86TargetLowering::ConstraintType
26075 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26076   if (Constraint.size() == 1) {
26077     switch (Constraint[0]) {
26078     case 'R':
26079     case 'q':
26080     case 'Q':
26081     case 'f':
26082     case 't':
26083     case 'u':
26084     case 'y':
26085     case 'x':
26086     case 'Y':
26087     case 'l':
26088       return C_RegisterClass;
26089     case 'a':
26090     case 'b':
26091     case 'c':
26092     case 'd':
26093     case 'S':
26094     case 'D':
26095     case 'A':
26096       return C_Register;
26097     case 'I':
26098     case 'J':
26099     case 'K':
26100     case 'L':
26101     case 'M':
26102     case 'N':
26103     case 'G':
26104     case 'C':
26105     case 'e':
26106     case 'Z':
26107       return C_Other;
26108     default:
26109       break;
26110     }
26111   }
26112   return TargetLowering::getConstraintType(Constraint);
26113 }
26114
26115 /// Examine constraint type and operand type and determine a weight value.
26116 /// This object must already have been set up with the operand type
26117 /// and the current alternative constraint selected.
26118 TargetLowering::ConstraintWeight
26119   X86TargetLowering::getSingleConstraintMatchWeight(
26120     AsmOperandInfo &info, const char *constraint) const {
26121   ConstraintWeight weight = CW_Invalid;
26122   Value *CallOperandVal = info.CallOperandVal;
26123     // If we don't have a value, we can't do a match,
26124     // but allow it at the lowest weight.
26125   if (!CallOperandVal)
26126     return CW_Default;
26127   Type *type = CallOperandVal->getType();
26128   // Look at the constraint type.
26129   switch (*constraint) {
26130   default:
26131     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26132   case 'R':
26133   case 'q':
26134   case 'Q':
26135   case 'a':
26136   case 'b':
26137   case 'c':
26138   case 'd':
26139   case 'S':
26140   case 'D':
26141   case 'A':
26142     if (CallOperandVal->getType()->isIntegerTy())
26143       weight = CW_SpecificReg;
26144     break;
26145   case 'f':
26146   case 't':
26147   case 'u':
26148     if (type->isFloatingPointTy())
26149       weight = CW_SpecificReg;
26150     break;
26151   case 'y':
26152     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26153       weight = CW_SpecificReg;
26154     break;
26155   case 'x':
26156   case 'Y':
26157     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26158         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26159       weight = CW_Register;
26160     break;
26161   case 'I':
26162     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26163       if (C->getZExtValue() <= 31)
26164         weight = CW_Constant;
26165     }
26166     break;
26167   case 'J':
26168     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26169       if (C->getZExtValue() <= 63)
26170         weight = CW_Constant;
26171     }
26172     break;
26173   case 'K':
26174     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26175       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26176         weight = CW_Constant;
26177     }
26178     break;
26179   case 'L':
26180     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26181       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26182         weight = CW_Constant;
26183     }
26184     break;
26185   case 'M':
26186     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26187       if (C->getZExtValue() <= 3)
26188         weight = CW_Constant;
26189     }
26190     break;
26191   case 'N':
26192     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26193       if (C->getZExtValue() <= 0xff)
26194         weight = CW_Constant;
26195     }
26196     break;
26197   case 'G':
26198   case 'C':
26199     if (isa<ConstantFP>(CallOperandVal)) {
26200       weight = CW_Constant;
26201     }
26202     break;
26203   case 'e':
26204     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26205       if ((C->getSExtValue() >= -0x80000000LL) &&
26206           (C->getSExtValue() <= 0x7fffffffLL))
26207         weight = CW_Constant;
26208     }
26209     break;
26210   case 'Z':
26211     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26212       if (C->getZExtValue() <= 0xffffffff)
26213         weight = CW_Constant;
26214     }
26215     break;
26216   }
26217   return weight;
26218 }
26219
26220 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26221 /// with another that has more specific requirements based on the type of the
26222 /// corresponding operand.
26223 const char *X86TargetLowering::
26224 LowerXConstraint(EVT ConstraintVT) const {
26225   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26226   // 'f' like normal targets.
26227   if (ConstraintVT.isFloatingPoint()) {
26228     if (Subtarget->hasSSE2())
26229       return "Y";
26230     if (Subtarget->hasSSE1())
26231       return "x";
26232   }
26233
26234   return TargetLowering::LowerXConstraint(ConstraintVT);
26235 }
26236
26237 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26238 /// vector.  If it is invalid, don't add anything to Ops.
26239 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26240                                                      std::string &Constraint,
26241                                                      std::vector<SDValue>&Ops,
26242                                                      SelectionDAG &DAG) const {
26243   SDValue Result;
26244
26245   // Only support length 1 constraints for now.
26246   if (Constraint.length() > 1) return;
26247
26248   char ConstraintLetter = Constraint[0];
26249   switch (ConstraintLetter) {
26250   default: break;
26251   case 'I':
26252     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26253       if (C->getZExtValue() <= 31) {
26254         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26255                                        Op.getValueType());
26256         break;
26257       }
26258     }
26259     return;
26260   case 'J':
26261     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26262       if (C->getZExtValue() <= 63) {
26263         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26264                                        Op.getValueType());
26265         break;
26266       }
26267     }
26268     return;
26269   case 'K':
26270     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26271       if (isInt<8>(C->getSExtValue())) {
26272         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26273                                        Op.getValueType());
26274         break;
26275       }
26276     }
26277     return;
26278   case 'L':
26279     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26280       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26281           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26282         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26283                                        Op.getValueType());
26284         break;
26285       }
26286     }
26287     return;
26288   case 'M':
26289     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26290       if (C->getZExtValue() <= 3) {
26291         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26292                                        Op.getValueType());
26293         break;
26294       }
26295     }
26296     return;
26297   case 'N':
26298     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26299       if (C->getZExtValue() <= 255) {
26300         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26301                                        Op.getValueType());
26302         break;
26303       }
26304     }
26305     return;
26306   case 'O':
26307     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26308       if (C->getZExtValue() <= 127) {
26309         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26310                                        Op.getValueType());
26311         break;
26312       }
26313     }
26314     return;
26315   case 'e': {
26316     // 32-bit signed value
26317     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26318       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26319                                            C->getSExtValue())) {
26320         // Widen to 64 bits here to get it sign extended.
26321         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26322         break;
26323       }
26324     // FIXME gcc accepts some relocatable values here too, but only in certain
26325     // memory models; it's complicated.
26326     }
26327     return;
26328   }
26329   case 'Z': {
26330     // 32-bit unsigned value
26331     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26332       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26333                                            C->getZExtValue())) {
26334         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26335                                        Op.getValueType());
26336         break;
26337       }
26338     }
26339     // FIXME gcc accepts some relocatable values here too, but only in certain
26340     // memory models; it's complicated.
26341     return;
26342   }
26343   case 'i': {
26344     // Literal immediates are always ok.
26345     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26346       // Widen to 64 bits here to get it sign extended.
26347       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26348       break;
26349     }
26350
26351     // In any sort of PIC mode addresses need to be computed at runtime by
26352     // adding in a register or some sort of table lookup.  These can't
26353     // be used as immediates.
26354     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26355       return;
26356
26357     // If we are in non-pic codegen mode, we allow the address of a global (with
26358     // an optional displacement) to be used with 'i'.
26359     GlobalAddressSDNode *GA = nullptr;
26360     int64_t Offset = 0;
26361
26362     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26363     while (1) {
26364       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26365         Offset += GA->getOffset();
26366         break;
26367       } else if (Op.getOpcode() == ISD::ADD) {
26368         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26369           Offset += C->getZExtValue();
26370           Op = Op.getOperand(0);
26371           continue;
26372         }
26373       } else if (Op.getOpcode() == ISD::SUB) {
26374         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26375           Offset += -C->getZExtValue();
26376           Op = Op.getOperand(0);
26377           continue;
26378         }
26379       }
26380
26381       // Otherwise, this isn't something we can handle, reject it.
26382       return;
26383     }
26384
26385     const GlobalValue *GV = GA->getGlobal();
26386     // If we require an extra load to get this address, as in PIC mode, we
26387     // can't accept it.
26388     if (isGlobalStubReference(
26389             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26390       return;
26391
26392     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26393                                         GA->getValueType(0), Offset);
26394     break;
26395   }
26396   }
26397
26398   if (Result.getNode()) {
26399     Ops.push_back(Result);
26400     return;
26401   }
26402   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26403 }
26404
26405 std::pair<unsigned, const TargetRegisterClass *>
26406 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26407                                                 StringRef Constraint,
26408                                                 MVT VT) const {
26409   // First, see if this is a constraint that directly corresponds to an LLVM
26410   // register class.
26411   if (Constraint.size() == 1) {
26412     // GCC Constraint Letters
26413     switch (Constraint[0]) {
26414     default: break;
26415       // TODO: Slight differences here in allocation order and leaving
26416       // RIP in the class. Do they matter any more here than they do
26417       // in the normal allocation?
26418     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26419       if (Subtarget->is64Bit()) {
26420         if (VT == MVT::i32 || VT == MVT::f32)
26421           return std::make_pair(0U, &X86::GR32RegClass);
26422         if (VT == MVT::i16)
26423           return std::make_pair(0U, &X86::GR16RegClass);
26424         if (VT == MVT::i8 || VT == MVT::i1)
26425           return std::make_pair(0U, &X86::GR8RegClass);
26426         if (VT == MVT::i64 || VT == MVT::f64)
26427           return std::make_pair(0U, &X86::GR64RegClass);
26428         break;
26429       }
26430       // 32-bit fallthrough
26431     case 'Q':   // Q_REGS
26432       if (VT == MVT::i32 || VT == MVT::f32)
26433         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26434       if (VT == MVT::i16)
26435         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26436       if (VT == MVT::i8 || VT == MVT::i1)
26437         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26438       if (VT == MVT::i64)
26439         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26440       break;
26441     case 'r':   // GENERAL_REGS
26442     case 'l':   // INDEX_REGS
26443       if (VT == MVT::i8 || VT == MVT::i1)
26444         return std::make_pair(0U, &X86::GR8RegClass);
26445       if (VT == MVT::i16)
26446         return std::make_pair(0U, &X86::GR16RegClass);
26447       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26448         return std::make_pair(0U, &X86::GR32RegClass);
26449       return std::make_pair(0U, &X86::GR64RegClass);
26450     case 'R':   // LEGACY_REGS
26451       if (VT == MVT::i8 || VT == MVT::i1)
26452         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26453       if (VT == MVT::i16)
26454         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26455       if (VT == MVT::i32 || !Subtarget->is64Bit())
26456         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26457       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26458     case 'f':  // FP Stack registers.
26459       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26460       // value to the correct fpstack register class.
26461       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26462         return std::make_pair(0U, &X86::RFP32RegClass);
26463       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26464         return std::make_pair(0U, &X86::RFP64RegClass);
26465       return std::make_pair(0U, &X86::RFP80RegClass);
26466     case 'y':   // MMX_REGS if MMX allowed.
26467       if (!Subtarget->hasMMX()) break;
26468       return std::make_pair(0U, &X86::VR64RegClass);
26469     case 'Y':   // SSE_REGS if SSE2 allowed
26470       if (!Subtarget->hasSSE2()) break;
26471       // FALL THROUGH.
26472     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26473       if (!Subtarget->hasSSE1()) break;
26474
26475       switch (VT.SimpleTy) {
26476       default: break;
26477       // Scalar SSE types.
26478       case MVT::f32:
26479       case MVT::i32:
26480         return std::make_pair(0U, &X86::FR32RegClass);
26481       case MVT::f64:
26482       case MVT::i64:
26483         return std::make_pair(0U, &X86::FR64RegClass);
26484       // Vector types.
26485       case MVT::v16i8:
26486       case MVT::v8i16:
26487       case MVT::v4i32:
26488       case MVT::v2i64:
26489       case MVT::v4f32:
26490       case MVT::v2f64:
26491         return std::make_pair(0U, &X86::VR128RegClass);
26492       // AVX types.
26493       case MVT::v32i8:
26494       case MVT::v16i16:
26495       case MVT::v8i32:
26496       case MVT::v4i64:
26497       case MVT::v8f32:
26498       case MVT::v4f64:
26499         return std::make_pair(0U, &X86::VR256RegClass);
26500       case MVT::v8f64:
26501       case MVT::v16f32:
26502       case MVT::v16i32:
26503       case MVT::v8i64:
26504         return std::make_pair(0U, &X86::VR512RegClass);
26505       }
26506       break;
26507     }
26508   }
26509
26510   // Use the default implementation in TargetLowering to convert the register
26511   // constraint into a member of a register class.
26512   std::pair<unsigned, const TargetRegisterClass*> Res;
26513   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26514
26515   // Not found as a standard register?
26516   if (!Res.second) {
26517     // Map st(0) -> st(7) -> ST0
26518     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26519         tolower(Constraint[1]) == 's' &&
26520         tolower(Constraint[2]) == 't' &&
26521         Constraint[3] == '(' &&
26522         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26523         Constraint[5] == ')' &&
26524         Constraint[6] == '}') {
26525
26526       Res.first = X86::FP0+Constraint[4]-'0';
26527       Res.second = &X86::RFP80RegClass;
26528       return Res;
26529     }
26530
26531     // GCC allows "st(0)" to be called just plain "st".
26532     if (StringRef("{st}").equals_lower(Constraint)) {
26533       Res.first = X86::FP0;
26534       Res.second = &X86::RFP80RegClass;
26535       return Res;
26536     }
26537
26538     // flags -> EFLAGS
26539     if (StringRef("{flags}").equals_lower(Constraint)) {
26540       Res.first = X86::EFLAGS;
26541       Res.second = &X86::CCRRegClass;
26542       return Res;
26543     }
26544
26545     // 'A' means EAX + EDX.
26546     if (Constraint == "A") {
26547       Res.first = X86::EAX;
26548       Res.second = &X86::GR32_ADRegClass;
26549       return Res;
26550     }
26551     return Res;
26552   }
26553
26554   // Otherwise, check to see if this is a register class of the wrong value
26555   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26556   // turn into {ax},{dx}.
26557   // MVT::Other is used to specify clobber names.
26558   if (Res.second->hasType(VT) || VT == MVT::Other)
26559     return Res;   // Correct type already, nothing to do.
26560
26561   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26562   // return "eax". This should even work for things like getting 64bit integer
26563   // registers when given an f64 type.
26564   const TargetRegisterClass *Class = Res.second;
26565   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26566       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26567     unsigned Size = VT.getSizeInBits();
26568     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26569                                   : Size == 16 ? MVT::i16
26570                                   : Size == 32 ? MVT::i32
26571                                   : Size == 64 ? MVT::i64
26572                                   : MVT::Other;
26573     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26574     if (DestReg > 0) {
26575       Res.first = DestReg;
26576       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26577                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26578                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26579                  : &X86::GR64RegClass;
26580       assert(Res.second->contains(Res.first) && "Register in register class");
26581     } else {
26582       // No register found/type mismatch.
26583       Res.first = 0;
26584       Res.second = nullptr;
26585     }
26586   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26587              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26588              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26589              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26590              Class == &X86::VR512RegClass) {
26591     // Handle references to XMM physical registers that got mapped into the
26592     // wrong class.  This can happen with constraints like {xmm0} where the
26593     // target independent register mapper will just pick the first match it can
26594     // find, ignoring the required type.
26595
26596     if (VT == MVT::f32 || VT == MVT::i32)
26597       Res.second = &X86::FR32RegClass;
26598     else if (VT == MVT::f64 || VT == MVT::i64)
26599       Res.second = &X86::FR64RegClass;
26600     else if (X86::VR128RegClass.hasType(VT))
26601       Res.second = &X86::VR128RegClass;
26602     else if (X86::VR256RegClass.hasType(VT))
26603       Res.second = &X86::VR256RegClass;
26604     else if (X86::VR512RegClass.hasType(VT))
26605       Res.second = &X86::VR512RegClass;
26606     else {
26607       // Type mismatch and not a clobber: Return an error;
26608       Res.first = 0;
26609       Res.second = nullptr;
26610     }
26611   }
26612
26613   return Res;
26614 }
26615
26616 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26617                                             const AddrMode &AM, Type *Ty,
26618                                             unsigned AS) const {
26619   // Scaling factors are not free at all.
26620   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26621   // will take 2 allocations in the out of order engine instead of 1
26622   // for plain addressing mode, i.e. inst (reg1).
26623   // E.g.,
26624   // vaddps (%rsi,%drx), %ymm0, %ymm1
26625   // Requires two allocations (one for the load, one for the computation)
26626   // whereas:
26627   // vaddps (%rsi), %ymm0, %ymm1
26628   // Requires just 1 allocation, i.e., freeing allocations for other operations
26629   // and having less micro operations to execute.
26630   //
26631   // For some X86 architectures, this is even worse because for instance for
26632   // stores, the complex addressing mode forces the instruction to use the
26633   // "load" ports instead of the dedicated "store" port.
26634   // E.g., on Haswell:
26635   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26636   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26637   if (isLegalAddressingMode(DL, AM, Ty, AS))
26638     // Scale represents reg2 * scale, thus account for 1
26639     // as soon as we use a second register.
26640     return AM.Scale != 0;
26641   return -1;
26642 }
26643
26644 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
26645   // Integer division on x86 is expensive. However, when aggressively optimizing
26646   // for code size, we prefer to use a div instruction, as it is usually smaller
26647   // than the alternative sequence.
26648   // The exception to this is vector division. Since x86 doesn't have vector
26649   // integer division, leaving the division as-is is a loss even in terms of
26650   // size, because it will have to be scalarized, while the alternative code
26651   // sequence can be performed in vector form.
26652   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
26653                                    Attribute::MinSize);
26654   return OptSize && !VT.isVector();
26655 }