[x86] fix allowsMisalignedMemoryAccesses() for 8-byte and smaller accesses
[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     switch (VT.getSizeInBits()) {
1927     default:
1928       // 8-byte and under are always assumed to be fast.
1929       *Fast = true;
1930       break;
1931     case 128:
1932       *Fast = !Subtarget->isUnalignedMem16Slow();
1933       break;
1934     case 256:
1935       *Fast = !Subtarget->isUnalignedMem32Slow();
1936       break;
1937     // TODO: What about AVX-512 (512-bit) accesses?
1938     }
1939   }
1940   // Misaligned accesses of any size are always allowed.
1941   return true;
1942 }
1943
1944 /// Return the entry encoding for a jump table in the
1945 /// current function.  The returned value is a member of the
1946 /// MachineJumpTableInfo::JTEntryKind enum.
1947 unsigned X86TargetLowering::getJumpTableEncoding() const {
1948   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1949   // symbol.
1950   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1951       Subtarget->isPICStyleGOT())
1952     return MachineJumpTableInfo::EK_Custom32;
1953
1954   // Otherwise, use the normal jump table encoding heuristics.
1955   return TargetLowering::getJumpTableEncoding();
1956 }
1957
1958 bool X86TargetLowering::useSoftFloat() const {
1959   return Subtarget->useSoftFloat();
1960 }
1961
1962 const MCExpr *
1963 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1964                                              const MachineBasicBlock *MBB,
1965                                              unsigned uid,MCContext &Ctx) const{
1966   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1967          Subtarget->isPICStyleGOT());
1968   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1969   // entries.
1970   return MCSymbolRefExpr::create(MBB->getSymbol(),
1971                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1972 }
1973
1974 /// Returns relocation base for the given PIC jumptable.
1975 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1976                                                     SelectionDAG &DAG) const {
1977   if (!Subtarget->is64Bit())
1978     // This doesn't have SDLoc associated with it, but is not really the
1979     // same as a Register.
1980     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1981                        getPointerTy(DAG.getDataLayout()));
1982   return Table;
1983 }
1984
1985 /// This returns the relocation base for the given PIC jumptable,
1986 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1987 const MCExpr *X86TargetLowering::
1988 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1989                              MCContext &Ctx) const {
1990   // X86-64 uses RIP relative addressing based on the jump table label.
1991   if (Subtarget->isPICStyleRIPRel())
1992     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1993
1994   // Otherwise, the reference is relative to the PIC base.
1995   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1996 }
1997
1998 std::pair<const TargetRegisterClass *, uint8_t>
1999 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2000                                            MVT VT) const {
2001   const TargetRegisterClass *RRC = nullptr;
2002   uint8_t Cost = 1;
2003   switch (VT.SimpleTy) {
2004   default:
2005     return TargetLowering::findRepresentativeClass(TRI, VT);
2006   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2007     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2008     break;
2009   case MVT::x86mmx:
2010     RRC = &X86::VR64RegClass;
2011     break;
2012   case MVT::f32: case MVT::f64:
2013   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2014   case MVT::v4f32: case MVT::v2f64:
2015   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2016   case MVT::v4f64:
2017     RRC = &X86::VR128RegClass;
2018     break;
2019   }
2020   return std::make_pair(RRC, Cost);
2021 }
2022
2023 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2024                                                unsigned &Offset) const {
2025   if (!Subtarget->isTargetLinux())
2026     return false;
2027
2028   if (Subtarget->is64Bit()) {
2029     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2030     Offset = 0x28;
2031     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2032       AddressSpace = 256;
2033     else
2034       AddressSpace = 257;
2035   } else {
2036     // %gs:0x14 on i386
2037     Offset = 0x14;
2038     AddressSpace = 256;
2039   }
2040   return true;
2041 }
2042
2043 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2044                                             unsigned DestAS) const {
2045   assert(SrcAS != DestAS && "Expected different address spaces!");
2046
2047   return SrcAS < 256 && DestAS < 256;
2048 }
2049
2050 //===----------------------------------------------------------------------===//
2051 //               Return Value Calling Convention Implementation
2052 //===----------------------------------------------------------------------===//
2053
2054 #include "X86GenCallingConv.inc"
2055
2056 bool
2057 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2058                                   MachineFunction &MF, bool isVarArg,
2059                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2060                         LLVMContext &Context) const {
2061   SmallVector<CCValAssign, 16> RVLocs;
2062   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2063   return CCInfo.CheckReturn(Outs, RetCC_X86);
2064 }
2065
2066 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2067   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2068   return ScratchRegs;
2069 }
2070
2071 SDValue
2072 X86TargetLowering::LowerReturn(SDValue Chain,
2073                                CallingConv::ID CallConv, bool isVarArg,
2074                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2075                                const SmallVectorImpl<SDValue> &OutVals,
2076                                SDLoc dl, SelectionDAG &DAG) const {
2077   MachineFunction &MF = DAG.getMachineFunction();
2078   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2079
2080   SmallVector<CCValAssign, 16> RVLocs;
2081   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2082   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2083
2084   SDValue Flag;
2085   SmallVector<SDValue, 6> RetOps;
2086   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2087   // Operand #1 = Bytes To Pop
2088   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2089                    MVT::i16));
2090
2091   // Copy the result values into the output registers.
2092   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2093     CCValAssign &VA = RVLocs[i];
2094     assert(VA.isRegLoc() && "Can only return in registers!");
2095     SDValue ValToCopy = OutVals[i];
2096     EVT ValVT = ValToCopy.getValueType();
2097
2098     // Promote values to the appropriate types.
2099     if (VA.getLocInfo() == CCValAssign::SExt)
2100       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2101     else if (VA.getLocInfo() == CCValAssign::ZExt)
2102       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2103     else if (VA.getLocInfo() == CCValAssign::AExt) {
2104       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2105         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2106       else
2107         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2108     }
2109     else if (VA.getLocInfo() == CCValAssign::BCvt)
2110       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2111
2112     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2113            "Unexpected FP-extend for return value.");
2114
2115     // If this is x86-64, and we disabled SSE, we can't return FP values,
2116     // or SSE or MMX vectors.
2117     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2118          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2119           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2120       report_fatal_error("SSE register return with SSE disabled");
2121     }
2122     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2123     // llvm-gcc has never done it right and no one has noticed, so this
2124     // should be OK for now.
2125     if (ValVT == MVT::f64 &&
2126         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2127       report_fatal_error("SSE2 register return with SSE2 disabled");
2128
2129     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2130     // the RET instruction and handled by the FP Stackifier.
2131     if (VA.getLocReg() == X86::FP0 ||
2132         VA.getLocReg() == X86::FP1) {
2133       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2134       // change the value to the FP stack register class.
2135       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2136         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2137       RetOps.push_back(ValToCopy);
2138       // Don't emit a copytoreg.
2139       continue;
2140     }
2141
2142     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2143     // which is returned in RAX / RDX.
2144     if (Subtarget->is64Bit()) {
2145       if (ValVT == MVT::x86mmx) {
2146         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2147           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2148           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2149                                   ValToCopy);
2150           // If we don't have SSE2 available, convert to v4f32 so the generated
2151           // register is legal.
2152           if (!Subtarget->hasSSE2())
2153             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2154         }
2155       }
2156     }
2157
2158     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2159     Flag = Chain.getValue(1);
2160     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2161   }
2162
2163   // All x86 ABIs require that for returning structs by value we copy
2164   // the sret argument into %rax/%eax (depending on ABI) for the return.
2165   // We saved the argument into a virtual register in the entry block,
2166   // so now we copy the value out and into %rax/%eax.
2167   //
2168   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2169   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2170   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2171   // either case FuncInfo->setSRetReturnReg() will have been called.
2172   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2173     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2174                                      getPointerTy(MF.getDataLayout()));
2175
2176     unsigned RetValReg
2177         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2178           X86::RAX : X86::EAX;
2179     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2180     Flag = Chain.getValue(1);
2181
2182     // RAX/EAX now acts like a return value.
2183     RetOps.push_back(
2184         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2185   }
2186
2187   RetOps[0] = Chain;  // Update chain.
2188
2189   // Add the flag if we have it.
2190   if (Flag.getNode())
2191     RetOps.push_back(Flag);
2192
2193   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2194 }
2195
2196 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2197   if (N->getNumValues() != 1)
2198     return false;
2199   if (!N->hasNUsesOfValue(1, 0))
2200     return false;
2201
2202   SDValue TCChain = Chain;
2203   SDNode *Copy = *N->use_begin();
2204   if (Copy->getOpcode() == ISD::CopyToReg) {
2205     // If the copy has a glue operand, we conservatively assume it isn't safe to
2206     // perform a tail call.
2207     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2208       return false;
2209     TCChain = Copy->getOperand(0);
2210   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2211     return false;
2212
2213   bool HasRet = false;
2214   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2215        UI != UE; ++UI) {
2216     if (UI->getOpcode() != X86ISD::RET_FLAG)
2217       return false;
2218     // If we are returning more than one value, we can definitely
2219     // not make a tail call see PR19530
2220     if (UI->getNumOperands() > 4)
2221       return false;
2222     if (UI->getNumOperands() == 4 &&
2223         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2224       return false;
2225     HasRet = true;
2226   }
2227
2228   if (!HasRet)
2229     return false;
2230
2231   Chain = TCChain;
2232   return true;
2233 }
2234
2235 EVT
2236 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2237                                             ISD::NodeType ExtendKind) const {
2238   MVT ReturnMVT;
2239   // TODO: Is this also valid on 32-bit?
2240   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2241     ReturnMVT = MVT::i8;
2242   else
2243     ReturnMVT = MVT::i32;
2244
2245   EVT MinVT = getRegisterType(Context, ReturnMVT);
2246   return VT.bitsLT(MinVT) ? MinVT : VT;
2247 }
2248
2249 /// Lower the result values of a call into the
2250 /// appropriate copies out of appropriate physical registers.
2251 ///
2252 SDValue
2253 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2254                                    CallingConv::ID CallConv, bool isVarArg,
2255                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2256                                    SDLoc dl, SelectionDAG &DAG,
2257                                    SmallVectorImpl<SDValue> &InVals) const {
2258
2259   // Assign locations to each value returned by this call.
2260   SmallVector<CCValAssign, 16> RVLocs;
2261   bool Is64Bit = Subtarget->is64Bit();
2262   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2263                  *DAG.getContext());
2264   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2265
2266   // Copy all of the result registers out of their specified physreg.
2267   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2268     CCValAssign &VA = RVLocs[i];
2269     EVT CopyVT = VA.getLocVT();
2270
2271     // If this is x86-64, and we disabled SSE, we can't return FP values
2272     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2273         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2274       report_fatal_error("SSE register return with SSE disabled");
2275     }
2276
2277     // If we prefer to use the value in xmm registers, copy it out as f80 and
2278     // use a truncate to move it from fp stack reg to xmm reg.
2279     bool RoundAfterCopy = false;
2280     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2281         isScalarFPTypeInSSEReg(VA.getValVT())) {
2282       CopyVT = MVT::f80;
2283       RoundAfterCopy = (CopyVT != VA.getLocVT());
2284     }
2285
2286     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2287                                CopyVT, InFlag).getValue(1);
2288     SDValue Val = Chain.getValue(0);
2289
2290     if (RoundAfterCopy)
2291       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2292                         // This truncation won't change the value.
2293                         DAG.getIntPtrConstant(1, dl));
2294
2295     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2296       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2297
2298     InFlag = Chain.getValue(2);
2299     InVals.push_back(Val);
2300   }
2301
2302   return Chain;
2303 }
2304
2305 //===----------------------------------------------------------------------===//
2306 //                C & StdCall & Fast Calling Convention implementation
2307 //===----------------------------------------------------------------------===//
2308 //  StdCall calling convention seems to be standard for many Windows' API
2309 //  routines and around. It differs from C calling convention just a little:
2310 //  callee should clean up the stack, not caller. Symbols should be also
2311 //  decorated in some fancy way :) It doesn't support any vector arguments.
2312 //  For info on fast calling convention see Fast Calling Convention (tail call)
2313 //  implementation LowerX86_32FastCCCallTo.
2314
2315 /// CallIsStructReturn - Determines whether a call uses struct return
2316 /// semantics.
2317 enum StructReturnType {
2318   NotStructReturn,
2319   RegStructReturn,
2320   StackStructReturn
2321 };
2322 static StructReturnType
2323 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2324   if (Outs.empty())
2325     return NotStructReturn;
2326
2327   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2328   if (!Flags.isSRet())
2329     return NotStructReturn;
2330   if (Flags.isInReg())
2331     return RegStructReturn;
2332   return StackStructReturn;
2333 }
2334
2335 /// Determines whether a function uses struct return semantics.
2336 static StructReturnType
2337 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2338   if (Ins.empty())
2339     return NotStructReturn;
2340
2341   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2342   if (!Flags.isSRet())
2343     return NotStructReturn;
2344   if (Flags.isInReg())
2345     return RegStructReturn;
2346   return StackStructReturn;
2347 }
2348
2349 /// Make a copy of an aggregate at address specified by "Src" to address
2350 /// "Dst" with size and alignment information specified by the specific
2351 /// parameter attribute. The copy will be passed as a byval function parameter.
2352 static SDValue
2353 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2354                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2355                           SDLoc dl) {
2356   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2357
2358   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2359                        /*isVolatile*/false, /*AlwaysInline=*/true,
2360                        /*isTailCall*/false,
2361                        MachinePointerInfo(), MachinePointerInfo());
2362 }
2363
2364 /// Return true if the calling convention is one that
2365 /// supports tail call optimization.
2366 static bool IsTailCallConvention(CallingConv::ID CC) {
2367   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2368           CC == CallingConv::HiPE);
2369 }
2370
2371 /// \brief Return true if the calling convention is a C calling convention.
2372 static bool IsCCallConvention(CallingConv::ID CC) {
2373   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2374           CC == CallingConv::X86_64_SysV);
2375 }
2376
2377 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2378   auto Attr =
2379       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2380   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2381     return false;
2382
2383   CallSite CS(CI);
2384   CallingConv::ID CalleeCC = CS.getCallingConv();
2385   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2386     return false;
2387
2388   return true;
2389 }
2390
2391 /// Return true if the function is being made into
2392 /// a tailcall target by changing its ABI.
2393 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2394                                    bool GuaranteedTailCallOpt) {
2395   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2396 }
2397
2398 SDValue
2399 X86TargetLowering::LowerMemArgument(SDValue Chain,
2400                                     CallingConv::ID CallConv,
2401                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2402                                     SDLoc dl, SelectionDAG &DAG,
2403                                     const CCValAssign &VA,
2404                                     MachineFrameInfo *MFI,
2405                                     unsigned i) const {
2406   // Create the nodes corresponding to a load from this parameter slot.
2407   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2408   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2409       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2410   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2411   EVT ValVT;
2412
2413   // If value is passed by pointer we have address passed instead of the value
2414   // itself.
2415   bool ExtendedInMem = VA.isExtInLoc() &&
2416     VA.getValVT().getScalarType() == MVT::i1;
2417
2418   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2419     ValVT = VA.getLocVT();
2420   else
2421     ValVT = VA.getValVT();
2422
2423   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2424   // changed with more analysis.
2425   // In case of tail call optimization mark all arguments mutable. Since they
2426   // could be overwritten by lowering of arguments in case of a tail call.
2427   if (Flags.isByVal()) {
2428     unsigned Bytes = Flags.getByValSize();
2429     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2430     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2431     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2432   } else {
2433     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2434                                     VA.getLocMemOffset(), isImmutable);
2435     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2436     SDValue Val = DAG.getLoad(
2437         ValVT, dl, Chain, FIN,
2438         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2439         false, false, 0);
2440     return ExtendedInMem ?
2441       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2442   }
2443 }
2444
2445 // FIXME: Get this from tablegen.
2446 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2447                                                 const X86Subtarget *Subtarget) {
2448   assert(Subtarget->is64Bit());
2449
2450   if (Subtarget->isCallingConvWin64(CallConv)) {
2451     static const MCPhysReg GPR64ArgRegsWin64[] = {
2452       X86::RCX, X86::RDX, X86::R8,  X86::R9
2453     };
2454     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2455   }
2456
2457   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2458     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2459   };
2460   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2461 }
2462
2463 // FIXME: Get this from tablegen.
2464 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2465                                                 CallingConv::ID CallConv,
2466                                                 const X86Subtarget *Subtarget) {
2467   assert(Subtarget->is64Bit());
2468   if (Subtarget->isCallingConvWin64(CallConv)) {
2469     // The XMM registers which might contain var arg parameters are shadowed
2470     // in their paired GPR.  So we only need to save the GPR to their home
2471     // slots.
2472     // TODO: __vectorcall will change this.
2473     return None;
2474   }
2475
2476   const Function *Fn = MF.getFunction();
2477   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2478   bool isSoftFloat = Subtarget->useSoftFloat();
2479   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2480          "SSE register cannot be used when SSE is disabled!");
2481   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2482     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2483     // registers.
2484     return None;
2485
2486   static const MCPhysReg XMMArgRegs64Bit[] = {
2487     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2488     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2489   };
2490   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2491 }
2492
2493 SDValue
2494 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2495                                         CallingConv::ID CallConv,
2496                                         bool isVarArg,
2497                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2498                                         SDLoc dl,
2499                                         SelectionDAG &DAG,
2500                                         SmallVectorImpl<SDValue> &InVals)
2501                                           const {
2502   MachineFunction &MF = DAG.getMachineFunction();
2503   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2504   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2505
2506   const Function* Fn = MF.getFunction();
2507   if (Fn->hasExternalLinkage() &&
2508       Subtarget->isTargetCygMing() &&
2509       Fn->getName() == "main")
2510     FuncInfo->setForceFramePointer(true);
2511
2512   MachineFrameInfo *MFI = MF.getFrameInfo();
2513   bool Is64Bit = Subtarget->is64Bit();
2514   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2515
2516   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2517          "Var args not supported with calling convention fastcc, ghc or hipe");
2518
2519   // Assign locations to all of the incoming arguments.
2520   SmallVector<CCValAssign, 16> ArgLocs;
2521   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2522
2523   // Allocate shadow area for Win64
2524   if (IsWin64)
2525     CCInfo.AllocateStack(32, 8);
2526
2527   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2528
2529   unsigned LastVal = ~0U;
2530   SDValue ArgValue;
2531   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2532     CCValAssign &VA = ArgLocs[i];
2533     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2534     // places.
2535     assert(VA.getValNo() != LastVal &&
2536            "Don't support value assigned to multiple locs yet");
2537     (void)LastVal;
2538     LastVal = VA.getValNo();
2539
2540     if (VA.isRegLoc()) {
2541       EVT RegVT = VA.getLocVT();
2542       const TargetRegisterClass *RC;
2543       if (RegVT == MVT::i32)
2544         RC = &X86::GR32RegClass;
2545       else if (Is64Bit && RegVT == MVT::i64)
2546         RC = &X86::GR64RegClass;
2547       else if (RegVT == MVT::f32)
2548         RC = &X86::FR32RegClass;
2549       else if (RegVT == MVT::f64)
2550         RC = &X86::FR64RegClass;
2551       else if (RegVT.is512BitVector())
2552         RC = &X86::VR512RegClass;
2553       else if (RegVT.is256BitVector())
2554         RC = &X86::VR256RegClass;
2555       else if (RegVT.is128BitVector())
2556         RC = &X86::VR128RegClass;
2557       else if (RegVT == MVT::x86mmx)
2558         RC = &X86::VR64RegClass;
2559       else if (RegVT == MVT::i1)
2560         RC = &X86::VK1RegClass;
2561       else if (RegVT == MVT::v8i1)
2562         RC = &X86::VK8RegClass;
2563       else if (RegVT == MVT::v16i1)
2564         RC = &X86::VK16RegClass;
2565       else if (RegVT == MVT::v32i1)
2566         RC = &X86::VK32RegClass;
2567       else if (RegVT == MVT::v64i1)
2568         RC = &X86::VK64RegClass;
2569       else
2570         llvm_unreachable("Unknown argument type!");
2571
2572       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2573       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2574
2575       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2576       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2577       // right size.
2578       if (VA.getLocInfo() == CCValAssign::SExt)
2579         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2580                                DAG.getValueType(VA.getValVT()));
2581       else if (VA.getLocInfo() == CCValAssign::ZExt)
2582         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2583                                DAG.getValueType(VA.getValVT()));
2584       else if (VA.getLocInfo() == CCValAssign::BCvt)
2585         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2586
2587       if (VA.isExtInLoc()) {
2588         // Handle MMX values passed in XMM regs.
2589         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2590           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2591         else
2592           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2593       }
2594     } else {
2595       assert(VA.isMemLoc());
2596       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2597     }
2598
2599     // If value is passed via pointer - do a load.
2600     if (VA.getLocInfo() == CCValAssign::Indirect)
2601       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2602                              MachinePointerInfo(), false, false, false, 0);
2603
2604     InVals.push_back(ArgValue);
2605   }
2606
2607   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2608     // All x86 ABIs require that for returning structs by value we copy the
2609     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2610     // the argument into a virtual register so that we can access it from the
2611     // return points.
2612     if (Ins[i].Flags.isSRet()) {
2613       unsigned Reg = FuncInfo->getSRetReturnReg();
2614       if (!Reg) {
2615         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2616         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2617         FuncInfo->setSRetReturnReg(Reg);
2618       }
2619       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2620       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2621       break;
2622     }
2623   }
2624
2625   unsigned StackSize = CCInfo.getNextStackOffset();
2626   // Align stack specially for tail calls.
2627   if (FuncIsMadeTailCallSafe(CallConv,
2628                              MF.getTarget().Options.GuaranteedTailCallOpt))
2629     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2630
2631   // If the function takes variable number of arguments, make a frame index for
2632   // the start of the first vararg value... for expansion of llvm.va_start. We
2633   // can skip this if there are no va_start calls.
2634   if (MFI->hasVAStart() &&
2635       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2636                    CallConv != CallingConv::X86_ThisCall))) {
2637     FuncInfo->setVarArgsFrameIndex(
2638         MFI->CreateFixedObject(1, StackSize, true));
2639   }
2640
2641   MachineModuleInfo &MMI = MF.getMMI();
2642   const Function *WinEHParent = nullptr;
2643   if (MMI.hasWinEHFuncInfo(Fn))
2644     WinEHParent = MMI.getWinEHParent(Fn);
2645   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2646   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2647
2648   // Figure out if XMM registers are in use.
2649   assert(!(Subtarget->useSoftFloat() &&
2650            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2651          "SSE register cannot be used when SSE is disabled!");
2652
2653   // 64-bit calling conventions support varargs and register parameters, so we
2654   // have to do extra work to spill them in the prologue.
2655   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2656     // Find the first unallocated argument registers.
2657     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2658     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2659     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2660     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2661     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2662            "SSE register cannot be used when SSE is disabled!");
2663
2664     // Gather all the live in physical registers.
2665     SmallVector<SDValue, 6> LiveGPRs;
2666     SmallVector<SDValue, 8> LiveXMMRegs;
2667     SDValue ALVal;
2668     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2669       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2670       LiveGPRs.push_back(
2671           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2672     }
2673     if (!ArgXMMs.empty()) {
2674       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2675       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2676       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2677         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2678         LiveXMMRegs.push_back(
2679             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2680       }
2681     }
2682
2683     if (IsWin64) {
2684       // Get to the caller-allocated home save location.  Add 8 to account
2685       // for the return address.
2686       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2687       FuncInfo->setRegSaveFrameIndex(
2688           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2689       // Fixup to set vararg frame on shadow area (4 x i64).
2690       if (NumIntRegs < 4)
2691         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2692     } else {
2693       // For X86-64, if there are vararg parameters that are passed via
2694       // registers, then we must store them to their spots on the stack so
2695       // they may be loaded by deferencing the result of va_next.
2696       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2697       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2698       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2699           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2700     }
2701
2702     // Store the integer parameter registers.
2703     SmallVector<SDValue, 8> MemOps;
2704     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2705                                       getPointerTy(DAG.getDataLayout()));
2706     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2707     for (SDValue Val : LiveGPRs) {
2708       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2709                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2710       SDValue Store =
2711           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2712                        MachinePointerInfo::getFixedStack(
2713                            DAG.getMachineFunction(),
2714                            FuncInfo->getRegSaveFrameIndex(), Offset),
2715                        false, false, 0);
2716       MemOps.push_back(Store);
2717       Offset += 8;
2718     }
2719
2720     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2721       // Now store the XMM (fp + vector) parameter registers.
2722       SmallVector<SDValue, 12> SaveXMMOps;
2723       SaveXMMOps.push_back(Chain);
2724       SaveXMMOps.push_back(ALVal);
2725       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2726                              FuncInfo->getRegSaveFrameIndex(), dl));
2727       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2728                              FuncInfo->getVarArgsFPOffset(), dl));
2729       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2730                         LiveXMMRegs.end());
2731       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2732                                    MVT::Other, SaveXMMOps));
2733     }
2734
2735     if (!MemOps.empty())
2736       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2737   } else if (IsWin64 && IsWinEHOutlined) {
2738     // Get to the caller-allocated home save location.  Add 8 to account
2739     // for the return address.
2740     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2741     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2742         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2743
2744     MMI.getWinEHFuncInfo(Fn)
2745         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2746         FuncInfo->getRegSaveFrameIndex();
2747
2748     // Store the second integer parameter (rdx) into rsp+16 relative to the
2749     // stack pointer at the entry of the function.
2750     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2751                                       getPointerTy(DAG.getDataLayout()));
2752     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2753     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2754     Chain = DAG.getStore(
2755         Val.getValue(1), dl, Val, RSFIN,
2756         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2757                                           FuncInfo->getRegSaveFrameIndex()),
2758         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2759   }
2760
2761   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2762     // Find the largest legal vector type.
2763     MVT VecVT = MVT::Other;
2764     // FIXME: Only some x86_32 calling conventions support AVX512.
2765     if (Subtarget->hasAVX512() &&
2766         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2767                      CallConv == CallingConv::Intel_OCL_BI)))
2768       VecVT = MVT::v16f32;
2769     else if (Subtarget->hasAVX())
2770       VecVT = MVT::v8f32;
2771     else if (Subtarget->hasSSE2())
2772       VecVT = MVT::v4f32;
2773
2774     // We forward some GPRs and some vector types.
2775     SmallVector<MVT, 2> RegParmTypes;
2776     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2777     RegParmTypes.push_back(IntVT);
2778     if (VecVT != MVT::Other)
2779       RegParmTypes.push_back(VecVT);
2780
2781     // Compute the set of forwarded registers. The rest are scratch.
2782     SmallVectorImpl<ForwardedRegister> &Forwards =
2783         FuncInfo->getForwardedMustTailRegParms();
2784     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2785
2786     // Conservatively forward AL on x86_64, since it might be used for varargs.
2787     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2788       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2789       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2790     }
2791
2792     // Copy all forwards from physical to virtual registers.
2793     for (ForwardedRegister &F : Forwards) {
2794       // FIXME: Can we use a less constrained schedule?
2795       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2796       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2797       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2798     }
2799   }
2800
2801   // Some CCs need callee pop.
2802   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2803                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2804     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2805   } else {
2806     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2807     // If this is an sret function, the return should pop the hidden pointer.
2808     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2809         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2810         argsAreStructReturn(Ins) == StackStructReturn)
2811       FuncInfo->setBytesToPopOnReturn(4);
2812   }
2813
2814   if (!Is64Bit) {
2815     // RegSaveFrameIndex is X86-64 only.
2816     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2817     if (CallConv == CallingConv::X86_FastCall ||
2818         CallConv == CallingConv::X86_ThisCall)
2819       // fastcc functions can't have varargs.
2820       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2821   }
2822
2823   FuncInfo->setArgumentStackSize(StackSize);
2824
2825   if (IsWinEHParent) {
2826     if (Is64Bit) {
2827       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2828       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2829       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2830       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2831       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2832                            MachinePointerInfo::getFixedStack(
2833                                DAG.getMachineFunction(), UnwindHelpFI),
2834                            /*isVolatile=*/true,
2835                            /*isNonTemporal=*/false, /*Alignment=*/0);
2836     } else {
2837       // Functions using Win32 EH are considered to have opaque SP adjustments
2838       // to force local variables to be addressed from the frame or base
2839       // pointers.
2840       MFI->setHasOpaqueSPAdjustment(true);
2841     }
2842   }
2843
2844   return Chain;
2845 }
2846
2847 SDValue
2848 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2849                                     SDValue StackPtr, SDValue Arg,
2850                                     SDLoc dl, SelectionDAG &DAG,
2851                                     const CCValAssign &VA,
2852                                     ISD::ArgFlagsTy Flags) const {
2853   unsigned LocMemOffset = VA.getLocMemOffset();
2854   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2855   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2856                        StackPtr, PtrOff);
2857   if (Flags.isByVal())
2858     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2859
2860   return DAG.getStore(
2861       Chain, dl, Arg, PtrOff,
2862       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2863       false, false, 0);
2864 }
2865
2866 /// Emit a load of return address if tail call
2867 /// optimization is performed and it is required.
2868 SDValue
2869 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2870                                            SDValue &OutRetAddr, SDValue Chain,
2871                                            bool IsTailCall, bool Is64Bit,
2872                                            int FPDiff, SDLoc dl) const {
2873   // Adjust the Return address stack slot.
2874   EVT VT = getPointerTy(DAG.getDataLayout());
2875   OutRetAddr = getReturnAddressFrameIndex(DAG);
2876
2877   // Load the "old" Return address.
2878   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2879                            false, false, false, 0);
2880   return SDValue(OutRetAddr.getNode(), 1);
2881 }
2882
2883 /// Emit a store of the return address if tail call
2884 /// optimization is performed and it is required (FPDiff!=0).
2885 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2886                                         SDValue Chain, SDValue RetAddrFrIdx,
2887                                         EVT PtrVT, unsigned SlotSize,
2888                                         int FPDiff, SDLoc dl) {
2889   // Store the return address to the appropriate stack slot.
2890   if (!FPDiff) return Chain;
2891   // Calculate the new stack slot for the return address.
2892   int NewReturnAddrFI =
2893     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2894                                          false);
2895   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2896   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2897                        MachinePointerInfo::getFixedStack(
2898                            DAG.getMachineFunction(), NewReturnAddrFI),
2899                        false, false, 0);
2900   return Chain;
2901 }
2902
2903 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2904 /// operation of specified width.
2905 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2906                        SDValue V2) {
2907   unsigned NumElems = VT.getVectorNumElements();
2908   SmallVector<int, 8> Mask;
2909   Mask.push_back(NumElems);
2910   for (unsigned i = 1; i != NumElems; ++i)
2911     Mask.push_back(i);
2912   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2913 }
2914
2915 SDValue
2916 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2917                              SmallVectorImpl<SDValue> &InVals) const {
2918   SelectionDAG &DAG                     = CLI.DAG;
2919   SDLoc &dl                             = CLI.DL;
2920   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2921   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2922   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2923   SDValue Chain                         = CLI.Chain;
2924   SDValue Callee                        = CLI.Callee;
2925   CallingConv::ID CallConv              = CLI.CallConv;
2926   bool &isTailCall                      = CLI.IsTailCall;
2927   bool isVarArg                         = CLI.IsVarArg;
2928
2929   MachineFunction &MF = DAG.getMachineFunction();
2930   bool Is64Bit        = Subtarget->is64Bit();
2931   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2932   StructReturnType SR = callIsStructReturn(Outs);
2933   bool IsSibcall      = false;
2934   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2935   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2936
2937   if (Attr.getValueAsString() == "true")
2938     isTailCall = false;
2939
2940   if (Subtarget->isPICStyleGOT() &&
2941       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2942     // If we are using a GOT, disable tail calls to external symbols with
2943     // default visibility. Tail calling such a symbol requires using a GOT
2944     // relocation, which forces early binding of the symbol. This breaks code
2945     // that require lazy function symbol resolution. Using musttail or
2946     // GuaranteedTailCallOpt will override this.
2947     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2948     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2949                G->getGlobal()->hasDefaultVisibility()))
2950       isTailCall = false;
2951   }
2952
2953   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2954   if (IsMustTail) {
2955     // Force this to be a tail call.  The verifier rules are enough to ensure
2956     // that we can lower this successfully without moving the return address
2957     // around.
2958     isTailCall = true;
2959   } else if (isTailCall) {
2960     // Check if it's really possible to do a tail call.
2961     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2962                     isVarArg, SR != NotStructReturn,
2963                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2964                     Outs, OutVals, Ins, DAG);
2965
2966     // Sibcalls are automatically detected tailcalls which do not require
2967     // ABI changes.
2968     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2969       IsSibcall = true;
2970
2971     if (isTailCall)
2972       ++NumTailCalls;
2973   }
2974
2975   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2976          "Var args not supported with calling convention fastcc, ghc or hipe");
2977
2978   // Analyze operands of the call, assigning locations to each operand.
2979   SmallVector<CCValAssign, 16> ArgLocs;
2980   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2981
2982   // Allocate shadow area for Win64
2983   if (IsWin64)
2984     CCInfo.AllocateStack(32, 8);
2985
2986   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2987
2988   // Get a count of how many bytes are to be pushed on the stack.
2989   unsigned NumBytes = CCInfo.getNextStackOffset();
2990   if (IsSibcall)
2991     // This is a sibcall. The memory operands are available in caller's
2992     // own caller's stack.
2993     NumBytes = 0;
2994   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2995            IsTailCallConvention(CallConv))
2996     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2997
2998   int FPDiff = 0;
2999   if (isTailCall && !IsSibcall && !IsMustTail) {
3000     // Lower arguments at fp - stackoffset + fpdiff.
3001     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3002
3003     FPDiff = NumBytesCallerPushed - NumBytes;
3004
3005     // Set the delta of movement of the returnaddr stackslot.
3006     // But only set if delta is greater than previous delta.
3007     if (FPDiff < X86Info->getTCReturnAddrDelta())
3008       X86Info->setTCReturnAddrDelta(FPDiff);
3009   }
3010
3011   unsigned NumBytesToPush = NumBytes;
3012   unsigned NumBytesToPop = NumBytes;
3013
3014   // If we have an inalloca argument, all stack space has already been allocated
3015   // for us and be right at the top of the stack.  We don't support multiple
3016   // arguments passed in memory when using inalloca.
3017   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3018     NumBytesToPush = 0;
3019     if (!ArgLocs.back().isMemLoc())
3020       report_fatal_error("cannot use inalloca attribute on a register "
3021                          "parameter");
3022     if (ArgLocs.back().getLocMemOffset() != 0)
3023       report_fatal_error("any parameter with the inalloca attribute must be "
3024                          "the only memory argument");
3025   }
3026
3027   if (!IsSibcall)
3028     Chain = DAG.getCALLSEQ_START(
3029         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3030
3031   SDValue RetAddrFrIdx;
3032   // Load return address for tail calls.
3033   if (isTailCall && FPDiff)
3034     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3035                                     Is64Bit, FPDiff, dl);
3036
3037   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3038   SmallVector<SDValue, 8> MemOpChains;
3039   SDValue StackPtr;
3040
3041   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3042   // of tail call optimization arguments are handle later.
3043   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3044   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3045     // Skip inalloca arguments, they have already been written.
3046     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3047     if (Flags.isInAlloca())
3048       continue;
3049
3050     CCValAssign &VA = ArgLocs[i];
3051     EVT RegVT = VA.getLocVT();
3052     SDValue Arg = OutVals[i];
3053     bool isByVal = Flags.isByVal();
3054
3055     // Promote the value if needed.
3056     switch (VA.getLocInfo()) {
3057     default: llvm_unreachable("Unknown loc info!");
3058     case CCValAssign::Full: break;
3059     case CCValAssign::SExt:
3060       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3061       break;
3062     case CCValAssign::ZExt:
3063       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3064       break;
3065     case CCValAssign::AExt:
3066       if (Arg.getValueType().isVector() &&
3067           Arg.getValueType().getScalarType() == MVT::i1)
3068         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3069       else if (RegVT.is128BitVector()) {
3070         // Special case: passing MMX values in XMM registers.
3071         Arg = DAG.getBitcast(MVT::i64, Arg);
3072         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3073         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3074       } else
3075         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3076       break;
3077     case CCValAssign::BCvt:
3078       Arg = DAG.getBitcast(RegVT, Arg);
3079       break;
3080     case CCValAssign::Indirect: {
3081       // Store the argument.
3082       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3083       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3084       Chain = DAG.getStore(
3085           Chain, dl, Arg, SpillSlot,
3086           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3087           false, false, 0);
3088       Arg = SpillSlot;
3089       break;
3090     }
3091     }
3092
3093     if (VA.isRegLoc()) {
3094       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3095       if (isVarArg && IsWin64) {
3096         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3097         // shadow reg if callee is a varargs function.
3098         unsigned ShadowReg = 0;
3099         switch (VA.getLocReg()) {
3100         case X86::XMM0: ShadowReg = X86::RCX; break;
3101         case X86::XMM1: ShadowReg = X86::RDX; break;
3102         case X86::XMM2: ShadowReg = X86::R8; break;
3103         case X86::XMM3: ShadowReg = X86::R9; break;
3104         }
3105         if (ShadowReg)
3106           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3107       }
3108     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3109       assert(VA.isMemLoc());
3110       if (!StackPtr.getNode())
3111         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3112                                       getPointerTy(DAG.getDataLayout()));
3113       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3114                                              dl, DAG, VA, Flags));
3115     }
3116   }
3117
3118   if (!MemOpChains.empty())
3119     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3120
3121   if (Subtarget->isPICStyleGOT()) {
3122     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3123     // GOT pointer.
3124     if (!isTailCall) {
3125       RegsToPass.push_back(std::make_pair(
3126           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3127                                           getPointerTy(DAG.getDataLayout()))));
3128     } else {
3129       // If we are tail calling and generating PIC/GOT style code load the
3130       // address of the callee into ECX. The value in ecx is used as target of
3131       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3132       // for tail calls on PIC/GOT architectures. Normally we would just put the
3133       // address of GOT into ebx and then call target@PLT. But for tail calls
3134       // ebx would be restored (since ebx is callee saved) before jumping to the
3135       // target@PLT.
3136
3137       // Note: The actual moving to ECX is done further down.
3138       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3139       if (G && !G->getGlobal()->hasLocalLinkage() &&
3140           G->getGlobal()->hasDefaultVisibility())
3141         Callee = LowerGlobalAddress(Callee, DAG);
3142       else if (isa<ExternalSymbolSDNode>(Callee))
3143         Callee = LowerExternalSymbol(Callee, DAG);
3144     }
3145   }
3146
3147   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3148     // From AMD64 ABI document:
3149     // For calls that may call functions that use varargs or stdargs
3150     // (prototype-less calls or calls to functions containing ellipsis (...) in
3151     // the declaration) %al is used as hidden argument to specify the number
3152     // of SSE registers used. The contents of %al do not need to match exactly
3153     // the number of registers, but must be an ubound on the number of SSE
3154     // registers used and is in the range 0 - 8 inclusive.
3155
3156     // Count the number of XMM registers allocated.
3157     static const MCPhysReg XMMArgRegs[] = {
3158       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3159       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3160     };
3161     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3162     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3163            && "SSE registers cannot be used when SSE is disabled");
3164
3165     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3166                                         DAG.getConstant(NumXMMRegs, dl,
3167                                                         MVT::i8)));
3168   }
3169
3170   if (isVarArg && IsMustTail) {
3171     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3172     for (const auto &F : Forwards) {
3173       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3174       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3175     }
3176   }
3177
3178   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3179   // don't need this because the eligibility check rejects calls that require
3180   // shuffling arguments passed in memory.
3181   if (!IsSibcall && isTailCall) {
3182     // Force all the incoming stack arguments to be loaded from the stack
3183     // before any new outgoing arguments are stored to the stack, because the
3184     // outgoing stack slots may alias the incoming argument stack slots, and
3185     // the alias isn't otherwise explicit. This is slightly more conservative
3186     // than necessary, because it means that each store effectively depends
3187     // on every argument instead of just those arguments it would clobber.
3188     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3189
3190     SmallVector<SDValue, 8> MemOpChains2;
3191     SDValue FIN;
3192     int FI = 0;
3193     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3194       CCValAssign &VA = ArgLocs[i];
3195       if (VA.isRegLoc())
3196         continue;
3197       assert(VA.isMemLoc());
3198       SDValue Arg = OutVals[i];
3199       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3200       // Skip inalloca arguments.  They don't require any work.
3201       if (Flags.isInAlloca())
3202         continue;
3203       // Create frame index.
3204       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3205       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3206       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3207       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3208
3209       if (Flags.isByVal()) {
3210         // Copy relative to framepointer.
3211         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3212         if (!StackPtr.getNode())
3213           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3214                                         getPointerTy(DAG.getDataLayout()));
3215         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3216                              StackPtr, Source);
3217
3218         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3219                                                          ArgChain,
3220                                                          Flags, DAG, dl));
3221       } else {
3222         // Store relative to framepointer.
3223         MemOpChains2.push_back(DAG.getStore(
3224             ArgChain, dl, Arg, FIN,
3225             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3226             false, false, 0));
3227       }
3228     }
3229
3230     if (!MemOpChains2.empty())
3231       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3232
3233     // Store the return address to the appropriate stack slot.
3234     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3235                                      getPointerTy(DAG.getDataLayout()),
3236                                      RegInfo->getSlotSize(), FPDiff, dl);
3237   }
3238
3239   // Build a sequence of copy-to-reg nodes chained together with token chain
3240   // and flag operands which copy the outgoing args into registers.
3241   SDValue InFlag;
3242   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3243     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3244                              RegsToPass[i].second, InFlag);
3245     InFlag = Chain.getValue(1);
3246   }
3247
3248   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3249     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3250     // In the 64-bit large code model, we have to make all calls
3251     // through a register, since the call instruction's 32-bit
3252     // pc-relative offset may not be large enough to hold the whole
3253     // address.
3254   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3255     // If the callee is a GlobalAddress node (quite common, every direct call
3256     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3257     // it.
3258     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3259
3260     // We should use extra load for direct calls to dllimported functions in
3261     // non-JIT mode.
3262     const GlobalValue *GV = G->getGlobal();
3263     if (!GV->hasDLLImportStorageClass()) {
3264       unsigned char OpFlags = 0;
3265       bool ExtraLoad = false;
3266       unsigned WrapperKind = ISD::DELETED_NODE;
3267
3268       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3269       // external symbols most go through the PLT in PIC mode.  If the symbol
3270       // has hidden or protected visibility, or if it is static or local, then
3271       // we don't need to use the PLT - we can directly call it.
3272       if (Subtarget->isTargetELF() &&
3273           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3274           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3275         OpFlags = X86II::MO_PLT;
3276       } else if (Subtarget->isPICStyleStubAny() &&
3277                  !GV->isStrongDefinitionForLinker() &&
3278                  (!Subtarget->getTargetTriple().isMacOSX() ||
3279                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3280         // PC-relative references to external symbols should go through $stub,
3281         // unless we're building with the leopard linker or later, which
3282         // automatically synthesizes these stubs.
3283         OpFlags = X86II::MO_DARWIN_STUB;
3284       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3285                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3286         // If the function is marked as non-lazy, generate an indirect call
3287         // which loads from the GOT directly. This avoids runtime overhead
3288         // at the cost of eager binding (and one extra byte of encoding).
3289         OpFlags = X86II::MO_GOTPCREL;
3290         WrapperKind = X86ISD::WrapperRIP;
3291         ExtraLoad = true;
3292       }
3293
3294       Callee = DAG.getTargetGlobalAddress(
3295           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3296
3297       // Add a wrapper if needed.
3298       if (WrapperKind != ISD::DELETED_NODE)
3299         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3300                              getPointerTy(DAG.getDataLayout()), Callee);
3301       // Add extra indirection if needed.
3302       if (ExtraLoad)
3303         Callee = DAG.getLoad(
3304             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3305             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3306             false, 0);
3307     }
3308   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3309     unsigned char OpFlags = 0;
3310
3311     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3312     // external symbols should go through the PLT.
3313     if (Subtarget->isTargetELF() &&
3314         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3315       OpFlags = X86II::MO_PLT;
3316     } else if (Subtarget->isPICStyleStubAny() &&
3317                (!Subtarget->getTargetTriple().isMacOSX() ||
3318                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3319       // PC-relative references to external symbols should go through $stub,
3320       // unless we're building with the leopard linker or later, which
3321       // automatically synthesizes these stubs.
3322       OpFlags = X86II::MO_DARWIN_STUB;
3323     }
3324
3325     Callee = DAG.getTargetExternalSymbol(
3326         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3327   } else if (Subtarget->isTarget64BitILP32() &&
3328              Callee->getValueType(0) == MVT::i32) {
3329     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3330     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3331   }
3332
3333   // Returns a chain & a flag for retval copy to use.
3334   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3335   SmallVector<SDValue, 8> Ops;
3336
3337   if (!IsSibcall && isTailCall) {
3338     Chain = DAG.getCALLSEQ_END(Chain,
3339                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3340                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3341     InFlag = Chain.getValue(1);
3342   }
3343
3344   Ops.push_back(Chain);
3345   Ops.push_back(Callee);
3346
3347   if (isTailCall)
3348     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3349
3350   // Add argument registers to the end of the list so that they are known live
3351   // into the call.
3352   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3353     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3354                                   RegsToPass[i].second.getValueType()));
3355
3356   // Add a register mask operand representing the call-preserved registers.
3357   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3358   assert(Mask && "Missing call preserved mask for calling convention");
3359
3360   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3361   // the function clobbers all registers. If an exception is thrown, the runtime
3362   // will not restore CSRs.
3363   // FIXME: Model this more precisely so that we can register allocate across
3364   // the normal edge and spill and fill across the exceptional edge.
3365   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3366     const Function *CallerFn = MF.getFunction();
3367     EHPersonality Pers =
3368         CallerFn->hasPersonalityFn()
3369             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3370             : EHPersonality::Unknown;
3371     if (isMSVCEHPersonality(Pers))
3372       Mask = RegInfo->getNoPreservedMask();
3373   }
3374
3375   Ops.push_back(DAG.getRegisterMask(Mask));
3376
3377   if (InFlag.getNode())
3378     Ops.push_back(InFlag);
3379
3380   if (isTailCall) {
3381     // We used to do:
3382     //// If this is the first return lowered for this function, add the regs
3383     //// to the liveout set for the function.
3384     // This isn't right, although it's probably harmless on x86; liveouts
3385     // should be computed from returns not tail calls.  Consider a void
3386     // function making a tail call to a function returning int.
3387     MF.getFrameInfo()->setHasTailCall();
3388     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3389   }
3390
3391   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3392   InFlag = Chain.getValue(1);
3393
3394   // Create the CALLSEQ_END node.
3395   unsigned NumBytesForCalleeToPop;
3396   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3397                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3398     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3399   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3400            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3401            SR == StackStructReturn)
3402     // If this is a call to a struct-return function, the callee
3403     // pops the hidden struct pointer, so we have to push it back.
3404     // This is common for Darwin/X86, Linux & Mingw32 targets.
3405     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3406     NumBytesForCalleeToPop = 4;
3407   else
3408     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3409
3410   // Returns a flag for retval copy to use.
3411   if (!IsSibcall) {
3412     Chain = DAG.getCALLSEQ_END(Chain,
3413                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3414                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3415                                                      true),
3416                                InFlag, dl);
3417     InFlag = Chain.getValue(1);
3418   }
3419
3420   // Handle result values, copying them out of physregs into vregs that we
3421   // return.
3422   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3423                          Ins, dl, DAG, InVals);
3424 }
3425
3426 //===----------------------------------------------------------------------===//
3427 //                Fast Calling Convention (tail call) implementation
3428 //===----------------------------------------------------------------------===//
3429
3430 //  Like std call, callee cleans arguments, convention except that ECX is
3431 //  reserved for storing the tail called function address. Only 2 registers are
3432 //  free for argument passing (inreg). Tail call optimization is performed
3433 //  provided:
3434 //                * tailcallopt is enabled
3435 //                * caller/callee are fastcc
3436 //  On X86_64 architecture with GOT-style position independent code only local
3437 //  (within module) calls are supported at the moment.
3438 //  To keep the stack aligned according to platform abi the function
3439 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3440 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3441 //  If a tail called function callee has more arguments than the caller the
3442 //  caller needs to make sure that there is room to move the RETADDR to. This is
3443 //  achieved by reserving an area the size of the argument delta right after the
3444 //  original RETADDR, but before the saved framepointer or the spilled registers
3445 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3446 //  stack layout:
3447 //    arg1
3448 //    arg2
3449 //    RETADDR
3450 //    [ new RETADDR
3451 //      move area ]
3452 //    (possible EBP)
3453 //    ESI
3454 //    EDI
3455 //    local1 ..
3456
3457 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3458 /// requirement.
3459 unsigned
3460 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3461                                                SelectionDAG& DAG) const {
3462   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3463   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3464   unsigned StackAlignment = TFI.getStackAlignment();
3465   uint64_t AlignMask = StackAlignment - 1;
3466   int64_t Offset = StackSize;
3467   unsigned SlotSize = RegInfo->getSlotSize();
3468   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3469     // Number smaller than 12 so just add the difference.
3470     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3471   } else {
3472     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3473     Offset = ((~AlignMask) & Offset) + StackAlignment +
3474       (StackAlignment-SlotSize);
3475   }
3476   return Offset;
3477 }
3478
3479 /// Return true if the given stack call argument is already available in the
3480 /// same position (relatively) of the caller's incoming argument stack.
3481 static
3482 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3483                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3484                          const X86InstrInfo *TII) {
3485   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3486   int FI = INT_MAX;
3487   if (Arg.getOpcode() == ISD::CopyFromReg) {
3488     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3489     if (!TargetRegisterInfo::isVirtualRegister(VR))
3490       return false;
3491     MachineInstr *Def = MRI->getVRegDef(VR);
3492     if (!Def)
3493       return false;
3494     if (!Flags.isByVal()) {
3495       if (!TII->isLoadFromStackSlot(Def, FI))
3496         return false;
3497     } else {
3498       unsigned Opcode = Def->getOpcode();
3499       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3500            Opcode == X86::LEA64_32r) &&
3501           Def->getOperand(1).isFI()) {
3502         FI = Def->getOperand(1).getIndex();
3503         Bytes = Flags.getByValSize();
3504       } else
3505         return false;
3506     }
3507   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3508     if (Flags.isByVal())
3509       // ByVal argument is passed in as a pointer but it's now being
3510       // dereferenced. e.g.
3511       // define @foo(%struct.X* %A) {
3512       //   tail call @bar(%struct.X* byval %A)
3513       // }
3514       return false;
3515     SDValue Ptr = Ld->getBasePtr();
3516     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3517     if (!FINode)
3518       return false;
3519     FI = FINode->getIndex();
3520   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3521     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3522     FI = FINode->getIndex();
3523     Bytes = Flags.getByValSize();
3524   } else
3525     return false;
3526
3527   assert(FI != INT_MAX);
3528   if (!MFI->isFixedObjectIndex(FI))
3529     return false;
3530   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3531 }
3532
3533 /// Check whether the call is eligible for tail call optimization. Targets
3534 /// that want to do tail call optimization should implement this function.
3535 bool
3536 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3537                                                      CallingConv::ID CalleeCC,
3538                                                      bool isVarArg,
3539                                                      bool isCalleeStructRet,
3540                                                      bool isCallerStructRet,
3541                                                      Type *RetTy,
3542                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3543                                     const SmallVectorImpl<SDValue> &OutVals,
3544                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3545                                                      SelectionDAG &DAG) const {
3546   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3547     return false;
3548
3549   // If -tailcallopt is specified, make fastcc functions tail-callable.
3550   const MachineFunction &MF = DAG.getMachineFunction();
3551   const Function *CallerF = MF.getFunction();
3552
3553   // If the function return type is x86_fp80 and the callee return type is not,
3554   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3555   // perform a tailcall optimization here.
3556   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3557     return false;
3558
3559   CallingConv::ID CallerCC = CallerF->getCallingConv();
3560   bool CCMatch = CallerCC == CalleeCC;
3561   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3562   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3563
3564   // Win64 functions have extra shadow space for argument homing. Don't do the
3565   // sibcall if the caller and callee have mismatched expectations for this
3566   // space.
3567   if (IsCalleeWin64 != IsCallerWin64)
3568     return false;
3569
3570   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3571     if (IsTailCallConvention(CalleeCC) && CCMatch)
3572       return true;
3573     return false;
3574   }
3575
3576   // Look for obvious safe cases to perform tail call optimization that do not
3577   // require ABI changes. This is what gcc calls sibcall.
3578
3579   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3580   // emit a special epilogue.
3581   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3582   if (RegInfo->needsStackRealignment(MF))
3583     return false;
3584
3585   // Also avoid sibcall optimization if either caller or callee uses struct
3586   // return semantics.
3587   if (isCalleeStructRet || isCallerStructRet)
3588     return false;
3589
3590   // An stdcall/thiscall caller is expected to clean up its arguments; the
3591   // callee isn't going to do that.
3592   // FIXME: this is more restrictive than needed. We could produce a tailcall
3593   // when the stack adjustment matches. For example, with a thiscall that takes
3594   // only one argument.
3595   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3596                    CallerCC == CallingConv::X86_ThisCall))
3597     return false;
3598
3599   // Do not sibcall optimize vararg calls unless all arguments are passed via
3600   // registers.
3601   if (isVarArg && !Outs.empty()) {
3602
3603     // Optimizing for varargs on Win64 is unlikely to be safe without
3604     // additional testing.
3605     if (IsCalleeWin64 || IsCallerWin64)
3606       return false;
3607
3608     SmallVector<CCValAssign, 16> ArgLocs;
3609     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3610                    *DAG.getContext());
3611
3612     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3613     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3614       if (!ArgLocs[i].isRegLoc())
3615         return false;
3616   }
3617
3618   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3619   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3620   // this into a sibcall.
3621   bool Unused = false;
3622   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3623     if (!Ins[i].Used) {
3624       Unused = true;
3625       break;
3626     }
3627   }
3628   if (Unused) {
3629     SmallVector<CCValAssign, 16> RVLocs;
3630     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3631                    *DAG.getContext());
3632     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3633     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3634       CCValAssign &VA = RVLocs[i];
3635       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3636         return false;
3637     }
3638   }
3639
3640   // If the calling conventions do not match, then we'd better make sure the
3641   // results are returned in the same way as what the caller expects.
3642   if (!CCMatch) {
3643     SmallVector<CCValAssign, 16> RVLocs1;
3644     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3645                     *DAG.getContext());
3646     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3647
3648     SmallVector<CCValAssign, 16> RVLocs2;
3649     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3650                     *DAG.getContext());
3651     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3652
3653     if (RVLocs1.size() != RVLocs2.size())
3654       return false;
3655     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3656       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3657         return false;
3658       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3659         return false;
3660       if (RVLocs1[i].isRegLoc()) {
3661         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3662           return false;
3663       } else {
3664         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3665           return false;
3666       }
3667     }
3668   }
3669
3670   // If the callee takes no arguments then go on to check the results of the
3671   // call.
3672   if (!Outs.empty()) {
3673     // Check if stack adjustment is needed. For now, do not do this if any
3674     // argument is passed on the stack.
3675     SmallVector<CCValAssign, 16> ArgLocs;
3676     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3677                    *DAG.getContext());
3678
3679     // Allocate shadow area for Win64
3680     if (IsCalleeWin64)
3681       CCInfo.AllocateStack(32, 8);
3682
3683     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3684     if (CCInfo.getNextStackOffset()) {
3685       MachineFunction &MF = DAG.getMachineFunction();
3686       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3687         return false;
3688
3689       // Check if the arguments are already laid out in the right way as
3690       // the caller's fixed stack objects.
3691       MachineFrameInfo *MFI = MF.getFrameInfo();
3692       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3693       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3694       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3695         CCValAssign &VA = ArgLocs[i];
3696         SDValue Arg = OutVals[i];
3697         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3698         if (VA.getLocInfo() == CCValAssign::Indirect)
3699           return false;
3700         if (!VA.isRegLoc()) {
3701           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3702                                    MFI, MRI, TII))
3703             return false;
3704         }
3705       }
3706     }
3707
3708     // If the tailcall address may be in a register, then make sure it's
3709     // possible to register allocate for it. In 32-bit, the call address can
3710     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3711     // callee-saved registers are restored. These happen to be the same
3712     // registers used to pass 'inreg' arguments so watch out for those.
3713     if (!Subtarget->is64Bit() &&
3714         ((!isa<GlobalAddressSDNode>(Callee) &&
3715           !isa<ExternalSymbolSDNode>(Callee)) ||
3716          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3717       unsigned NumInRegs = 0;
3718       // In PIC we need an extra register to formulate the address computation
3719       // for the callee.
3720       unsigned MaxInRegs =
3721         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3722
3723       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3724         CCValAssign &VA = ArgLocs[i];
3725         if (!VA.isRegLoc())
3726           continue;
3727         unsigned Reg = VA.getLocReg();
3728         switch (Reg) {
3729         default: break;
3730         case X86::EAX: case X86::EDX: case X86::ECX:
3731           if (++NumInRegs == MaxInRegs)
3732             return false;
3733           break;
3734         }
3735       }
3736     }
3737   }
3738
3739   return true;
3740 }
3741
3742 FastISel *
3743 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3744                                   const TargetLibraryInfo *libInfo) const {
3745   return X86::createFastISel(funcInfo, libInfo);
3746 }
3747
3748 //===----------------------------------------------------------------------===//
3749 //                           Other Lowering Hooks
3750 //===----------------------------------------------------------------------===//
3751
3752 static bool MayFoldLoad(SDValue Op) {
3753   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3754 }
3755
3756 static bool MayFoldIntoStore(SDValue Op) {
3757   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3758 }
3759
3760 static bool isTargetShuffle(unsigned Opcode) {
3761   switch(Opcode) {
3762   default: return false;
3763   case X86ISD::BLENDI:
3764   case X86ISD::PSHUFB:
3765   case X86ISD::PSHUFD:
3766   case X86ISD::PSHUFHW:
3767   case X86ISD::PSHUFLW:
3768   case X86ISD::SHUFP:
3769   case X86ISD::PALIGNR:
3770   case X86ISD::MOVLHPS:
3771   case X86ISD::MOVLHPD:
3772   case X86ISD::MOVHLPS:
3773   case X86ISD::MOVLPS:
3774   case X86ISD::MOVLPD:
3775   case X86ISD::MOVSHDUP:
3776   case X86ISD::MOVSLDUP:
3777   case X86ISD::MOVDDUP:
3778   case X86ISD::MOVSS:
3779   case X86ISD::MOVSD:
3780   case X86ISD::UNPCKL:
3781   case X86ISD::UNPCKH:
3782   case X86ISD::VPERMILPI:
3783   case X86ISD::VPERM2X128:
3784   case X86ISD::VPERMI:
3785     return true;
3786   }
3787 }
3788
3789 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3790                                     SDValue V1, unsigned TargetMask,
3791                                     SelectionDAG &DAG) {
3792   switch(Opc) {
3793   default: llvm_unreachable("Unknown x86 shuffle node");
3794   case X86ISD::PSHUFD:
3795   case X86ISD::PSHUFHW:
3796   case X86ISD::PSHUFLW:
3797   case X86ISD::VPERMILPI:
3798   case X86ISD::VPERMI:
3799     return DAG.getNode(Opc, dl, VT, V1,
3800                        DAG.getConstant(TargetMask, dl, MVT::i8));
3801   }
3802 }
3803
3804 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3805                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3806   switch(Opc) {
3807   default: llvm_unreachable("Unknown x86 shuffle node");
3808   case X86ISD::MOVLHPS:
3809   case X86ISD::MOVLHPD:
3810   case X86ISD::MOVHLPS:
3811   case X86ISD::MOVLPS:
3812   case X86ISD::MOVLPD:
3813   case X86ISD::MOVSS:
3814   case X86ISD::MOVSD:
3815   case X86ISD::UNPCKL:
3816   case X86ISD::UNPCKH:
3817     return DAG.getNode(Opc, dl, VT, V1, V2);
3818   }
3819 }
3820
3821 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3822   MachineFunction &MF = DAG.getMachineFunction();
3823   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3824   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3825   int ReturnAddrIndex = FuncInfo->getRAIndex();
3826
3827   if (ReturnAddrIndex == 0) {
3828     // Set up a frame object for the return address.
3829     unsigned SlotSize = RegInfo->getSlotSize();
3830     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3831                                                            -(int64_t)SlotSize,
3832                                                            false);
3833     FuncInfo->setRAIndex(ReturnAddrIndex);
3834   }
3835
3836   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3837 }
3838
3839 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3840                                        bool hasSymbolicDisplacement) {
3841   // Offset should fit into 32 bit immediate field.
3842   if (!isInt<32>(Offset))
3843     return false;
3844
3845   // If we don't have a symbolic displacement - we don't have any extra
3846   // restrictions.
3847   if (!hasSymbolicDisplacement)
3848     return true;
3849
3850   // FIXME: Some tweaks might be needed for medium code model.
3851   if (M != CodeModel::Small && M != CodeModel::Kernel)
3852     return false;
3853
3854   // For small code model we assume that latest object is 16MB before end of 31
3855   // bits boundary. We may also accept pretty large negative constants knowing
3856   // that all objects are in the positive half of address space.
3857   if (M == CodeModel::Small && Offset < 16*1024*1024)
3858     return true;
3859
3860   // For kernel code model we know that all object resist in the negative half
3861   // of 32bits address space. We may not accept negative offsets, since they may
3862   // be just off and we may accept pretty large positive ones.
3863   if (M == CodeModel::Kernel && Offset >= 0)
3864     return true;
3865
3866   return false;
3867 }
3868
3869 /// Determines whether the callee is required to pop its own arguments.
3870 /// Callee pop is necessary to support tail calls.
3871 bool X86::isCalleePop(CallingConv::ID CallingConv,
3872                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3873   switch (CallingConv) {
3874   default:
3875     return false;
3876   case CallingConv::X86_StdCall:
3877   case CallingConv::X86_FastCall:
3878   case CallingConv::X86_ThisCall:
3879     return !is64Bit;
3880   case CallingConv::Fast:
3881   case CallingConv::GHC:
3882   case CallingConv::HiPE:
3883     if (IsVarArg)
3884       return false;
3885     return TailCallOpt;
3886   }
3887 }
3888
3889 /// \brief Return true if the condition is an unsigned comparison operation.
3890 static bool isX86CCUnsigned(unsigned X86CC) {
3891   switch (X86CC) {
3892   default: llvm_unreachable("Invalid integer condition!");
3893   case X86::COND_E:     return true;
3894   case X86::COND_G:     return false;
3895   case X86::COND_GE:    return false;
3896   case X86::COND_L:     return false;
3897   case X86::COND_LE:    return false;
3898   case X86::COND_NE:    return true;
3899   case X86::COND_B:     return true;
3900   case X86::COND_A:     return true;
3901   case X86::COND_BE:    return true;
3902   case X86::COND_AE:    return true;
3903   }
3904   llvm_unreachable("covered switch fell through?!");
3905 }
3906
3907 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3908 /// condition code, returning the condition code and the LHS/RHS of the
3909 /// comparison to make.
3910 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3911                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3912   if (!isFP) {
3913     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3914       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3915         // X > -1   -> X == 0, jump !sign.
3916         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3917         return X86::COND_NS;
3918       }
3919       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3920         // X < 0   -> X == 0, jump on sign.
3921         return X86::COND_S;
3922       }
3923       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3924         // X < 1   -> X <= 0
3925         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3926         return X86::COND_LE;
3927       }
3928     }
3929
3930     switch (SetCCOpcode) {
3931     default: llvm_unreachable("Invalid integer condition!");
3932     case ISD::SETEQ:  return X86::COND_E;
3933     case ISD::SETGT:  return X86::COND_G;
3934     case ISD::SETGE:  return X86::COND_GE;
3935     case ISD::SETLT:  return X86::COND_L;
3936     case ISD::SETLE:  return X86::COND_LE;
3937     case ISD::SETNE:  return X86::COND_NE;
3938     case ISD::SETULT: return X86::COND_B;
3939     case ISD::SETUGT: return X86::COND_A;
3940     case ISD::SETULE: return X86::COND_BE;
3941     case ISD::SETUGE: return X86::COND_AE;
3942     }
3943   }
3944
3945   // First determine if it is required or is profitable to flip the operands.
3946
3947   // If LHS is a foldable load, but RHS is not, flip the condition.
3948   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3949       !ISD::isNON_EXTLoad(RHS.getNode())) {
3950     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3951     std::swap(LHS, RHS);
3952   }
3953
3954   switch (SetCCOpcode) {
3955   default: break;
3956   case ISD::SETOLT:
3957   case ISD::SETOLE:
3958   case ISD::SETUGT:
3959   case ISD::SETUGE:
3960     std::swap(LHS, RHS);
3961     break;
3962   }
3963
3964   // On a floating point condition, the flags are set as follows:
3965   // ZF  PF  CF   op
3966   //  0 | 0 | 0 | X > Y
3967   //  0 | 0 | 1 | X < Y
3968   //  1 | 0 | 0 | X == Y
3969   //  1 | 1 | 1 | unordered
3970   switch (SetCCOpcode) {
3971   default: llvm_unreachable("Condcode should be pre-legalized away");
3972   case ISD::SETUEQ:
3973   case ISD::SETEQ:   return X86::COND_E;
3974   case ISD::SETOLT:              // flipped
3975   case ISD::SETOGT:
3976   case ISD::SETGT:   return X86::COND_A;
3977   case ISD::SETOLE:              // flipped
3978   case ISD::SETOGE:
3979   case ISD::SETGE:   return X86::COND_AE;
3980   case ISD::SETUGT:              // flipped
3981   case ISD::SETULT:
3982   case ISD::SETLT:   return X86::COND_B;
3983   case ISD::SETUGE:              // flipped
3984   case ISD::SETULE:
3985   case ISD::SETLE:   return X86::COND_BE;
3986   case ISD::SETONE:
3987   case ISD::SETNE:   return X86::COND_NE;
3988   case ISD::SETUO:   return X86::COND_P;
3989   case ISD::SETO:    return X86::COND_NP;
3990   case ISD::SETOEQ:
3991   case ISD::SETUNE:  return X86::COND_INVALID;
3992   }
3993 }
3994
3995 /// Is there a floating point cmov for the specific X86 condition code?
3996 /// Current x86 isa includes the following FP cmov instructions:
3997 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3998 static bool hasFPCMov(unsigned X86CC) {
3999   switch (X86CC) {
4000   default:
4001     return false;
4002   case X86::COND_B:
4003   case X86::COND_BE:
4004   case X86::COND_E:
4005   case X86::COND_P:
4006   case X86::COND_A:
4007   case X86::COND_AE:
4008   case X86::COND_NE:
4009   case X86::COND_NP:
4010     return true;
4011   }
4012 }
4013
4014 /// Returns true if the target can instruction select the
4015 /// specified FP immediate natively. If false, the legalizer will
4016 /// materialize the FP immediate as a load from a constant pool.
4017 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4018   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4019     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4020       return true;
4021   }
4022   return false;
4023 }
4024
4025 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4026                                               ISD::LoadExtType ExtTy,
4027                                               EVT NewVT) const {
4028   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4029   // relocation target a movq or addq instruction: don't let the load shrink.
4030   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4031   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4032     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4033       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4034   return true;
4035 }
4036
4037 /// \brief Returns true if it is beneficial to convert a load of a constant
4038 /// to just the constant itself.
4039 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4040                                                           Type *Ty) const {
4041   assert(Ty->isIntegerTy());
4042
4043   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4044   if (BitSize == 0 || BitSize > 64)
4045     return false;
4046   return true;
4047 }
4048
4049 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4050                                                 unsigned Index) const {
4051   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4052     return false;
4053
4054   return (Index == 0 || Index == ResVT.getVectorNumElements());
4055 }
4056
4057 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4058   // Speculate cttz only if we can directly use TZCNT.
4059   return Subtarget->hasBMI();
4060 }
4061
4062 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4063   // Speculate ctlz only if we can directly use LZCNT.
4064   return Subtarget->hasLZCNT();
4065 }
4066
4067 /// Return true if every element in Mask, beginning
4068 /// from position Pos and ending in Pos+Size is undef.
4069 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4070   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4071     if (0 <= Mask[i])
4072       return false;
4073   return true;
4074 }
4075
4076 /// Return true if Val is undef or if its value falls within the
4077 /// specified range (L, H].
4078 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4079   return (Val < 0) || (Val >= Low && Val < Hi);
4080 }
4081
4082 /// Val is either less than zero (undef) or equal to the specified value.
4083 static bool isUndefOrEqual(int Val, int CmpVal) {
4084   return (Val < 0 || Val == CmpVal);
4085 }
4086
4087 /// Return true if every element in Mask, beginning
4088 /// from position Pos and ending in Pos+Size, falls within the specified
4089 /// sequential range (Low, Low+Size]. or is undef.
4090 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4091                                        unsigned Pos, unsigned Size, int Low) {
4092   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4093     if (!isUndefOrEqual(Mask[i], Low))
4094       return false;
4095   return true;
4096 }
4097
4098 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4099 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4100 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4101   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4102   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4103     return false;
4104
4105   // The index should be aligned on a vecWidth-bit boundary.
4106   uint64_t Index =
4107     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4108
4109   MVT VT = N->getSimpleValueType(0);
4110   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4111   bool Result = (Index * ElSize) % vecWidth == 0;
4112
4113   return Result;
4114 }
4115
4116 /// Return true if the specified INSERT_SUBVECTOR
4117 /// operand specifies a subvector insert that is suitable for input to
4118 /// insertion of 128 or 256-bit subvectors
4119 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4120   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4121   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4122     return false;
4123   // The index should be aligned on a vecWidth-bit boundary.
4124   uint64_t Index =
4125     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4126
4127   MVT VT = N->getSimpleValueType(0);
4128   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4129   bool Result = (Index * ElSize) % vecWidth == 0;
4130
4131   return Result;
4132 }
4133
4134 bool X86::isVINSERT128Index(SDNode *N) {
4135   return isVINSERTIndex(N, 128);
4136 }
4137
4138 bool X86::isVINSERT256Index(SDNode *N) {
4139   return isVINSERTIndex(N, 256);
4140 }
4141
4142 bool X86::isVEXTRACT128Index(SDNode *N) {
4143   return isVEXTRACTIndex(N, 128);
4144 }
4145
4146 bool X86::isVEXTRACT256Index(SDNode *N) {
4147   return isVEXTRACTIndex(N, 256);
4148 }
4149
4150 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4151   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4152   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4153     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4154
4155   uint64_t Index =
4156     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4157
4158   MVT VecVT = N->getOperand(0).getSimpleValueType();
4159   MVT ElVT = VecVT.getVectorElementType();
4160
4161   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4162   return Index / NumElemsPerChunk;
4163 }
4164
4165 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4166   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4167   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4168     llvm_unreachable("Illegal insert subvector for VINSERT");
4169
4170   uint64_t Index =
4171     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4172
4173   MVT VecVT = N->getSimpleValueType(0);
4174   MVT ElVT = VecVT.getVectorElementType();
4175
4176   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4177   return Index / NumElemsPerChunk;
4178 }
4179
4180 /// Return the appropriate immediate to extract the specified
4181 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4182 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4183   return getExtractVEXTRACTImmediate(N, 128);
4184 }
4185
4186 /// Return the appropriate immediate to extract the specified
4187 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4188 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4189   return getExtractVEXTRACTImmediate(N, 256);
4190 }
4191
4192 /// Return the appropriate immediate to insert at the specified
4193 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4194 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4195   return getInsertVINSERTImmediate(N, 128);
4196 }
4197
4198 /// Return the appropriate immediate to insert at the specified
4199 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4200 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4201   return getInsertVINSERTImmediate(N, 256);
4202 }
4203
4204 /// Returns true if Elt is a constant integer zero
4205 static bool isZero(SDValue V) {
4206   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4207   return C && C->isNullValue();
4208 }
4209
4210 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4211 bool X86::isZeroNode(SDValue Elt) {
4212   if (isZero(Elt))
4213     return true;
4214   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4215     return CFP->getValueAPF().isPosZero();
4216   return false;
4217 }
4218
4219 /// Returns a vector of specified type with all zero elements.
4220 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4221                              SelectionDAG &DAG, SDLoc dl) {
4222   assert(VT.isVector() && "Expected a vector type");
4223
4224   // Always build SSE zero vectors as <4 x i32> bitcasted
4225   // to their dest type. This ensures they get CSE'd.
4226   SDValue Vec;
4227   if (VT.is128BitVector()) {  // SSE
4228     if (Subtarget->hasSSE2()) {  // SSE2
4229       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4230       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4231     } else { // SSE1
4232       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4233       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4234     }
4235   } else if (VT.is256BitVector()) { // AVX
4236     if (Subtarget->hasInt256()) { // AVX2
4237       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4238       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4239       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4240     } else {
4241       // 256-bit logic and arithmetic instructions in AVX are all
4242       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4243       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4244       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4245       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4246     }
4247   } else if (VT.is512BitVector()) { // AVX-512
4248       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4249       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4250                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4251       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4252   } else if (VT.getScalarType() == MVT::i1) {
4253
4254     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4255             && "Unexpected vector type");
4256     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4257             && "Unexpected vector type");
4258     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4259     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4260     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4261   } else
4262     llvm_unreachable("Unexpected vector type");
4263
4264   return DAG.getBitcast(VT, Vec);
4265 }
4266
4267 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4268                                 SelectionDAG &DAG, SDLoc dl,
4269                                 unsigned vectorWidth) {
4270   assert((vectorWidth == 128 || vectorWidth == 256) &&
4271          "Unsupported vector width");
4272   EVT VT = Vec.getValueType();
4273   EVT ElVT = VT.getVectorElementType();
4274   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4275   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4276                                   VT.getVectorNumElements()/Factor);
4277
4278   // Extract from UNDEF is UNDEF.
4279   if (Vec.getOpcode() == ISD::UNDEF)
4280     return DAG.getUNDEF(ResultVT);
4281
4282   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4283   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4284
4285   // This is the index of the first element of the vectorWidth-bit chunk
4286   // we want.
4287   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4288                                * ElemsPerChunk);
4289
4290   // If the input is a buildvector just emit a smaller one.
4291   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4292     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4293                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4294                                     ElemsPerChunk));
4295
4296   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4297   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4298 }
4299
4300 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4301 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4302 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4303 /// instructions or a simple subregister reference. Idx is an index in the
4304 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4305 /// lowering EXTRACT_VECTOR_ELT operations easier.
4306 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4307                                    SelectionDAG &DAG, SDLoc dl) {
4308   assert((Vec.getValueType().is256BitVector() ||
4309           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4310   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4311 }
4312
4313 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4314 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4315                                    SelectionDAG &DAG, SDLoc dl) {
4316   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4317   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4318 }
4319
4320 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4321                                unsigned IdxVal, SelectionDAG &DAG,
4322                                SDLoc dl, unsigned vectorWidth) {
4323   assert((vectorWidth == 128 || vectorWidth == 256) &&
4324          "Unsupported vector width");
4325   // Inserting UNDEF is Result
4326   if (Vec.getOpcode() == ISD::UNDEF)
4327     return Result;
4328   EVT VT = Vec.getValueType();
4329   EVT ElVT = VT.getVectorElementType();
4330   EVT ResultVT = Result.getValueType();
4331
4332   // Insert the relevant vectorWidth bits.
4333   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4334
4335   // This is the index of the first element of the vectorWidth-bit chunk
4336   // we want.
4337   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4338                                * ElemsPerChunk);
4339
4340   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4341   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4342 }
4343
4344 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4345 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4346 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4347 /// simple superregister reference.  Idx is an index in the 128 bits
4348 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4349 /// lowering INSERT_VECTOR_ELT operations easier.
4350 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4351                                   SelectionDAG &DAG, SDLoc dl) {
4352   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4353
4354   // For insertion into the zero index (low half) of a 256-bit vector, it is
4355   // more efficient to generate a blend with immediate instead of an insert*128.
4356   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4357   // extend the subvector to the size of the result vector. Make sure that
4358   // we are not recursing on that node by checking for undef here.
4359   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4360       Result.getOpcode() != ISD::UNDEF) {
4361     EVT ResultVT = Result.getValueType();
4362     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4363     SDValue Undef = DAG.getUNDEF(ResultVT);
4364     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4365                                  Vec, ZeroIndex);
4366
4367     // The blend instruction, and therefore its mask, depend on the data type.
4368     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4369     if (ScalarType.isFloatingPoint()) {
4370       // Choose either vblendps (float) or vblendpd (double).
4371       unsigned ScalarSize = ScalarType.getSizeInBits();
4372       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4373       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4374       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4375       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4376     }
4377
4378     const X86Subtarget &Subtarget =
4379     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4380
4381     // AVX2 is needed for 256-bit integer blend support.
4382     // Integers must be cast to 32-bit because there is only vpblendd;
4383     // vpblendw can't be used for this because it has a handicapped mask.
4384
4385     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4386     // is still more efficient than using the wrong domain vinsertf128 that
4387     // will be created by InsertSubVector().
4388     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4389
4390     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4391     Vec256 = DAG.getBitcast(CastVT, Vec256);
4392     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4393     return DAG.getBitcast(ResultVT, Vec256);
4394   }
4395
4396   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4397 }
4398
4399 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4400                                   SelectionDAG &DAG, SDLoc dl) {
4401   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4402   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4403 }
4404
4405 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4406 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4407 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4408 /// large BUILD_VECTORS.
4409 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4410                                    unsigned NumElems, SelectionDAG &DAG,
4411                                    SDLoc dl) {
4412   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4413   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4414 }
4415
4416 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4417                                    unsigned NumElems, SelectionDAG &DAG,
4418                                    SDLoc dl) {
4419   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4420   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4421 }
4422
4423 /// Returns a vector of specified type with all bits set.
4424 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4425 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4426 /// Then bitcast to their original type, ensuring they get CSE'd.
4427 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4428                              SDLoc dl) {
4429   assert(VT.isVector() && "Expected a vector type");
4430
4431   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4432   SDValue Vec;
4433   if (VT.is256BitVector()) {
4434     if (HasInt256) { // AVX2
4435       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4436       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4437     } else { // AVX
4438       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4439       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4440     }
4441   } else if (VT.is128BitVector()) {
4442     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4443   } else
4444     llvm_unreachable("Unexpected vector type");
4445
4446   return DAG.getBitcast(VT, Vec);
4447 }
4448
4449 /// Returns a vector_shuffle node for an unpackl operation.
4450 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4451                           SDValue V2) {
4452   unsigned NumElems = VT.getVectorNumElements();
4453   SmallVector<int, 8> Mask;
4454   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4455     Mask.push_back(i);
4456     Mask.push_back(i + NumElems);
4457   }
4458   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4459 }
4460
4461 /// Returns a vector_shuffle node for an unpackh operation.
4462 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4463                           SDValue V2) {
4464   unsigned NumElems = VT.getVectorNumElements();
4465   SmallVector<int, 8> Mask;
4466   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4467     Mask.push_back(i + Half);
4468     Mask.push_back(i + NumElems + Half);
4469   }
4470   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4471 }
4472
4473 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4474 /// This produces a shuffle where the low element of V2 is swizzled into the
4475 /// zero/undef vector, landing at element Idx.
4476 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4477 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4478                                            bool IsZero,
4479                                            const X86Subtarget *Subtarget,
4480                                            SelectionDAG &DAG) {
4481   MVT VT = V2.getSimpleValueType();
4482   SDValue V1 = IsZero
4483     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4484   unsigned NumElems = VT.getVectorNumElements();
4485   SmallVector<int, 16> MaskVec;
4486   for (unsigned i = 0; i != NumElems; ++i)
4487     // If this is the insertion idx, put the low elt of V2 here.
4488     MaskVec.push_back(i == Idx ? NumElems : i);
4489   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4490 }
4491
4492 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4493 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4494 /// uses one source. Note that this will set IsUnary for shuffles which use a
4495 /// single input multiple times, and in those cases it will
4496 /// adjust the mask to only have indices within that single input.
4497 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4498 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4499                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4500   unsigned NumElems = VT.getVectorNumElements();
4501   SDValue ImmN;
4502
4503   IsUnary = false;
4504   bool IsFakeUnary = false;
4505   switch(N->getOpcode()) {
4506   case X86ISD::BLENDI:
4507     ImmN = N->getOperand(N->getNumOperands()-1);
4508     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4509     break;
4510   case X86ISD::SHUFP:
4511     ImmN = N->getOperand(N->getNumOperands()-1);
4512     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4513     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4514     break;
4515   case X86ISD::UNPCKH:
4516     DecodeUNPCKHMask(VT, Mask);
4517     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4518     break;
4519   case X86ISD::UNPCKL:
4520     DecodeUNPCKLMask(VT, Mask);
4521     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4522     break;
4523   case X86ISD::MOVHLPS:
4524     DecodeMOVHLPSMask(NumElems, Mask);
4525     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4526     break;
4527   case X86ISD::MOVLHPS:
4528     DecodeMOVLHPSMask(NumElems, Mask);
4529     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4530     break;
4531   case X86ISD::PALIGNR:
4532     ImmN = N->getOperand(N->getNumOperands()-1);
4533     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4534     break;
4535   case X86ISD::PSHUFD:
4536   case X86ISD::VPERMILPI:
4537     ImmN = N->getOperand(N->getNumOperands()-1);
4538     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4539     IsUnary = true;
4540     break;
4541   case X86ISD::PSHUFHW:
4542     ImmN = N->getOperand(N->getNumOperands()-1);
4543     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4544     IsUnary = true;
4545     break;
4546   case X86ISD::PSHUFLW:
4547     ImmN = N->getOperand(N->getNumOperands()-1);
4548     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4549     IsUnary = true;
4550     break;
4551   case X86ISD::PSHUFB: {
4552     IsUnary = true;
4553     SDValue MaskNode = N->getOperand(1);
4554     while (MaskNode->getOpcode() == ISD::BITCAST)
4555       MaskNode = MaskNode->getOperand(0);
4556
4557     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4558       // If we have a build-vector, then things are easy.
4559       EVT VT = MaskNode.getValueType();
4560       assert(VT.isVector() &&
4561              "Can't produce a non-vector with a build_vector!");
4562       if (!VT.isInteger())
4563         return false;
4564
4565       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4566
4567       SmallVector<uint64_t, 32> RawMask;
4568       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4569         SDValue Op = MaskNode->getOperand(i);
4570         if (Op->getOpcode() == ISD::UNDEF) {
4571           RawMask.push_back((uint64_t)SM_SentinelUndef);
4572           continue;
4573         }
4574         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4575         if (!CN)
4576           return false;
4577         APInt MaskElement = CN->getAPIntValue();
4578
4579         // We now have to decode the element which could be any integer size and
4580         // extract each byte of it.
4581         for (int j = 0; j < NumBytesPerElement; ++j) {
4582           // Note that this is x86 and so always little endian: the low byte is
4583           // the first byte of the mask.
4584           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4585           MaskElement = MaskElement.lshr(8);
4586         }
4587       }
4588       DecodePSHUFBMask(RawMask, Mask);
4589       break;
4590     }
4591
4592     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4593     if (!MaskLoad)
4594       return false;
4595
4596     SDValue Ptr = MaskLoad->getBasePtr();
4597     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4598         Ptr->getOpcode() == X86ISD::WrapperRIP)
4599       Ptr = Ptr->getOperand(0);
4600
4601     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4602     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4603       return false;
4604
4605     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4606       DecodePSHUFBMask(C, Mask);
4607       if (Mask.empty())
4608         return false;
4609       break;
4610     }
4611
4612     return false;
4613   }
4614   case X86ISD::VPERMI:
4615     ImmN = N->getOperand(N->getNumOperands()-1);
4616     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4617     IsUnary = true;
4618     break;
4619   case X86ISD::MOVSS:
4620   case X86ISD::MOVSD:
4621     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4622     break;
4623   case X86ISD::VPERM2X128:
4624     ImmN = N->getOperand(N->getNumOperands()-1);
4625     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4626     if (Mask.empty()) return false;
4627     // Mask only contains negative index if an element is zero.
4628     if (std::any_of(Mask.begin(), Mask.end(),
4629                     [](int M){ return M == SM_SentinelZero; }))
4630       return false;
4631     break;
4632   case X86ISD::MOVSLDUP:
4633     DecodeMOVSLDUPMask(VT, Mask);
4634     IsUnary = true;
4635     break;
4636   case X86ISD::MOVSHDUP:
4637     DecodeMOVSHDUPMask(VT, Mask);
4638     IsUnary = true;
4639     break;
4640   case X86ISD::MOVDDUP:
4641     DecodeMOVDDUPMask(VT, Mask);
4642     IsUnary = true;
4643     break;
4644   case X86ISD::MOVLHPD:
4645   case X86ISD::MOVLPD:
4646   case X86ISD::MOVLPS:
4647     // Not yet implemented
4648     return false;
4649   default: llvm_unreachable("unknown target shuffle node");
4650   }
4651
4652   // If we have a fake unary shuffle, the shuffle mask is spread across two
4653   // inputs that are actually the same node. Re-map the mask to always point
4654   // into the first input.
4655   if (IsFakeUnary)
4656     for (int &M : Mask)
4657       if (M >= (int)Mask.size())
4658         M -= Mask.size();
4659
4660   return true;
4661 }
4662
4663 /// Returns the scalar element that will make up the ith
4664 /// element of the result of the vector shuffle.
4665 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4666                                    unsigned Depth) {
4667   if (Depth == 6)
4668     return SDValue();  // Limit search depth.
4669
4670   SDValue V = SDValue(N, 0);
4671   EVT VT = V.getValueType();
4672   unsigned Opcode = V.getOpcode();
4673
4674   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4675   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4676     int Elt = SV->getMaskElt(Index);
4677
4678     if (Elt < 0)
4679       return DAG.getUNDEF(VT.getVectorElementType());
4680
4681     unsigned NumElems = VT.getVectorNumElements();
4682     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4683                                          : SV->getOperand(1);
4684     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4685   }
4686
4687   // Recurse into target specific vector shuffles to find scalars.
4688   if (isTargetShuffle(Opcode)) {
4689     MVT ShufVT = V.getSimpleValueType();
4690     unsigned NumElems = ShufVT.getVectorNumElements();
4691     SmallVector<int, 16> ShuffleMask;
4692     bool IsUnary;
4693
4694     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4695       return SDValue();
4696
4697     int Elt = ShuffleMask[Index];
4698     if (Elt < 0)
4699       return DAG.getUNDEF(ShufVT.getVectorElementType());
4700
4701     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4702                                          : N->getOperand(1);
4703     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4704                                Depth+1);
4705   }
4706
4707   // Actual nodes that may contain scalar elements
4708   if (Opcode == ISD::BITCAST) {
4709     V = V.getOperand(0);
4710     EVT SrcVT = V.getValueType();
4711     unsigned NumElems = VT.getVectorNumElements();
4712
4713     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4714       return SDValue();
4715   }
4716
4717   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4718     return (Index == 0) ? V.getOperand(0)
4719                         : DAG.getUNDEF(VT.getVectorElementType());
4720
4721   if (V.getOpcode() == ISD::BUILD_VECTOR)
4722     return V.getOperand(Index);
4723
4724   return SDValue();
4725 }
4726
4727 /// Custom lower build_vector of v16i8.
4728 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4729                                        unsigned NumNonZero, unsigned NumZero,
4730                                        SelectionDAG &DAG,
4731                                        const X86Subtarget* Subtarget,
4732                                        const TargetLowering &TLI) {
4733   if (NumNonZero > 8)
4734     return SDValue();
4735
4736   SDLoc dl(Op);
4737   SDValue V;
4738   bool First = true;
4739
4740   // SSE4.1 - use PINSRB to insert each byte directly.
4741   if (Subtarget->hasSSE41()) {
4742     for (unsigned i = 0; i < 16; ++i) {
4743       bool isNonZero = (NonZeros & (1 << i)) != 0;
4744       if (isNonZero) {
4745         if (First) {
4746           if (NumZero)
4747             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4748           else
4749             V = DAG.getUNDEF(MVT::v16i8);
4750           First = false;
4751         }
4752         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4753                         MVT::v16i8, V, Op.getOperand(i),
4754                         DAG.getIntPtrConstant(i, dl));
4755       }
4756     }
4757
4758     return V;
4759   }
4760
4761   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4762   for (unsigned i = 0; i < 16; ++i) {
4763     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4764     if (ThisIsNonZero && First) {
4765       if (NumZero)
4766         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4767       else
4768         V = DAG.getUNDEF(MVT::v8i16);
4769       First = false;
4770     }
4771
4772     if ((i & 1) != 0) {
4773       SDValue ThisElt, LastElt;
4774       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4775       if (LastIsNonZero) {
4776         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4777                               MVT::i16, Op.getOperand(i-1));
4778       }
4779       if (ThisIsNonZero) {
4780         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4781         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4782                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4783         if (LastIsNonZero)
4784           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4785       } else
4786         ThisElt = LastElt;
4787
4788       if (ThisElt.getNode())
4789         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4790                         DAG.getIntPtrConstant(i/2, dl));
4791     }
4792   }
4793
4794   return DAG.getBitcast(MVT::v16i8, V);
4795 }
4796
4797 /// Custom lower build_vector of v8i16.
4798 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4799                                      unsigned NumNonZero, unsigned NumZero,
4800                                      SelectionDAG &DAG,
4801                                      const X86Subtarget* Subtarget,
4802                                      const TargetLowering &TLI) {
4803   if (NumNonZero > 4)
4804     return SDValue();
4805
4806   SDLoc dl(Op);
4807   SDValue V;
4808   bool First = true;
4809   for (unsigned i = 0; i < 8; ++i) {
4810     bool isNonZero = (NonZeros & (1 << i)) != 0;
4811     if (isNonZero) {
4812       if (First) {
4813         if (NumZero)
4814           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4815         else
4816           V = DAG.getUNDEF(MVT::v8i16);
4817         First = false;
4818       }
4819       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4820                       MVT::v8i16, V, Op.getOperand(i),
4821                       DAG.getIntPtrConstant(i, dl));
4822     }
4823   }
4824
4825   return V;
4826 }
4827
4828 /// Custom lower build_vector of v4i32 or v4f32.
4829 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4830                                      const X86Subtarget *Subtarget,
4831                                      const TargetLowering &TLI) {
4832   // Find all zeroable elements.
4833   std::bitset<4> Zeroable;
4834   for (int i=0; i < 4; ++i) {
4835     SDValue Elt = Op->getOperand(i);
4836     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4837   }
4838   assert(Zeroable.size() - Zeroable.count() > 1 &&
4839          "We expect at least two non-zero elements!");
4840
4841   // We only know how to deal with build_vector nodes where elements are either
4842   // zeroable or extract_vector_elt with constant index.
4843   SDValue FirstNonZero;
4844   unsigned FirstNonZeroIdx;
4845   for (unsigned i=0; i < 4; ++i) {
4846     if (Zeroable[i])
4847       continue;
4848     SDValue Elt = Op->getOperand(i);
4849     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4850         !isa<ConstantSDNode>(Elt.getOperand(1)))
4851       return SDValue();
4852     // Make sure that this node is extracting from a 128-bit vector.
4853     MVT VT = Elt.getOperand(0).getSimpleValueType();
4854     if (!VT.is128BitVector())
4855       return SDValue();
4856     if (!FirstNonZero.getNode()) {
4857       FirstNonZero = Elt;
4858       FirstNonZeroIdx = i;
4859     }
4860   }
4861
4862   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4863   SDValue V1 = FirstNonZero.getOperand(0);
4864   MVT VT = V1.getSimpleValueType();
4865
4866   // See if this build_vector can be lowered as a blend with zero.
4867   SDValue Elt;
4868   unsigned EltMaskIdx, EltIdx;
4869   int Mask[4];
4870   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4871     if (Zeroable[EltIdx]) {
4872       // The zero vector will be on the right hand side.
4873       Mask[EltIdx] = EltIdx+4;
4874       continue;
4875     }
4876
4877     Elt = Op->getOperand(EltIdx);
4878     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4879     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4880     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4881       break;
4882     Mask[EltIdx] = EltIdx;
4883   }
4884
4885   if (EltIdx == 4) {
4886     // Let the shuffle legalizer deal with blend operations.
4887     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4888     if (V1.getSimpleValueType() != VT)
4889       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4890     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4891   }
4892
4893   // See if we can lower this build_vector to a INSERTPS.
4894   if (!Subtarget->hasSSE41())
4895     return SDValue();
4896
4897   SDValue V2 = Elt.getOperand(0);
4898   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4899     V1 = SDValue();
4900
4901   bool CanFold = true;
4902   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4903     if (Zeroable[i])
4904       continue;
4905
4906     SDValue Current = Op->getOperand(i);
4907     SDValue SrcVector = Current->getOperand(0);
4908     if (!V1.getNode())
4909       V1 = SrcVector;
4910     CanFold = SrcVector == V1 &&
4911       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4912   }
4913
4914   if (!CanFold)
4915     return SDValue();
4916
4917   assert(V1.getNode() && "Expected at least two non-zero elements!");
4918   if (V1.getSimpleValueType() != MVT::v4f32)
4919     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4920   if (V2.getSimpleValueType() != MVT::v4f32)
4921     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4922
4923   // Ok, we can emit an INSERTPS instruction.
4924   unsigned ZMask = Zeroable.to_ulong();
4925
4926   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4927   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4928   SDLoc DL(Op);
4929   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4930                                DAG.getIntPtrConstant(InsertPSMask, DL));
4931   return DAG.getBitcast(VT, Result);
4932 }
4933
4934 /// Return a vector logical shift node.
4935 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4936                          unsigned NumBits, SelectionDAG &DAG,
4937                          const TargetLowering &TLI, SDLoc dl) {
4938   assert(VT.is128BitVector() && "Unknown type for VShift");
4939   MVT ShVT = MVT::v2i64;
4940   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4941   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4942   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4943   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4944   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4945   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4946 }
4947
4948 static SDValue
4949 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4950
4951   // Check if the scalar load can be widened into a vector load. And if
4952   // the address is "base + cst" see if the cst can be "absorbed" into
4953   // the shuffle mask.
4954   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4955     SDValue Ptr = LD->getBasePtr();
4956     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4957       return SDValue();
4958     EVT PVT = LD->getValueType(0);
4959     if (PVT != MVT::i32 && PVT != MVT::f32)
4960       return SDValue();
4961
4962     int FI = -1;
4963     int64_t Offset = 0;
4964     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4965       FI = FINode->getIndex();
4966       Offset = 0;
4967     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4968                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4969       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4970       Offset = Ptr.getConstantOperandVal(1);
4971       Ptr = Ptr.getOperand(0);
4972     } else {
4973       return SDValue();
4974     }
4975
4976     // FIXME: 256-bit vector instructions don't require a strict alignment,
4977     // improve this code to support it better.
4978     unsigned RequiredAlign = VT.getSizeInBits()/8;
4979     SDValue Chain = LD->getChain();
4980     // Make sure the stack object alignment is at least 16 or 32.
4981     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4982     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4983       if (MFI->isFixedObjectIndex(FI)) {
4984         // Can't change the alignment. FIXME: It's possible to compute
4985         // the exact stack offset and reference FI + adjust offset instead.
4986         // If someone *really* cares about this. That's the way to implement it.
4987         return SDValue();
4988       } else {
4989         MFI->setObjectAlignment(FI, RequiredAlign);
4990       }
4991     }
4992
4993     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4994     // Ptr + (Offset & ~15).
4995     if (Offset < 0)
4996       return SDValue();
4997     if ((Offset % RequiredAlign) & 3)
4998       return SDValue();
4999     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5000     if (StartOffset) {
5001       SDLoc DL(Ptr);
5002       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5003                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5004     }
5005
5006     int EltNo = (Offset - StartOffset) >> 2;
5007     unsigned NumElems = VT.getVectorNumElements();
5008
5009     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5010     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5011                              LD->getPointerInfo().getWithOffset(StartOffset),
5012                              false, false, false, 0);
5013
5014     SmallVector<int, 8> Mask(NumElems, EltNo);
5015
5016     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5017   }
5018
5019   return SDValue();
5020 }
5021
5022 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5023 /// elements can be replaced by a single large load which has the same value as
5024 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5025 ///
5026 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5027 ///
5028 /// FIXME: we'd also like to handle the case where the last elements are zero
5029 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5030 /// There's even a handy isZeroNode for that purpose.
5031 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5032                                         SDLoc &DL, SelectionDAG &DAG,
5033                                         bool isAfterLegalize) {
5034   unsigned NumElems = Elts.size();
5035
5036   LoadSDNode *LDBase = nullptr;
5037   unsigned LastLoadedElt = -1U;
5038
5039   // For each element in the initializer, see if we've found a load or an undef.
5040   // If we don't find an initial load element, or later load elements are
5041   // non-consecutive, bail out.
5042   for (unsigned i = 0; i < NumElems; ++i) {
5043     SDValue Elt = Elts[i];
5044     // Look through a bitcast.
5045     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5046       Elt = Elt.getOperand(0);
5047     if (!Elt.getNode() ||
5048         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5049       return SDValue();
5050     if (!LDBase) {
5051       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5052         return SDValue();
5053       LDBase = cast<LoadSDNode>(Elt.getNode());
5054       LastLoadedElt = i;
5055       continue;
5056     }
5057     if (Elt.getOpcode() == ISD::UNDEF)
5058       continue;
5059
5060     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5061     EVT LdVT = Elt.getValueType();
5062     // Each loaded element must be the correct fractional portion of the
5063     // requested vector load.
5064     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5065       return SDValue();
5066     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5067       return SDValue();
5068     LastLoadedElt = i;
5069   }
5070
5071   // If we have found an entire vector of loads and undefs, then return a large
5072   // load of the entire vector width starting at the base pointer.  If we found
5073   // consecutive loads for the low half, generate a vzext_load node.
5074   if (LastLoadedElt == NumElems - 1) {
5075     assert(LDBase && "Did not find base load for merging consecutive loads");
5076     EVT EltVT = LDBase->getValueType(0);
5077     // Ensure that the input vector size for the merged loads matches the
5078     // cumulative size of the input elements.
5079     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5080       return SDValue();
5081
5082     if (isAfterLegalize &&
5083         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5084       return SDValue();
5085
5086     SDValue NewLd = SDValue();
5087
5088     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5089                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5090                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5091                         LDBase->getAlignment());
5092
5093     if (LDBase->hasAnyUseOfValue(1)) {
5094       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5095                                      SDValue(LDBase, 1),
5096                                      SDValue(NewLd.getNode(), 1));
5097       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5098       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5099                              SDValue(NewLd.getNode(), 1));
5100     }
5101
5102     return NewLd;
5103   }
5104
5105   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5106   //of a v4i32 / v4f32. It's probably worth generalizing.
5107   EVT EltVT = VT.getVectorElementType();
5108   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5109       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5110     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5111     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5112     SDValue ResNode =
5113         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5114                                 LDBase->getPointerInfo(),
5115                                 LDBase->getAlignment(),
5116                                 false/*isVolatile*/, true/*ReadMem*/,
5117                                 false/*WriteMem*/);
5118
5119     // Make sure the newly-created LOAD is in the same position as LDBase in
5120     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5121     // update uses of LDBase's output chain to use the TokenFactor.
5122     if (LDBase->hasAnyUseOfValue(1)) {
5123       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5124                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5125       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5126       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5127                              SDValue(ResNode.getNode(), 1));
5128     }
5129
5130     return DAG.getBitcast(VT, ResNode);
5131   }
5132   return SDValue();
5133 }
5134
5135 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5136 /// to generate a splat value for the following cases:
5137 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5138 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5139 /// a scalar load, or a constant.
5140 /// The VBROADCAST node is returned when a pattern is found,
5141 /// or SDValue() otherwise.
5142 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5143                                     SelectionDAG &DAG) {
5144   // VBROADCAST requires AVX.
5145   // TODO: Splats could be generated for non-AVX CPUs using SSE
5146   // instructions, but there's less potential gain for only 128-bit vectors.
5147   if (!Subtarget->hasAVX())
5148     return SDValue();
5149
5150   MVT VT = Op.getSimpleValueType();
5151   SDLoc dl(Op);
5152
5153   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5154          "Unsupported vector type for broadcast.");
5155
5156   SDValue Ld;
5157   bool ConstSplatVal;
5158
5159   switch (Op.getOpcode()) {
5160     default:
5161       // Unknown pattern found.
5162       return SDValue();
5163
5164     case ISD::BUILD_VECTOR: {
5165       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5166       BitVector UndefElements;
5167       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5168
5169       // We need a splat of a single value to use broadcast, and it doesn't
5170       // make any sense if the value is only in one element of the vector.
5171       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5172         return SDValue();
5173
5174       Ld = Splat;
5175       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5176                        Ld.getOpcode() == ISD::ConstantFP);
5177
5178       // Make sure that all of the users of a non-constant load are from the
5179       // BUILD_VECTOR node.
5180       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5181         return SDValue();
5182       break;
5183     }
5184
5185     case ISD::VECTOR_SHUFFLE: {
5186       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5187
5188       // Shuffles must have a splat mask where the first element is
5189       // broadcasted.
5190       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5191         return SDValue();
5192
5193       SDValue Sc = Op.getOperand(0);
5194       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5195           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5196
5197         if (!Subtarget->hasInt256())
5198           return SDValue();
5199
5200         // Use the register form of the broadcast instruction available on AVX2.
5201         if (VT.getSizeInBits() >= 256)
5202           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5203         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5204       }
5205
5206       Ld = Sc.getOperand(0);
5207       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5208                        Ld.getOpcode() == ISD::ConstantFP);
5209
5210       // The scalar_to_vector node and the suspected
5211       // load node must have exactly one user.
5212       // Constants may have multiple users.
5213
5214       // AVX-512 has register version of the broadcast
5215       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5216         Ld.getValueType().getSizeInBits() >= 32;
5217       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5218           !hasRegVer))
5219         return SDValue();
5220       break;
5221     }
5222   }
5223
5224   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5225   bool IsGE256 = (VT.getSizeInBits() >= 256);
5226
5227   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5228   // instruction to save 8 or more bytes of constant pool data.
5229   // TODO: If multiple splats are generated to load the same constant,
5230   // it may be detrimental to overall size. There needs to be a way to detect
5231   // that condition to know if this is truly a size win.
5232   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5233
5234   // Handle broadcasting a single constant scalar from the constant pool
5235   // into a vector.
5236   // On Sandybridge (no AVX2), it is still better to load a constant vector
5237   // from the constant pool and not to broadcast it from a scalar.
5238   // But override that restriction when optimizing for size.
5239   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5240   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5241     EVT CVT = Ld.getValueType();
5242     assert(!CVT.isVector() && "Must not broadcast a vector type");
5243
5244     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5245     // For size optimization, also splat v2f64 and v2i64, and for size opt
5246     // with AVX2, also splat i8 and i16.
5247     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5248     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5249         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5250       const Constant *C = nullptr;
5251       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5252         C = CI->getConstantIntValue();
5253       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5254         C = CF->getConstantFPValue();
5255
5256       assert(C && "Invalid constant type");
5257
5258       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5259       SDValue CP =
5260           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5261       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5262       Ld = DAG.getLoad(
5263           CVT, dl, DAG.getEntryNode(), CP,
5264           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5265           false, false, Alignment);
5266
5267       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5268     }
5269   }
5270
5271   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5272
5273   // Handle AVX2 in-register broadcasts.
5274   if (!IsLoad && Subtarget->hasInt256() &&
5275       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5276     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5277
5278   // The scalar source must be a normal load.
5279   if (!IsLoad)
5280     return SDValue();
5281
5282   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5283       (Subtarget->hasVLX() && ScalarSize == 64))
5284     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5285
5286   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5287   // double since there is no vbroadcastsd xmm
5288   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5289     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5290       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5291   }
5292
5293   // Unsupported broadcast.
5294   return SDValue();
5295 }
5296
5297 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5298 /// underlying vector and index.
5299 ///
5300 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5301 /// index.
5302 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5303                                          SDValue ExtIdx) {
5304   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5305   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5306     return Idx;
5307
5308   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5309   // lowered this:
5310   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5311   // to:
5312   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5313   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5314   //                           undef)
5315   //                       Constant<0>)
5316   // In this case the vector is the extract_subvector expression and the index
5317   // is 2, as specified by the shuffle.
5318   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5319   SDValue ShuffleVec = SVOp->getOperand(0);
5320   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5321   assert(ShuffleVecVT.getVectorElementType() ==
5322          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5323
5324   int ShuffleIdx = SVOp->getMaskElt(Idx);
5325   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5326     ExtractedFromVec = ShuffleVec;
5327     return ShuffleIdx;
5328   }
5329   return Idx;
5330 }
5331
5332 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5333   MVT VT = Op.getSimpleValueType();
5334
5335   // Skip if insert_vec_elt is not supported.
5336   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5337   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5338     return SDValue();
5339
5340   SDLoc DL(Op);
5341   unsigned NumElems = Op.getNumOperands();
5342
5343   SDValue VecIn1;
5344   SDValue VecIn2;
5345   SmallVector<unsigned, 4> InsertIndices;
5346   SmallVector<int, 8> Mask(NumElems, -1);
5347
5348   for (unsigned i = 0; i != NumElems; ++i) {
5349     unsigned Opc = Op.getOperand(i).getOpcode();
5350
5351     if (Opc == ISD::UNDEF)
5352       continue;
5353
5354     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5355       // Quit if more than 1 elements need inserting.
5356       if (InsertIndices.size() > 1)
5357         return SDValue();
5358
5359       InsertIndices.push_back(i);
5360       continue;
5361     }
5362
5363     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5364     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5365     // Quit if non-constant index.
5366     if (!isa<ConstantSDNode>(ExtIdx))
5367       return SDValue();
5368     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5369
5370     // Quit if extracted from vector of different type.
5371     if (ExtractedFromVec.getValueType() != VT)
5372       return SDValue();
5373
5374     if (!VecIn1.getNode())
5375       VecIn1 = ExtractedFromVec;
5376     else if (VecIn1 != ExtractedFromVec) {
5377       if (!VecIn2.getNode())
5378         VecIn2 = ExtractedFromVec;
5379       else if (VecIn2 != ExtractedFromVec)
5380         // Quit if more than 2 vectors to shuffle
5381         return SDValue();
5382     }
5383
5384     if (ExtractedFromVec == VecIn1)
5385       Mask[i] = Idx;
5386     else if (ExtractedFromVec == VecIn2)
5387       Mask[i] = Idx + NumElems;
5388   }
5389
5390   if (!VecIn1.getNode())
5391     return SDValue();
5392
5393   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5394   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5395   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5396     unsigned Idx = InsertIndices[i];
5397     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5398                      DAG.getIntPtrConstant(Idx, DL));
5399   }
5400
5401   return NV;
5402 }
5403
5404 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5405   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5406          Op.getScalarValueSizeInBits() == 1 &&
5407          "Can not convert non-constant vector");
5408   uint64_t Immediate = 0;
5409   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5410     SDValue In = Op.getOperand(idx);
5411     if (In.getOpcode() != ISD::UNDEF)
5412       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5413   }
5414   SDLoc dl(Op);
5415   MVT VT =
5416    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5417   return DAG.getConstant(Immediate, dl, VT);
5418 }
5419 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5420 SDValue
5421 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5422
5423   MVT VT = Op.getSimpleValueType();
5424   assert((VT.getVectorElementType() == MVT::i1) &&
5425          "Unexpected type in LowerBUILD_VECTORvXi1!");
5426
5427   SDLoc dl(Op);
5428   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5429     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5430     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5431     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5432   }
5433
5434   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5435     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5436     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5437     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5438   }
5439
5440   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5441     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5442     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5443       return DAG.getBitcast(VT, Imm);
5444     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5445     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5446                         DAG.getIntPtrConstant(0, dl));
5447   }
5448
5449   // Vector has one or more non-const elements
5450   uint64_t Immediate = 0;
5451   SmallVector<unsigned, 16> NonConstIdx;
5452   bool IsSplat = true;
5453   bool HasConstElts = false;
5454   int SplatIdx = -1;
5455   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5456     SDValue In = Op.getOperand(idx);
5457     if (In.getOpcode() == ISD::UNDEF)
5458       continue;
5459     if (!isa<ConstantSDNode>(In))
5460       NonConstIdx.push_back(idx);
5461     else {
5462       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5463       HasConstElts = true;
5464     }
5465     if (SplatIdx == -1)
5466       SplatIdx = idx;
5467     else if (In != Op.getOperand(SplatIdx))
5468       IsSplat = false;
5469   }
5470
5471   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5472   if (IsSplat)
5473     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5474                        DAG.getConstant(1, dl, VT),
5475                        DAG.getConstant(0, dl, VT));
5476
5477   // insert elements one by one
5478   SDValue DstVec;
5479   SDValue Imm;
5480   if (Immediate) {
5481     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5482     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5483   }
5484   else if (HasConstElts)
5485     Imm = DAG.getConstant(0, dl, VT);
5486   else
5487     Imm = DAG.getUNDEF(VT);
5488   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5489     DstVec = DAG.getBitcast(VT, Imm);
5490   else {
5491     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5492     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5493                          DAG.getIntPtrConstant(0, dl));
5494   }
5495
5496   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5497     unsigned InsertIdx = NonConstIdx[i];
5498     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5499                          Op.getOperand(InsertIdx),
5500                          DAG.getIntPtrConstant(InsertIdx, dl));
5501   }
5502   return DstVec;
5503 }
5504
5505 /// \brief Return true if \p N implements a horizontal binop and return the
5506 /// operands for the horizontal binop into V0 and V1.
5507 ///
5508 /// This is a helper function of LowerToHorizontalOp().
5509 /// This function checks that the build_vector \p N in input implements a
5510 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5511 /// operation to match.
5512 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5513 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5514 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5515 /// arithmetic sub.
5516 ///
5517 /// This function only analyzes elements of \p N whose indices are
5518 /// in range [BaseIdx, LastIdx).
5519 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5520                               SelectionDAG &DAG,
5521                               unsigned BaseIdx, unsigned LastIdx,
5522                               SDValue &V0, SDValue &V1) {
5523   EVT VT = N->getValueType(0);
5524
5525   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5526   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5527          "Invalid Vector in input!");
5528
5529   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5530   bool CanFold = true;
5531   unsigned ExpectedVExtractIdx = BaseIdx;
5532   unsigned NumElts = LastIdx - BaseIdx;
5533   V0 = DAG.getUNDEF(VT);
5534   V1 = DAG.getUNDEF(VT);
5535
5536   // Check if N implements a horizontal binop.
5537   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5538     SDValue Op = N->getOperand(i + BaseIdx);
5539
5540     // Skip UNDEFs.
5541     if (Op->getOpcode() == ISD::UNDEF) {
5542       // Update the expected vector extract index.
5543       if (i * 2 == NumElts)
5544         ExpectedVExtractIdx = BaseIdx;
5545       ExpectedVExtractIdx += 2;
5546       continue;
5547     }
5548
5549     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5550
5551     if (!CanFold)
5552       break;
5553
5554     SDValue Op0 = Op.getOperand(0);
5555     SDValue Op1 = Op.getOperand(1);
5556
5557     // Try to match the following pattern:
5558     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5559     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5560         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5561         Op0.getOperand(0) == Op1.getOperand(0) &&
5562         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5563         isa<ConstantSDNode>(Op1.getOperand(1)));
5564     if (!CanFold)
5565       break;
5566
5567     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5568     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5569
5570     if (i * 2 < NumElts) {
5571       if (V0.getOpcode() == ISD::UNDEF) {
5572         V0 = Op0.getOperand(0);
5573         if (V0.getValueType() != VT)
5574           return false;
5575       }
5576     } else {
5577       if (V1.getOpcode() == ISD::UNDEF) {
5578         V1 = Op0.getOperand(0);
5579         if (V1.getValueType() != VT)
5580           return false;
5581       }
5582       if (i * 2 == NumElts)
5583         ExpectedVExtractIdx = BaseIdx;
5584     }
5585
5586     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5587     if (I0 == ExpectedVExtractIdx)
5588       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5589     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5590       // Try to match the following dag sequence:
5591       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5592       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5593     } else
5594       CanFold = false;
5595
5596     ExpectedVExtractIdx += 2;
5597   }
5598
5599   return CanFold;
5600 }
5601
5602 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5603 /// a concat_vector.
5604 ///
5605 /// This is a helper function of LowerToHorizontalOp().
5606 /// This function expects two 256-bit vectors called V0 and V1.
5607 /// At first, each vector is split into two separate 128-bit vectors.
5608 /// Then, the resulting 128-bit vectors are used to implement two
5609 /// horizontal binary operations.
5610 ///
5611 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5612 ///
5613 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5614 /// the two new horizontal binop.
5615 /// When Mode is set, the first horizontal binop dag node would take as input
5616 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5617 /// horizontal binop dag node would take as input the lower 128-bit of V1
5618 /// and the upper 128-bit of V1.
5619 ///   Example:
5620 ///     HADD V0_LO, V0_HI
5621 ///     HADD V1_LO, V1_HI
5622 ///
5623 /// Otherwise, the first horizontal binop dag node takes as input the lower
5624 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5625 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5626 ///   Example:
5627 ///     HADD V0_LO, V1_LO
5628 ///     HADD V0_HI, V1_HI
5629 ///
5630 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5631 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5632 /// the upper 128-bits of the result.
5633 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5634                                      SDLoc DL, SelectionDAG &DAG,
5635                                      unsigned X86Opcode, bool Mode,
5636                                      bool isUndefLO, bool isUndefHI) {
5637   EVT VT = V0.getValueType();
5638   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5639          "Invalid nodes in input!");
5640
5641   unsigned NumElts = VT.getVectorNumElements();
5642   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5643   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5644   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5645   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5646   EVT NewVT = V0_LO.getValueType();
5647
5648   SDValue LO = DAG.getUNDEF(NewVT);
5649   SDValue HI = DAG.getUNDEF(NewVT);
5650
5651   if (Mode) {
5652     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5653     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5654       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5655     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5656       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5657   } else {
5658     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5659     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5660                        V1_LO->getOpcode() != ISD::UNDEF))
5661       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5662
5663     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5664                        V1_HI->getOpcode() != ISD::UNDEF))
5665       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5666   }
5667
5668   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5669 }
5670
5671 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5672 /// node.
5673 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5674                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5675   EVT VT = BV->getValueType(0);
5676   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5677       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5678     return SDValue();
5679
5680   SDLoc DL(BV);
5681   unsigned NumElts = VT.getVectorNumElements();
5682   SDValue InVec0 = DAG.getUNDEF(VT);
5683   SDValue InVec1 = DAG.getUNDEF(VT);
5684
5685   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5686           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5687
5688   // Odd-numbered elements in the input build vector are obtained from
5689   // adding two integer/float elements.
5690   // Even-numbered elements in the input build vector are obtained from
5691   // subtracting two integer/float elements.
5692   unsigned ExpectedOpcode = ISD::FSUB;
5693   unsigned NextExpectedOpcode = ISD::FADD;
5694   bool AddFound = false;
5695   bool SubFound = false;
5696
5697   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5698     SDValue Op = BV->getOperand(i);
5699
5700     // Skip 'undef' values.
5701     unsigned Opcode = Op.getOpcode();
5702     if (Opcode == ISD::UNDEF) {
5703       std::swap(ExpectedOpcode, NextExpectedOpcode);
5704       continue;
5705     }
5706
5707     // Early exit if we found an unexpected opcode.
5708     if (Opcode != ExpectedOpcode)
5709       return SDValue();
5710
5711     SDValue Op0 = Op.getOperand(0);
5712     SDValue Op1 = Op.getOperand(1);
5713
5714     // Try to match the following pattern:
5715     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5716     // Early exit if we cannot match that sequence.
5717     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5718         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5719         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5720         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5721         Op0.getOperand(1) != Op1.getOperand(1))
5722       return SDValue();
5723
5724     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5725     if (I0 != i)
5726       return SDValue();
5727
5728     // We found a valid add/sub node. Update the information accordingly.
5729     if (i & 1)
5730       AddFound = true;
5731     else
5732       SubFound = true;
5733
5734     // Update InVec0 and InVec1.
5735     if (InVec0.getOpcode() == ISD::UNDEF) {
5736       InVec0 = Op0.getOperand(0);
5737       if (InVec0.getValueType() != VT)
5738         return SDValue();
5739     }
5740     if (InVec1.getOpcode() == ISD::UNDEF) {
5741       InVec1 = Op1.getOperand(0);
5742       if (InVec1.getValueType() != VT)
5743         return SDValue();
5744     }
5745
5746     // Make sure that operands in input to each add/sub node always
5747     // come from a same pair of vectors.
5748     if (InVec0 != Op0.getOperand(0)) {
5749       if (ExpectedOpcode == ISD::FSUB)
5750         return SDValue();
5751
5752       // FADD is commutable. Try to commute the operands
5753       // and then test again.
5754       std::swap(Op0, Op1);
5755       if (InVec0 != Op0.getOperand(0))
5756         return SDValue();
5757     }
5758
5759     if (InVec1 != Op1.getOperand(0))
5760       return SDValue();
5761
5762     // Update the pair of expected opcodes.
5763     std::swap(ExpectedOpcode, NextExpectedOpcode);
5764   }
5765
5766   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5767   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5768       InVec1.getOpcode() != ISD::UNDEF)
5769     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5770
5771   return SDValue();
5772 }
5773
5774 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5775 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5776                                    const X86Subtarget *Subtarget,
5777                                    SelectionDAG &DAG) {
5778   EVT VT = BV->getValueType(0);
5779   unsigned NumElts = VT.getVectorNumElements();
5780   unsigned NumUndefsLO = 0;
5781   unsigned NumUndefsHI = 0;
5782   unsigned Half = NumElts/2;
5783
5784   // Count the number of UNDEF operands in the build_vector in input.
5785   for (unsigned i = 0, e = Half; i != e; ++i)
5786     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5787       NumUndefsLO++;
5788
5789   for (unsigned i = Half, e = NumElts; i != e; ++i)
5790     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5791       NumUndefsHI++;
5792
5793   // Early exit if this is either a build_vector of all UNDEFs or all the
5794   // operands but one are UNDEF.
5795   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5796     return SDValue();
5797
5798   SDLoc DL(BV);
5799   SDValue InVec0, InVec1;
5800   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5801     // Try to match an SSE3 float HADD/HSUB.
5802     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5803       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5804
5805     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5806       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5807   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5808     // Try to match an SSSE3 integer HADD/HSUB.
5809     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5810       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5811
5812     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5813       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5814   }
5815
5816   if (!Subtarget->hasAVX())
5817     return SDValue();
5818
5819   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5820     // Try to match an AVX horizontal add/sub of packed single/double
5821     // precision floating point values from 256-bit vectors.
5822     SDValue InVec2, InVec3;
5823     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5824         isHorizontalBinOp(BV, ISD::FADD, 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::FHADD, DL, VT, InVec0, InVec1);
5830
5831     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5832         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5833         ((InVec0.getOpcode() == ISD::UNDEF ||
5834           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5835         ((InVec1.getOpcode() == ISD::UNDEF ||
5836           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5837       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5838   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5839     // Try to match an AVX2 horizontal add/sub of signed integers.
5840     SDValue InVec2, InVec3;
5841     unsigned X86Opcode;
5842     bool CanFold = true;
5843
5844     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5845         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5846         ((InVec0.getOpcode() == ISD::UNDEF ||
5847           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5848         ((InVec1.getOpcode() == ISD::UNDEF ||
5849           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5850       X86Opcode = X86ISD::HADD;
5851     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5852         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5853         ((InVec0.getOpcode() == ISD::UNDEF ||
5854           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5855         ((InVec1.getOpcode() == ISD::UNDEF ||
5856           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5857       X86Opcode = X86ISD::HSUB;
5858     else
5859       CanFold = false;
5860
5861     if (CanFold) {
5862       // Fold this build_vector into a single horizontal add/sub.
5863       // Do this only if the target has AVX2.
5864       if (Subtarget->hasAVX2())
5865         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5866
5867       // Do not try to expand this build_vector into a pair of horizontal
5868       // add/sub if we can emit a pair of scalar add/sub.
5869       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5870         return SDValue();
5871
5872       // Convert this build_vector into a pair of horizontal binop followed by
5873       // a concat vector.
5874       bool isUndefLO = NumUndefsLO == Half;
5875       bool isUndefHI = NumUndefsHI == Half;
5876       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5877                                    isUndefLO, isUndefHI);
5878     }
5879   }
5880
5881   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5882        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5883     unsigned X86Opcode;
5884     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5885       X86Opcode = X86ISD::HADD;
5886     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5887       X86Opcode = X86ISD::HSUB;
5888     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5889       X86Opcode = X86ISD::FHADD;
5890     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5891       X86Opcode = X86ISD::FHSUB;
5892     else
5893       return SDValue();
5894
5895     // Don't try to expand this build_vector into a pair of horizontal add/sub
5896     // if we can simply emit a pair of scalar add/sub.
5897     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5898       return SDValue();
5899
5900     // Convert this build_vector into two horizontal add/sub followed by
5901     // a concat vector.
5902     bool isUndefLO = NumUndefsLO == Half;
5903     bool isUndefHI = NumUndefsHI == Half;
5904     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5905                                  isUndefLO, isUndefHI);
5906   }
5907
5908   return SDValue();
5909 }
5910
5911 SDValue
5912 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5913   SDLoc dl(Op);
5914
5915   MVT VT = Op.getSimpleValueType();
5916   MVT ExtVT = VT.getVectorElementType();
5917   unsigned NumElems = Op.getNumOperands();
5918
5919   // Generate vectors for predicate vectors.
5920   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5921     return LowerBUILD_VECTORvXi1(Op, DAG);
5922
5923   // Vectors containing all zeros can be matched by pxor and xorps later
5924   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5925     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5926     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5927     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5928       return Op;
5929
5930     return getZeroVector(VT, Subtarget, DAG, dl);
5931   }
5932
5933   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5934   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5935   // vpcmpeqd on 256-bit vectors.
5936   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5937     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5938       return Op;
5939
5940     if (!VT.is512BitVector())
5941       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5942   }
5943
5944   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5945   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5946     return AddSub;
5947   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5948     return HorizontalOp;
5949   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5950     return Broadcast;
5951
5952   unsigned EVTBits = ExtVT.getSizeInBits();
5953
5954   unsigned NumZero  = 0;
5955   unsigned NumNonZero = 0;
5956   unsigned NonZeros = 0;
5957   bool IsAllConstants = true;
5958   SmallSet<SDValue, 8> Values;
5959   for (unsigned i = 0; i < NumElems; ++i) {
5960     SDValue Elt = Op.getOperand(i);
5961     if (Elt.getOpcode() == ISD::UNDEF)
5962       continue;
5963     Values.insert(Elt);
5964     if (Elt.getOpcode() != ISD::Constant &&
5965         Elt.getOpcode() != ISD::ConstantFP)
5966       IsAllConstants = false;
5967     if (X86::isZeroNode(Elt))
5968       NumZero++;
5969     else {
5970       NonZeros |= (1 << i);
5971       NumNonZero++;
5972     }
5973   }
5974
5975   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5976   if (NumNonZero == 0)
5977     return DAG.getUNDEF(VT);
5978
5979   // Special case for single non-zero, non-undef, element.
5980   if (NumNonZero == 1) {
5981     unsigned Idx = countTrailingZeros(NonZeros);
5982     SDValue Item = Op.getOperand(Idx);
5983
5984     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5985     // the value are obviously zero, truncate the value to i32 and do the
5986     // insertion that way.  Only do this if the value is non-constant or if the
5987     // value is a constant being inserted into element 0.  It is cheaper to do
5988     // a constant pool load than it is to do a movd + shuffle.
5989     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5990         (!IsAllConstants || Idx == 0)) {
5991       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5992         // Handle SSE only.
5993         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5994         EVT VecVT = MVT::v4i32;
5995
5996         // Truncate the value (which may itself be a constant) to i32, and
5997         // convert it to a vector with movd (S2V+shuffle to zero extend).
5998         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5999         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6000         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6001                                       Item, Idx * 2, true, Subtarget, DAG));
6002       }
6003     }
6004
6005     // If we have a constant or non-constant insertion into the low element of
6006     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6007     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6008     // depending on what the source datatype is.
6009     if (Idx == 0) {
6010       if (NumZero == 0)
6011         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6012
6013       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6014           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6015         if (VT.is512BitVector()) {
6016           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6017           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6018                              Item, DAG.getIntPtrConstant(0, dl));
6019         }
6020         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6021                "Expected an SSE value type!");
6022         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6023         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6024         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6025       }
6026
6027       // We can't directly insert an i8 or i16 into a vector, so zero extend
6028       // it to i32 first.
6029       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6030         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6031         if (VT.is256BitVector()) {
6032           if (Subtarget->hasAVX()) {
6033             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6034             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6035           } else {
6036             // Without AVX, we need to extend to a 128-bit vector and then
6037             // insert into the 256-bit vector.
6038             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6039             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6040             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6041           }
6042         } else {
6043           assert(VT.is128BitVector() && "Expected an SSE value type!");
6044           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6045           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6046         }
6047         return DAG.getBitcast(VT, Item);
6048       }
6049     }
6050
6051     // Is it a vector logical left shift?
6052     if (NumElems == 2 && Idx == 1 &&
6053         X86::isZeroNode(Op.getOperand(0)) &&
6054         !X86::isZeroNode(Op.getOperand(1))) {
6055       unsigned NumBits = VT.getSizeInBits();
6056       return getVShift(true, VT,
6057                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6058                                    VT, Op.getOperand(1)),
6059                        NumBits/2, DAG, *this, dl);
6060     }
6061
6062     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6063       return SDValue();
6064
6065     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6066     // is a non-constant being inserted into an element other than the low one,
6067     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6068     // movd/movss) to move this into the low element, then shuffle it into
6069     // place.
6070     if (EVTBits == 32) {
6071       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6072       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6073     }
6074   }
6075
6076   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6077   if (Values.size() == 1) {
6078     if (EVTBits == 32) {
6079       // Instead of a shuffle like this:
6080       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6081       // Check if it's possible to issue this instead.
6082       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6083       unsigned Idx = countTrailingZeros(NonZeros);
6084       SDValue Item = Op.getOperand(Idx);
6085       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6086         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6087     }
6088     return SDValue();
6089   }
6090
6091   // A vector full of immediates; various special cases are already
6092   // handled, so this is best done with a single constant-pool load.
6093   if (IsAllConstants)
6094     return SDValue();
6095
6096   // For AVX-length vectors, see if we can use a vector load to get all of the
6097   // elements, otherwise build the individual 128-bit pieces and use
6098   // shuffles to put them in place.
6099   if (VT.is256BitVector() || VT.is512BitVector()) {
6100     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6101
6102     // Check for a build vector of consecutive loads.
6103     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6104       return LD;
6105
6106     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6107
6108     // Build both the lower and upper subvector.
6109     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6110                                 makeArrayRef(&V[0], NumElems/2));
6111     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6112                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6113
6114     // Recreate the wider vector with the lower and upper part.
6115     if (VT.is256BitVector())
6116       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6117     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6118   }
6119
6120   // Let legalizer expand 2-wide build_vectors.
6121   if (EVTBits == 64) {
6122     if (NumNonZero == 1) {
6123       // One half is zero or undef.
6124       unsigned Idx = countTrailingZeros(NonZeros);
6125       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6126                                  Op.getOperand(Idx));
6127       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6128     }
6129     return SDValue();
6130   }
6131
6132   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6133   if (EVTBits == 8 && NumElems == 16)
6134     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6135                                         Subtarget, *this))
6136       return V;
6137
6138   if (EVTBits == 16 && NumElems == 8)
6139     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6140                                       Subtarget, *this))
6141       return V;
6142
6143   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6144   if (EVTBits == 32 && NumElems == 4)
6145     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6146       return V;
6147
6148   // If element VT is == 32 bits, turn it into a number of shuffles.
6149   SmallVector<SDValue, 8> V(NumElems);
6150   if (NumElems == 4 && NumZero > 0) {
6151     for (unsigned i = 0; i < 4; ++i) {
6152       bool isZero = !(NonZeros & (1 << i));
6153       if (isZero)
6154         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6155       else
6156         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6157     }
6158
6159     for (unsigned i = 0; i < 2; ++i) {
6160       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6161         default: break;
6162         case 0:
6163           V[i] = V[i*2];  // Must be a zero vector.
6164           break;
6165         case 1:
6166           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6167           break;
6168         case 2:
6169           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6170           break;
6171         case 3:
6172           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6173           break;
6174       }
6175     }
6176
6177     bool Reverse1 = (NonZeros & 0x3) == 2;
6178     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6179     int MaskVec[] = {
6180       Reverse1 ? 1 : 0,
6181       Reverse1 ? 0 : 1,
6182       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6183       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6184     };
6185     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6186   }
6187
6188   if (Values.size() > 1 && VT.is128BitVector()) {
6189     // Check for a build vector of consecutive loads.
6190     for (unsigned i = 0; i < NumElems; ++i)
6191       V[i] = Op.getOperand(i);
6192
6193     // Check for elements which are consecutive loads.
6194     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6195       return LD;
6196
6197     // Check for a build vector from mostly shuffle plus few inserting.
6198     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6199       return Sh;
6200
6201     // For SSE 4.1, use insertps to put the high elements into the low element.
6202     if (Subtarget->hasSSE41()) {
6203       SDValue Result;
6204       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6205         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6206       else
6207         Result = DAG.getUNDEF(VT);
6208
6209       for (unsigned i = 1; i < NumElems; ++i) {
6210         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6211         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6212                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6213       }
6214       return Result;
6215     }
6216
6217     // Otherwise, expand into a number of unpckl*, start by extending each of
6218     // our (non-undef) elements to the full vector width with the element in the
6219     // bottom slot of the vector (which generates no code for SSE).
6220     for (unsigned i = 0; i < NumElems; ++i) {
6221       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6222         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6223       else
6224         V[i] = DAG.getUNDEF(VT);
6225     }
6226
6227     // Next, we iteratively mix elements, e.g. for v4f32:
6228     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6229     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6230     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6231     unsigned EltStride = NumElems >> 1;
6232     while (EltStride != 0) {
6233       for (unsigned i = 0; i < EltStride; ++i) {
6234         // If V[i+EltStride] is undef and this is the first round of mixing,
6235         // then it is safe to just drop this shuffle: V[i] is already in the
6236         // right place, the one element (since it's the first round) being
6237         // inserted as undef can be dropped.  This isn't safe for successive
6238         // rounds because they will permute elements within both vectors.
6239         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6240             EltStride == NumElems/2)
6241           continue;
6242
6243         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6244       }
6245       EltStride >>= 1;
6246     }
6247     return V[0];
6248   }
6249   return SDValue();
6250 }
6251
6252 // 256-bit AVX can use the vinsertf128 instruction
6253 // to create 256-bit vectors from two other 128-bit ones.
6254 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6255   SDLoc dl(Op);
6256   MVT ResVT = Op.getSimpleValueType();
6257
6258   assert((ResVT.is256BitVector() ||
6259           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6260
6261   SDValue V1 = Op.getOperand(0);
6262   SDValue V2 = Op.getOperand(1);
6263   unsigned NumElems = ResVT.getVectorNumElements();
6264   if (ResVT.is256BitVector())
6265     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6266
6267   if (Op.getNumOperands() == 4) {
6268     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6269                                 ResVT.getVectorNumElements()/2);
6270     SDValue V3 = Op.getOperand(2);
6271     SDValue V4 = Op.getOperand(3);
6272     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6273       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6274   }
6275   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6276 }
6277
6278 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6279                                        const X86Subtarget *Subtarget,
6280                                        SelectionDAG & DAG) {
6281   SDLoc dl(Op);
6282   MVT ResVT = Op.getSimpleValueType();
6283   unsigned NumOfOperands = Op.getNumOperands();
6284
6285   assert(isPowerOf2_32(NumOfOperands) &&
6286          "Unexpected number of operands in CONCAT_VECTORS");
6287
6288   if (NumOfOperands > 2) {
6289     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6290                                   ResVT.getVectorNumElements()/2);
6291     SmallVector<SDValue, 2> Ops;
6292     for (unsigned i = 0; i < NumOfOperands/2; i++)
6293       Ops.push_back(Op.getOperand(i));
6294     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6295     Ops.clear();
6296     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6297       Ops.push_back(Op.getOperand(i));
6298     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6299     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6300   }
6301
6302   SDValue V1 = Op.getOperand(0);
6303   SDValue V2 = Op.getOperand(1);
6304   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6305   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6306
6307   if (IsZeroV1 && IsZeroV2)
6308     return getZeroVector(ResVT, Subtarget, DAG, dl);
6309
6310   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6311   SDValue Undef = DAG.getUNDEF(ResVT);
6312   unsigned NumElems = ResVT.getVectorNumElements();
6313   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6314
6315   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6316   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6317   if (IsZeroV1)
6318     return V2;
6319
6320   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6321   // Zero the upper bits of V1
6322   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6323   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6324   if (IsZeroV2)
6325     return V1;
6326   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6327 }
6328
6329 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6330                                    const X86Subtarget *Subtarget,
6331                                    SelectionDAG &DAG) {
6332   MVT VT = Op.getSimpleValueType();
6333   if (VT.getVectorElementType() == MVT::i1)
6334     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6335
6336   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6337          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6338           Op.getNumOperands() == 4)));
6339
6340   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6341   // from two other 128-bit ones.
6342
6343   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6344   return LowerAVXCONCAT_VECTORS(Op, DAG);
6345 }
6346
6347
6348 //===----------------------------------------------------------------------===//
6349 // Vector shuffle lowering
6350 //
6351 // This is an experimental code path for lowering vector shuffles on x86. It is
6352 // designed to handle arbitrary vector shuffles and blends, gracefully
6353 // degrading performance as necessary. It works hard to recognize idiomatic
6354 // shuffles and lower them to optimal instruction patterns without leaving
6355 // a framework that allows reasonably efficient handling of all vector shuffle
6356 // patterns.
6357 //===----------------------------------------------------------------------===//
6358
6359 /// \brief Tiny helper function to identify a no-op mask.
6360 ///
6361 /// This is a somewhat boring predicate function. It checks whether the mask
6362 /// array input, which is assumed to be a single-input shuffle mask of the kind
6363 /// used by the X86 shuffle instructions (not a fully general
6364 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6365 /// in-place shuffle are 'no-op's.
6366 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6367   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6368     if (Mask[i] != -1 && Mask[i] != i)
6369       return false;
6370   return true;
6371 }
6372
6373 /// \brief Helper function to classify a mask as a single-input mask.
6374 ///
6375 /// This isn't a generic single-input test because in the vector shuffle
6376 /// lowering we canonicalize single inputs to be the first input operand. This
6377 /// means we can more quickly test for a single input by only checking whether
6378 /// an input from the second operand exists. We also assume that the size of
6379 /// mask corresponds to the size of the input vectors which isn't true in the
6380 /// fully general case.
6381 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6382   for (int M : Mask)
6383     if (M >= (int)Mask.size())
6384       return false;
6385   return true;
6386 }
6387
6388 /// \brief Test whether there are elements crossing 128-bit lanes in this
6389 /// shuffle mask.
6390 ///
6391 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6392 /// and we routinely test for these.
6393 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6394   int LaneSize = 128 / VT.getScalarSizeInBits();
6395   int Size = Mask.size();
6396   for (int i = 0; i < Size; ++i)
6397     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6398       return true;
6399   return false;
6400 }
6401
6402 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6403 ///
6404 /// This checks a shuffle mask to see if it is performing the same
6405 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6406 /// that it is also not lane-crossing. It may however involve a blend from the
6407 /// same lane of a second vector.
6408 ///
6409 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6410 /// non-trivial to compute in the face of undef lanes. The representation is
6411 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6412 /// entries from both V1 and V2 inputs to the wider mask.
6413 static bool
6414 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6415                                 SmallVectorImpl<int> &RepeatedMask) {
6416   int LaneSize = 128 / VT.getScalarSizeInBits();
6417   RepeatedMask.resize(LaneSize, -1);
6418   int Size = Mask.size();
6419   for (int i = 0; i < Size; ++i) {
6420     if (Mask[i] < 0)
6421       continue;
6422     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6423       // This entry crosses lanes, so there is no way to model this shuffle.
6424       return false;
6425
6426     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6427     if (RepeatedMask[i % LaneSize] == -1)
6428       // This is the first non-undef entry in this slot of a 128-bit lane.
6429       RepeatedMask[i % LaneSize] =
6430           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6431     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6432       // Found a mismatch with the repeated mask.
6433       return false;
6434   }
6435   return true;
6436 }
6437
6438 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6439 /// arguments.
6440 ///
6441 /// This is a fast way to test a shuffle mask against a fixed pattern:
6442 ///
6443 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6444 ///
6445 /// It returns true if the mask is exactly as wide as the argument list, and
6446 /// each element of the mask is either -1 (signifying undef) or the value given
6447 /// in the argument.
6448 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6449                                 ArrayRef<int> ExpectedMask) {
6450   if (Mask.size() != ExpectedMask.size())
6451     return false;
6452
6453   int Size = Mask.size();
6454
6455   // If the values are build vectors, we can look through them to find
6456   // equivalent inputs that make the shuffles equivalent.
6457   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6458   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6459
6460   for (int i = 0; i < Size; ++i)
6461     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6462       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6463       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6464       if (!MaskBV || !ExpectedBV ||
6465           MaskBV->getOperand(Mask[i] % Size) !=
6466               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6467         return false;
6468     }
6469
6470   return true;
6471 }
6472
6473 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6474 ///
6475 /// This helper function produces an 8-bit shuffle immediate corresponding to
6476 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6477 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6478 /// example.
6479 ///
6480 /// NB: We rely heavily on "undef" masks preserving the input lane.
6481 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6482                                           SelectionDAG &DAG) {
6483   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6484   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6485   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6486   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6487   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6488
6489   unsigned Imm = 0;
6490   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6491   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6492   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6493   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6494   return DAG.getConstant(Imm, DL, MVT::i8);
6495 }
6496
6497 /// \brief Compute whether each element of a shuffle is zeroable.
6498 ///
6499 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6500 /// Either it is an undef element in the shuffle mask, the element of the input
6501 /// referenced is undef, or the element of the input referenced is known to be
6502 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6503 /// as many lanes with this technique as possible to simplify the remaining
6504 /// shuffle.
6505 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6506                                                      SDValue V1, SDValue V2) {
6507   SmallBitVector Zeroable(Mask.size(), false);
6508
6509   while (V1.getOpcode() == ISD::BITCAST)
6510     V1 = V1->getOperand(0);
6511   while (V2.getOpcode() == ISD::BITCAST)
6512     V2 = V2->getOperand(0);
6513
6514   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6515   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6516
6517   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6518     int M = Mask[i];
6519     // Handle the easy cases.
6520     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6521       Zeroable[i] = true;
6522       continue;
6523     }
6524
6525     // If this is an index into a build_vector node (which has the same number
6526     // of elements), dig out the input value and use it.
6527     SDValue V = M < Size ? V1 : V2;
6528     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6529       continue;
6530
6531     SDValue Input = V.getOperand(M % Size);
6532     // The UNDEF opcode check really should be dead code here, but not quite
6533     // worth asserting on (it isn't invalid, just unexpected).
6534     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6535       Zeroable[i] = true;
6536   }
6537
6538   return Zeroable;
6539 }
6540
6541 /// \brief Try to emit a bitmask instruction for a shuffle.
6542 ///
6543 /// This handles cases where we can model a blend exactly as a bitmask due to
6544 /// one of the inputs being zeroable.
6545 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6546                                            SDValue V2, ArrayRef<int> Mask,
6547                                            SelectionDAG &DAG) {
6548   MVT EltVT = VT.getScalarType();
6549   int NumEltBits = EltVT.getSizeInBits();
6550   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6551   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6552   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6553                                     IntEltVT);
6554   if (EltVT.isFloatingPoint()) {
6555     Zero = DAG.getBitcast(EltVT, Zero);
6556     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6557   }
6558   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6559   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6560   SDValue V;
6561   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6562     if (Zeroable[i])
6563       continue;
6564     if (Mask[i] % Size != i)
6565       return SDValue(); // Not a blend.
6566     if (!V)
6567       V = Mask[i] < Size ? V1 : V2;
6568     else if (V != (Mask[i] < Size ? V1 : V2))
6569       return SDValue(); // Can only let one input through the mask.
6570
6571     VMaskOps[i] = AllOnes;
6572   }
6573   if (!V)
6574     return SDValue(); // No non-zeroable elements!
6575
6576   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6577   V = DAG.getNode(VT.isFloatingPoint()
6578                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6579                   DL, VT, V, VMask);
6580   return V;
6581 }
6582
6583 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6584 ///
6585 /// This is used as a fallback approach when first class blend instructions are
6586 /// unavailable. Currently it is only suitable for integer vectors, but could
6587 /// be generalized for floating point vectors if desirable.
6588 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6589                                             SDValue V2, ArrayRef<int> Mask,
6590                                             SelectionDAG &DAG) {
6591   assert(VT.isInteger() && "Only supports integer vector types!");
6592   MVT EltVT = VT.getScalarType();
6593   int NumEltBits = EltVT.getSizeInBits();
6594   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6595   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6596                                     EltVT);
6597   SmallVector<SDValue, 16> MaskOps;
6598   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6599     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6600       return SDValue(); // Shuffled input!
6601     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6602   }
6603
6604   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6605   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6606   // We have to cast V2 around.
6607   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6608   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6609                                       DAG.getBitcast(MaskVT, V1Mask),
6610                                       DAG.getBitcast(MaskVT, V2)));
6611   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6612 }
6613
6614 /// \brief Try to emit a blend instruction for a shuffle.
6615 ///
6616 /// This doesn't do any checks for the availability of instructions for blending
6617 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6618 /// be matched in the backend with the type given. What it does check for is
6619 /// that the shuffle mask is in fact a blend.
6620 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6621                                          SDValue V2, ArrayRef<int> Mask,
6622                                          const X86Subtarget *Subtarget,
6623                                          SelectionDAG &DAG) {
6624   unsigned BlendMask = 0;
6625   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6626     if (Mask[i] >= Size) {
6627       if (Mask[i] != i + Size)
6628         return SDValue(); // Shuffled V2 input!
6629       BlendMask |= 1u << i;
6630       continue;
6631     }
6632     if (Mask[i] >= 0 && Mask[i] != i)
6633       return SDValue(); // Shuffled V1 input!
6634   }
6635   switch (VT.SimpleTy) {
6636   case MVT::v2f64:
6637   case MVT::v4f32:
6638   case MVT::v4f64:
6639   case MVT::v8f32:
6640     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6641                        DAG.getConstant(BlendMask, DL, MVT::i8));
6642
6643   case MVT::v4i64:
6644   case MVT::v8i32:
6645     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6646     // FALLTHROUGH
6647   case MVT::v2i64:
6648   case MVT::v4i32:
6649     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6650     // that instruction.
6651     if (Subtarget->hasAVX2()) {
6652       // Scale the blend by the number of 32-bit dwords per element.
6653       int Scale =  VT.getScalarSizeInBits() / 32;
6654       BlendMask = 0;
6655       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6656         if (Mask[i] >= Size)
6657           for (int j = 0; j < Scale; ++j)
6658             BlendMask |= 1u << (i * Scale + j);
6659
6660       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6661       V1 = DAG.getBitcast(BlendVT, V1);
6662       V2 = DAG.getBitcast(BlendVT, V2);
6663       return DAG.getBitcast(
6664           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6665                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6666     }
6667     // FALLTHROUGH
6668   case MVT::v8i16: {
6669     // For integer shuffles we need to expand the mask and cast the inputs to
6670     // v8i16s prior to blending.
6671     int Scale = 8 / VT.getVectorNumElements();
6672     BlendMask = 0;
6673     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6674       if (Mask[i] >= Size)
6675         for (int j = 0; j < Scale; ++j)
6676           BlendMask |= 1u << (i * Scale + j);
6677
6678     V1 = DAG.getBitcast(MVT::v8i16, V1);
6679     V2 = DAG.getBitcast(MVT::v8i16, V2);
6680     return DAG.getBitcast(VT,
6681                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6682                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6683   }
6684
6685   case MVT::v16i16: {
6686     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6687     SmallVector<int, 8> RepeatedMask;
6688     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6689       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6690       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6691       BlendMask = 0;
6692       for (int i = 0; i < 8; ++i)
6693         if (RepeatedMask[i] >= 16)
6694           BlendMask |= 1u << i;
6695       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6696                          DAG.getConstant(BlendMask, DL, MVT::i8));
6697     }
6698   }
6699     // FALLTHROUGH
6700   case MVT::v16i8:
6701   case MVT::v32i8: {
6702     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6703            "256-bit byte-blends require AVX2 support!");
6704
6705     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6706     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6707       return Masked;
6708
6709     // Scale the blend by the number of bytes per element.
6710     int Scale = VT.getScalarSizeInBits() / 8;
6711
6712     // This form of blend is always done on bytes. Compute the byte vector
6713     // type.
6714     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6715
6716     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6717     // mix of LLVM's code generator and the x86 backend. We tell the code
6718     // generator that boolean values in the elements of an x86 vector register
6719     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6720     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6721     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6722     // of the element (the remaining are ignored) and 0 in that high bit would
6723     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6724     // the LLVM model for boolean values in vector elements gets the relevant
6725     // bit set, it is set backwards and over constrained relative to x86's
6726     // actual model.
6727     SmallVector<SDValue, 32> VSELECTMask;
6728     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6729       for (int j = 0; j < Scale; ++j)
6730         VSELECTMask.push_back(
6731             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6732                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6733                                           MVT::i8));
6734
6735     V1 = DAG.getBitcast(BlendVT, V1);
6736     V2 = DAG.getBitcast(BlendVT, V2);
6737     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6738                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6739                                                       BlendVT, VSELECTMask),
6740                                           V1, V2));
6741   }
6742
6743   default:
6744     llvm_unreachable("Not a supported integer vector type!");
6745   }
6746 }
6747
6748 /// \brief Try to lower as a blend of elements from two inputs followed by
6749 /// a single-input permutation.
6750 ///
6751 /// This matches the pattern where we can blend elements from two inputs and
6752 /// then reduce the shuffle to a single-input permutation.
6753 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6754                                                    SDValue V2,
6755                                                    ArrayRef<int> Mask,
6756                                                    SelectionDAG &DAG) {
6757   // We build up the blend mask while checking whether a blend is a viable way
6758   // to reduce the shuffle.
6759   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6760   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6761
6762   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6763     if (Mask[i] < 0)
6764       continue;
6765
6766     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6767
6768     if (BlendMask[Mask[i] % Size] == -1)
6769       BlendMask[Mask[i] % Size] = Mask[i];
6770     else if (BlendMask[Mask[i] % Size] != Mask[i])
6771       return SDValue(); // Can't blend in the needed input!
6772
6773     PermuteMask[i] = Mask[i] % Size;
6774   }
6775
6776   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6777   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6778 }
6779
6780 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6781 /// blends and permutes.
6782 ///
6783 /// This matches the extremely common pattern for handling combined
6784 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6785 /// operations. It will try to pick the best arrangement of shuffles and
6786 /// blends.
6787 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6788                                                           SDValue V1,
6789                                                           SDValue V2,
6790                                                           ArrayRef<int> Mask,
6791                                                           SelectionDAG &DAG) {
6792   // Shuffle the input elements into the desired positions in V1 and V2 and
6793   // blend them together.
6794   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6795   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6796   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6797   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6798     if (Mask[i] >= 0 && Mask[i] < Size) {
6799       V1Mask[i] = Mask[i];
6800       BlendMask[i] = i;
6801     } else if (Mask[i] >= Size) {
6802       V2Mask[i] = Mask[i] - Size;
6803       BlendMask[i] = i + Size;
6804     }
6805
6806   // Try to lower with the simpler initial blend strategy unless one of the
6807   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6808   // shuffle may be able to fold with a load or other benefit. However, when
6809   // we'll have to do 2x as many shuffles in order to achieve this, blending
6810   // first is a better strategy.
6811   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6812     if (SDValue BlendPerm =
6813             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6814       return BlendPerm;
6815
6816   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6817   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6818   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6819 }
6820
6821 /// \brief Try to lower a vector shuffle as a byte rotation.
6822 ///
6823 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6824 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6825 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6826 /// try to generically lower a vector shuffle through such an pattern. It
6827 /// does not check for the profitability of lowering either as PALIGNR or
6828 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6829 /// This matches shuffle vectors that look like:
6830 ///
6831 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6832 ///
6833 /// Essentially it concatenates V1 and V2, shifts right by some number of
6834 /// elements, and takes the low elements as the result. Note that while this is
6835 /// specified as a *right shift* because x86 is little-endian, it is a *left
6836 /// rotate* of the vector lanes.
6837 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6838                                               SDValue V2,
6839                                               ArrayRef<int> Mask,
6840                                               const X86Subtarget *Subtarget,
6841                                               SelectionDAG &DAG) {
6842   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6843
6844   int NumElts = Mask.size();
6845   int NumLanes = VT.getSizeInBits() / 128;
6846   int NumLaneElts = NumElts / NumLanes;
6847
6848   // We need to detect various ways of spelling a rotation:
6849   //   [11, 12, 13, 14, 15,  0,  1,  2]
6850   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6851   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6852   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6853   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6854   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6855   int Rotation = 0;
6856   SDValue Lo, Hi;
6857   for (int l = 0; l < NumElts; l += NumLaneElts) {
6858     for (int i = 0; i < NumLaneElts; ++i) {
6859       if (Mask[l + i] == -1)
6860         continue;
6861       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6862
6863       // Get the mod-Size index and lane correct it.
6864       int LaneIdx = (Mask[l + i] % NumElts) - l;
6865       // Make sure it was in this lane.
6866       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6867         return SDValue();
6868
6869       // Determine where a rotated vector would have started.
6870       int StartIdx = i - LaneIdx;
6871       if (StartIdx == 0)
6872         // The identity rotation isn't interesting, stop.
6873         return SDValue();
6874
6875       // If we found the tail of a vector the rotation must be the missing
6876       // front. If we found the head of a vector, it must be how much of the
6877       // head.
6878       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6879
6880       if (Rotation == 0)
6881         Rotation = CandidateRotation;
6882       else if (Rotation != CandidateRotation)
6883         // The rotations don't match, so we can't match this mask.
6884         return SDValue();
6885
6886       // Compute which value this mask is pointing at.
6887       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6888
6889       // Compute which of the two target values this index should be assigned
6890       // to. This reflects whether the high elements are remaining or the low
6891       // elements are remaining.
6892       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6893
6894       // Either set up this value if we've not encountered it before, or check
6895       // that it remains consistent.
6896       if (!TargetV)
6897         TargetV = MaskV;
6898       else if (TargetV != MaskV)
6899         // This may be a rotation, but it pulls from the inputs in some
6900         // unsupported interleaving.
6901         return SDValue();
6902     }
6903   }
6904
6905   // Check that we successfully analyzed the mask, and normalize the results.
6906   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6907   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6908   if (!Lo)
6909     Lo = Hi;
6910   else if (!Hi)
6911     Hi = Lo;
6912
6913   // The actual rotate instruction rotates bytes, so we need to scale the
6914   // rotation based on how many bytes are in the vector lane.
6915   int Scale = 16 / NumLaneElts;
6916
6917   // SSSE3 targets can use the palignr instruction.
6918   if (Subtarget->hasSSSE3()) {
6919     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6920     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6921     Lo = DAG.getBitcast(AlignVT, Lo);
6922     Hi = DAG.getBitcast(AlignVT, Hi);
6923
6924     return DAG.getBitcast(
6925         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
6926                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6927   }
6928
6929   assert(VT.getSizeInBits() == 128 &&
6930          "Rotate-based lowering only supports 128-bit lowering!");
6931   assert(Mask.size() <= 16 &&
6932          "Can shuffle at most 16 bytes in a 128-bit vector!");
6933
6934   // Default SSE2 implementation
6935   int LoByteShift = 16 - Rotation * Scale;
6936   int HiByteShift = Rotation * Scale;
6937
6938   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6939   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6940   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6941
6942   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6943                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6944   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6945                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6946   return DAG.getBitcast(VT,
6947                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6948 }
6949
6950 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6951 ///
6952 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6953 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6954 /// matches elements from one of the input vectors shuffled to the left or
6955 /// right with zeroable elements 'shifted in'. It handles both the strictly
6956 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6957 /// quad word lane.
6958 ///
6959 /// PSHL : (little-endian) left bit shift.
6960 /// [ zz, 0, zz,  2 ]
6961 /// [ -1, 4, zz, -1 ]
6962 /// PSRL : (little-endian) right bit shift.
6963 /// [  1, zz,  3, zz]
6964 /// [ -1, -1,  7, zz]
6965 /// PSLLDQ : (little-endian) left byte shift
6966 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6967 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6968 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6969 /// PSRLDQ : (little-endian) right byte shift
6970 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6971 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6972 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6973 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6974                                          SDValue V2, ArrayRef<int> Mask,
6975                                          SelectionDAG &DAG) {
6976   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6977
6978   int Size = Mask.size();
6979   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6980
6981   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6982     for (int i = 0; i < Size; i += Scale)
6983       for (int j = 0; j < Shift; ++j)
6984         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6985           return false;
6986
6987     return true;
6988   };
6989
6990   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6991     for (int i = 0; i != Size; i += Scale) {
6992       unsigned Pos = Left ? i + Shift : i;
6993       unsigned Low = Left ? i : i + Shift;
6994       unsigned Len = Scale - Shift;
6995       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6996                                       Low + (V == V1 ? 0 : Size)))
6997         return SDValue();
6998     }
6999
7000     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7001     bool ByteShift = ShiftEltBits > 64;
7002     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7003                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7004     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7005
7006     // Normalize the scale for byte shifts to still produce an i64 element
7007     // type.
7008     Scale = ByteShift ? Scale / 2 : Scale;
7009
7010     // We need to round trip through the appropriate type for the shift.
7011     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7012     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7013     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7014            "Illegal integer vector type");
7015     V = DAG.getBitcast(ShiftVT, V);
7016
7017     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7018                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7019     return DAG.getBitcast(VT, V);
7020   };
7021
7022   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7023   // keep doubling the size of the integer elements up to that. We can
7024   // then shift the elements of the integer vector by whole multiples of
7025   // their width within the elements of the larger integer vector. Test each
7026   // multiple to see if we can find a match with the moved element indices
7027   // and that the shifted in elements are all zeroable.
7028   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7029     for (int Shift = 1; Shift != Scale; ++Shift)
7030       for (bool Left : {true, false})
7031         if (CheckZeros(Shift, Scale, Left))
7032           for (SDValue V : {V1, V2})
7033             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7034               return Match;
7035
7036   // no match
7037   return SDValue();
7038 }
7039
7040 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7041 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7042                                            SDValue V2, ArrayRef<int> Mask,
7043                                            SelectionDAG &DAG) {
7044   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7045   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7046
7047   int Size = Mask.size();
7048   int HalfSize = Size / 2;
7049   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7050
7051   // Upper half must be undefined.
7052   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7053     return SDValue();
7054
7055   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7056   // Remainder of lower half result is zero and upper half is all undef.
7057   auto LowerAsEXTRQ = [&]() {
7058     // Determine the extraction length from the part of the
7059     // lower half that isn't zeroable.
7060     int Len = HalfSize;
7061     for (; Len >= 0; --Len)
7062       if (!Zeroable[Len - 1])
7063         break;
7064     assert(Len > 0 && "Zeroable shuffle mask");
7065
7066     // Attempt to match first Len sequential elements from the lower half.
7067     SDValue Src;
7068     int Idx = -1;
7069     for (int i = 0; i != Len; ++i) {
7070       int M = Mask[i];
7071       if (M < 0)
7072         continue;
7073       SDValue &V = (M < Size ? V1 : V2);
7074       M = M % Size;
7075
7076       // All mask elements must be in the lower half.
7077       if (M > HalfSize)
7078         return SDValue();
7079
7080       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7081         Src = V;
7082         Idx = M - i;
7083         continue;
7084       }
7085       return SDValue();
7086     }
7087
7088     if (Idx < 0)
7089       return SDValue();
7090
7091     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7092     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7093     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7094     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7095                        DAG.getConstant(BitLen, DL, MVT::i8),
7096                        DAG.getConstant(BitIdx, DL, MVT::i8));
7097   };
7098
7099   if (SDValue ExtrQ = LowerAsEXTRQ())
7100     return ExtrQ;
7101
7102   // INSERTQ: Extract lowest Len elements from lower half of second source and
7103   // insert over first source, starting at Idx.
7104   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7105   auto LowerAsInsertQ = [&]() {
7106     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7107       SDValue Base;
7108
7109       // Attempt to match first source from mask before insertion point.
7110       if (isUndefInRange(Mask, 0, Idx)) {
7111         /* EMPTY */
7112       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7113         Base = V1;
7114       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7115         Base = V2;
7116       } else {
7117         continue;
7118       }
7119
7120       // Extend the extraction length looking to match both the insertion of
7121       // the second source and the remaining elements of the first.
7122       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7123         SDValue Insert;
7124         int Len = Hi - Idx;
7125
7126         // Match insertion.
7127         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7128           Insert = V1;
7129         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7130           Insert = V2;
7131         } else {
7132           continue;
7133         }
7134
7135         // Match the remaining elements of the lower half.
7136         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7137           /* EMPTY */
7138         } else if ((!Base || (Base == V1)) &&
7139                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7140           Base = V1;
7141         } else if ((!Base || (Base == V2)) &&
7142                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7143                                               Size + Hi)) {
7144           Base = V2;
7145         } else {
7146           continue;
7147         }
7148
7149         // We may not have a base (first source) - this can safely be undefined.
7150         if (!Base)
7151           Base = DAG.getUNDEF(VT);
7152
7153         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7154         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7155         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7156                            DAG.getConstant(BitLen, DL, MVT::i8),
7157                            DAG.getConstant(BitIdx, DL, MVT::i8));
7158       }
7159     }
7160
7161     return SDValue();
7162   };
7163
7164   if (SDValue InsertQ = LowerAsInsertQ())
7165     return InsertQ;
7166
7167   return SDValue();
7168 }
7169
7170 /// \brief Lower a vector shuffle as a zero or any extension.
7171 ///
7172 /// Given a specific number of elements, element bit width, and extension
7173 /// stride, produce either a zero or any extension based on the available
7174 /// features of the subtarget.
7175 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7176     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7177     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7178   assert(Scale > 1 && "Need a scale to extend.");
7179   int NumElements = VT.getVectorNumElements();
7180   int EltBits = VT.getScalarSizeInBits();
7181   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7182          "Only 8, 16, and 32 bit elements can be extended.");
7183   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7184
7185   // Found a valid zext mask! Try various lowering strategies based on the
7186   // input type and available ISA extensions.
7187   if (Subtarget->hasSSE41()) {
7188     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7189                                  NumElements / Scale);
7190     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7191   }
7192
7193   // For any extends we can cheat for larger element sizes and use shuffle
7194   // instructions that can fold with a load and/or copy.
7195   if (AnyExt && EltBits == 32) {
7196     int PSHUFDMask[4] = {0, -1, 1, -1};
7197     return DAG.getBitcast(
7198         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7199                         DAG.getBitcast(MVT::v4i32, InputV),
7200                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7201   }
7202   if (AnyExt && EltBits == 16 && Scale > 2) {
7203     int PSHUFDMask[4] = {0, -1, 0, -1};
7204     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7205                          DAG.getBitcast(MVT::v4i32, InputV),
7206                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7207     int PSHUFHWMask[4] = {1, -1, -1, -1};
7208     return DAG.getBitcast(
7209         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7210                         DAG.getBitcast(MVT::v8i16, InputV),
7211                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7212   }
7213
7214   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7215   // to 64-bits.
7216   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7217     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7218     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7219
7220     SDValue Lo = 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(0, DL, MVT::i8)));
7224     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7225       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7226
7227     SDValue Hi =
7228         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7229                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7230                                 DAG.getConstant(EltBits, DL, MVT::i8),
7231                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7232     return DAG.getNode(ISD::BITCAST, DL, VT,
7233                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7234   }
7235
7236   // If this would require more than 2 unpack instructions to expand, use
7237   // pshufb when available. We can only use more than 2 unpack instructions
7238   // when zero extending i8 elements which also makes it easier to use pshufb.
7239   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7240     assert(NumElements == 16 && "Unexpected byte vector width!");
7241     SDValue PSHUFBMask[16];
7242     for (int i = 0; i < 16; ++i)
7243       PSHUFBMask[i] =
7244           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7245     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7246     return DAG.getBitcast(VT,
7247                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7248                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7249                                                   MVT::v16i8, PSHUFBMask)));
7250   }
7251
7252   // Otherwise emit a sequence of unpacks.
7253   do {
7254     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7255     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7256                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7257     InputV = DAG.getBitcast(InputVT, InputV);
7258     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7259     Scale /= 2;
7260     EltBits *= 2;
7261     NumElements /= 2;
7262   } while (Scale > 1);
7263   return DAG.getBitcast(VT, InputV);
7264 }
7265
7266 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7267 ///
7268 /// This routine will try to do everything in its power to cleverly lower
7269 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7270 /// check for the profitability of this lowering,  it tries to aggressively
7271 /// match this pattern. It will use all of the micro-architectural details it
7272 /// can to emit an efficient lowering. It handles both blends with all-zero
7273 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7274 /// masking out later).
7275 ///
7276 /// The reason we have dedicated lowering for zext-style shuffles is that they
7277 /// are both incredibly common and often quite performance sensitive.
7278 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7279     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7280     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7281   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7282
7283   int Bits = VT.getSizeInBits();
7284   int NumElements = VT.getVectorNumElements();
7285   assert(VT.getScalarSizeInBits() <= 32 &&
7286          "Exceeds 32-bit integer zero extension limit");
7287   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7288
7289   // Define a helper function to check a particular ext-scale and lower to it if
7290   // valid.
7291   auto Lower = [&](int Scale) -> SDValue {
7292     SDValue InputV;
7293     bool AnyExt = true;
7294     for (int i = 0; i < NumElements; ++i) {
7295       if (Mask[i] == -1)
7296         continue; // Valid anywhere but doesn't tell us anything.
7297       if (i % Scale != 0) {
7298         // Each of the extended elements need to be zeroable.
7299         if (!Zeroable[i])
7300           return SDValue();
7301
7302         // We no longer are in the anyext case.
7303         AnyExt = false;
7304         continue;
7305       }
7306
7307       // Each of the base elements needs to be consecutive indices into the
7308       // same input vector.
7309       SDValue V = Mask[i] < NumElements ? V1 : V2;
7310       if (!InputV)
7311         InputV = V;
7312       else if (InputV != V)
7313         return SDValue(); // Flip-flopping inputs.
7314
7315       if (Mask[i] % NumElements != i / Scale)
7316         return SDValue(); // Non-consecutive strided elements.
7317     }
7318
7319     // If we fail to find an input, we have a zero-shuffle which should always
7320     // have already been handled.
7321     // FIXME: Maybe handle this here in case during blending we end up with one?
7322     if (!InputV)
7323       return SDValue();
7324
7325     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7326         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7327   };
7328
7329   // The widest scale possible for extending is to a 64-bit integer.
7330   assert(Bits % 64 == 0 &&
7331          "The number of bits in a vector must be divisible by 64 on x86!");
7332   int NumExtElements = Bits / 64;
7333
7334   // Each iteration, try extending the elements half as much, but into twice as
7335   // many elements.
7336   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7337     assert(NumElements % NumExtElements == 0 &&
7338            "The input vector size must be divisible by the extended size.");
7339     if (SDValue V = Lower(NumElements / NumExtElements))
7340       return V;
7341   }
7342
7343   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7344   if (Bits != 128)
7345     return SDValue();
7346
7347   // Returns one of the source operands if the shuffle can be reduced to a
7348   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7349   auto CanZExtLowHalf = [&]() {
7350     for (int i = NumElements / 2; i != NumElements; ++i)
7351       if (!Zeroable[i])
7352         return SDValue();
7353     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7354       return V1;
7355     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7356       return V2;
7357     return SDValue();
7358   };
7359
7360   if (SDValue V = CanZExtLowHalf()) {
7361     V = DAG.getBitcast(MVT::v2i64, V);
7362     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7363     return DAG.getBitcast(VT, V);
7364   }
7365
7366   // No viable ext lowering found.
7367   return SDValue();
7368 }
7369
7370 /// \brief Try to get a scalar value for a specific element of a vector.
7371 ///
7372 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7373 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7374                                               SelectionDAG &DAG) {
7375   MVT VT = V.getSimpleValueType();
7376   MVT EltVT = VT.getVectorElementType();
7377   while (V.getOpcode() == ISD::BITCAST)
7378     V = V.getOperand(0);
7379   // If the bitcasts shift the element size, we can't extract an equivalent
7380   // element from it.
7381   MVT NewVT = V.getSimpleValueType();
7382   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7383     return SDValue();
7384
7385   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7386       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7387     // Ensure the scalar operand is the same size as the destination.
7388     // FIXME: Add support for scalar truncation where possible.
7389     SDValue S = V.getOperand(Idx);
7390     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7391       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7392   }
7393
7394   return SDValue();
7395 }
7396
7397 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7398 ///
7399 /// This is particularly important because the set of instructions varies
7400 /// significantly based on whether the operand is a load or not.
7401 static bool isShuffleFoldableLoad(SDValue V) {
7402   while (V.getOpcode() == ISD::BITCAST)
7403     V = V.getOperand(0);
7404
7405   return ISD::isNON_EXTLoad(V.getNode());
7406 }
7407
7408 /// \brief Try to lower insertion of a single element into a zero vector.
7409 ///
7410 /// This is a common pattern that we have especially efficient patterns to lower
7411 /// across all subtarget feature sets.
7412 static SDValue lowerVectorShuffleAsElementInsertion(
7413     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7414     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7415   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7416   MVT ExtVT = VT;
7417   MVT EltVT = VT.getVectorElementType();
7418
7419   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7420                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7421                 Mask.begin();
7422   bool IsV1Zeroable = true;
7423   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7424     if (i != V2Index && !Zeroable[i]) {
7425       IsV1Zeroable = false;
7426       break;
7427     }
7428
7429   // Check for a single input from a SCALAR_TO_VECTOR node.
7430   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7431   // all the smarts here sunk into that routine. However, the current
7432   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7433   // vector shuffle lowering is dead.
7434   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7435                                                DAG);
7436   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7437     // We need to zext the scalar if it is smaller than an i32.
7438     V2S = DAG.getBitcast(EltVT, V2S);
7439     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7440       // Using zext to expand a narrow element won't work for non-zero
7441       // insertions.
7442       if (!IsV1Zeroable)
7443         return SDValue();
7444
7445       // Zero-extend directly to i32.
7446       ExtVT = MVT::v4i32;
7447       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7448     }
7449     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7450   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7451              EltVT == MVT::i16) {
7452     // Either not inserting from the low element of the input or the input
7453     // element size is too small to use VZEXT_MOVL to clear the high bits.
7454     return SDValue();
7455   }
7456
7457   if (!IsV1Zeroable) {
7458     // If V1 can't be treated as a zero vector we have fewer options to lower
7459     // this. We can't support integer vectors or non-zero targets cheaply, and
7460     // the V1 elements can't be permuted in any way.
7461     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7462     if (!VT.isFloatingPoint() || V2Index != 0)
7463       return SDValue();
7464     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7465     V1Mask[V2Index] = -1;
7466     if (!isNoopShuffleMask(V1Mask))
7467       return SDValue();
7468     // This is essentially a special case blend operation, but if we have
7469     // general purpose blend operations, they are always faster. Bail and let
7470     // the rest of the lowering handle these as blends.
7471     if (Subtarget->hasSSE41())
7472       return SDValue();
7473
7474     // Otherwise, use MOVSD or MOVSS.
7475     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7476            "Only two types of floating point element types to handle!");
7477     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7478                        ExtVT, V1, V2);
7479   }
7480
7481   // This lowering only works for the low element with floating point vectors.
7482   if (VT.isFloatingPoint() && V2Index != 0)
7483     return SDValue();
7484
7485   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7486   if (ExtVT != VT)
7487     V2 = DAG.getBitcast(VT, V2);
7488
7489   if (V2Index != 0) {
7490     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7491     // the desired position. Otherwise it is more efficient to do a vector
7492     // shift left. We know that we can do a vector shift left because all
7493     // the inputs are zero.
7494     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7495       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7496       V2Shuffle[V2Index] = 0;
7497       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7498     } else {
7499       V2 = DAG.getBitcast(MVT::v2i64, V2);
7500       V2 = DAG.getNode(
7501           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7502           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7503                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7504                               DAG.getDataLayout(), VT)));
7505       V2 = DAG.getBitcast(VT, V2);
7506     }
7507   }
7508   return V2;
7509 }
7510
7511 /// \brief Try to lower broadcast of a single element.
7512 ///
7513 /// For convenience, this code also bundles all of the subtarget feature set
7514 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7515 /// a convenient way to factor it out.
7516 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7517                                              ArrayRef<int> Mask,
7518                                              const X86Subtarget *Subtarget,
7519                                              SelectionDAG &DAG) {
7520   if (!Subtarget->hasAVX())
7521     return SDValue();
7522   if (VT.isInteger() && !Subtarget->hasAVX2())
7523     return SDValue();
7524
7525   // Check that the mask is a broadcast.
7526   int BroadcastIdx = -1;
7527   for (int M : Mask)
7528     if (M >= 0 && BroadcastIdx == -1)
7529       BroadcastIdx = M;
7530     else if (M >= 0 && M != BroadcastIdx)
7531       return SDValue();
7532
7533   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7534                                             "a sorted mask where the broadcast "
7535                                             "comes from V1.");
7536
7537   // Go up the chain of (vector) values to find a scalar load that we can
7538   // combine with the broadcast.
7539   for (;;) {
7540     switch (V.getOpcode()) {
7541     case ISD::CONCAT_VECTORS: {
7542       int OperandSize = Mask.size() / V.getNumOperands();
7543       V = V.getOperand(BroadcastIdx / OperandSize);
7544       BroadcastIdx %= OperandSize;
7545       continue;
7546     }
7547
7548     case ISD::INSERT_SUBVECTOR: {
7549       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7550       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7551       if (!ConstantIdx)
7552         break;
7553
7554       int BeginIdx = (int)ConstantIdx->getZExtValue();
7555       int EndIdx =
7556           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7557       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7558         BroadcastIdx -= BeginIdx;
7559         V = VInner;
7560       } else {
7561         V = VOuter;
7562       }
7563       continue;
7564     }
7565     }
7566     break;
7567   }
7568
7569   // Check if this is a broadcast of a scalar. We special case lowering
7570   // for scalars so that we can more effectively fold with loads.
7571   // First, look through bitcast: if the original value has a larger element
7572   // type than the shuffle, the broadcast element is in essence truncated.
7573   // Make that explicit to ease folding.
7574   if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7575     EVT EltVT = VT.getVectorElementType();
7576     SDValue V0 = V.getOperand(0);
7577     EVT V0VT = V0.getValueType();
7578
7579     if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7580         ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7581          (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7582       V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7583       BroadcastIdx = 0;
7584     }
7585   }
7586
7587   // Also check the simpler case, where we can directly reuse the scalar.
7588   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7589       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7590     V = V.getOperand(BroadcastIdx);
7591
7592     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7593     // Only AVX2 has register broadcasts.
7594     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7595       return SDValue();
7596   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7597     // We can't broadcast from a vector register without AVX2, and we can only
7598     // broadcast from the zero-element of a vector register.
7599     return SDValue();
7600   }
7601
7602   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7603 }
7604
7605 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7606 // INSERTPS when the V1 elements are already in the correct locations
7607 // because otherwise we can just always use two SHUFPS instructions which
7608 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7609 // perform INSERTPS if a single V1 element is out of place and all V2
7610 // elements are zeroable.
7611 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7612                                             ArrayRef<int> Mask,
7613                                             SelectionDAG &DAG) {
7614   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7615   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7616   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7617   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7618
7619   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7620
7621   unsigned ZMask = 0;
7622   int V1DstIndex = -1;
7623   int V2DstIndex = -1;
7624   bool V1UsedInPlace = false;
7625
7626   for (int i = 0; i < 4; ++i) {
7627     // Synthesize a zero mask from the zeroable elements (includes undefs).
7628     if (Zeroable[i]) {
7629       ZMask |= 1 << i;
7630       continue;
7631     }
7632
7633     // Flag if we use any V1 inputs in place.
7634     if (i == Mask[i]) {
7635       V1UsedInPlace = true;
7636       continue;
7637     }
7638
7639     // We can only insert a single non-zeroable element.
7640     if (V1DstIndex != -1 || V2DstIndex != -1)
7641       return SDValue();
7642
7643     if (Mask[i] < 4) {
7644       // V1 input out of place for insertion.
7645       V1DstIndex = i;
7646     } else {
7647       // V2 input for insertion.
7648       V2DstIndex = i;
7649     }
7650   }
7651
7652   // Don't bother if we have no (non-zeroable) element for insertion.
7653   if (V1DstIndex == -1 && V2DstIndex == -1)
7654     return SDValue();
7655
7656   // Determine element insertion src/dst indices. The src index is from the
7657   // start of the inserted vector, not the start of the concatenated vector.
7658   unsigned V2SrcIndex = 0;
7659   if (V1DstIndex != -1) {
7660     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7661     // and don't use the original V2 at all.
7662     V2SrcIndex = Mask[V1DstIndex];
7663     V2DstIndex = V1DstIndex;
7664     V2 = V1;
7665   } else {
7666     V2SrcIndex = Mask[V2DstIndex] - 4;
7667   }
7668
7669   // If no V1 inputs are used in place, then the result is created only from
7670   // the zero mask and the V2 insertion - so remove V1 dependency.
7671   if (!V1UsedInPlace)
7672     V1 = DAG.getUNDEF(MVT::v4f32);
7673
7674   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7675   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7676
7677   // Insert the V2 element into the desired position.
7678   SDLoc DL(Op);
7679   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7680                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7681 }
7682
7683 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7684 /// UNPCK instruction.
7685 ///
7686 /// This specifically targets cases where we end up with alternating between
7687 /// the two inputs, and so can permute them into something that feeds a single
7688 /// UNPCK instruction. Note that this routine only targets integer vectors
7689 /// because for floating point vectors we have a generalized SHUFPS lowering
7690 /// strategy that handles everything that doesn't *exactly* match an unpack,
7691 /// making this clever lowering unnecessary.
7692 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7693                                           SDValue V2, ArrayRef<int> Mask,
7694                                           SelectionDAG &DAG) {
7695   assert(!VT.isFloatingPoint() &&
7696          "This routine only supports integer vectors.");
7697   assert(!isSingleInputShuffleMask(Mask) &&
7698          "This routine should only be used when blending two inputs.");
7699   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7700
7701   int Size = Mask.size();
7702
7703   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7704     return M >= 0 && M % Size < Size / 2;
7705   });
7706   int NumHiInputs = std::count_if(
7707       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7708
7709   bool UnpackLo = NumLoInputs >= NumHiInputs;
7710
7711   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7712     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7713     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7714
7715     for (int i = 0; i < Size; ++i) {
7716       if (Mask[i] < 0)
7717         continue;
7718
7719       // Each element of the unpack contains Scale elements from this mask.
7720       int UnpackIdx = i / Scale;
7721
7722       // We only handle the case where V1 feeds the first slots of the unpack.
7723       // We rely on canonicalization to ensure this is the case.
7724       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7725         return SDValue();
7726
7727       // Setup the mask for this input. The indexing is tricky as we have to
7728       // handle the unpack stride.
7729       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7730       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7731           Mask[i] % Size;
7732     }
7733
7734     // If we will have to shuffle both inputs to use the unpack, check whether
7735     // we can just unpack first and shuffle the result. If so, skip this unpack.
7736     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7737         !isNoopShuffleMask(V2Mask))
7738       return SDValue();
7739
7740     // Shuffle the inputs into place.
7741     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7742     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7743
7744     // Cast the inputs to the type we will use to unpack them.
7745     V1 = DAG.getBitcast(UnpackVT, V1);
7746     V2 = DAG.getBitcast(UnpackVT, V2);
7747
7748     // Unpack the inputs and cast the result back to the desired type.
7749     return DAG.getBitcast(
7750         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7751                         UnpackVT, V1, V2));
7752   };
7753
7754   // We try each unpack from the largest to the smallest to try and find one
7755   // that fits this mask.
7756   int OrigNumElements = VT.getVectorNumElements();
7757   int OrigScalarSize = VT.getScalarSizeInBits();
7758   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7759     int Scale = ScalarSize / OrigScalarSize;
7760     int NumElements = OrigNumElements / Scale;
7761     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7762     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7763       return Unpack;
7764   }
7765
7766   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7767   // initial unpack.
7768   if (NumLoInputs == 0 || NumHiInputs == 0) {
7769     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7770            "We have to have *some* inputs!");
7771     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7772
7773     // FIXME: We could consider the total complexity of the permute of each
7774     // possible unpacking. Or at the least we should consider how many
7775     // half-crossings are created.
7776     // FIXME: We could consider commuting the unpacks.
7777
7778     SmallVector<int, 32> PermMask;
7779     PermMask.assign(Size, -1);
7780     for (int i = 0; i < Size; ++i) {
7781       if (Mask[i] < 0)
7782         continue;
7783
7784       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7785
7786       PermMask[i] =
7787           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7788     }
7789     return DAG.getVectorShuffle(
7790         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7791                             DL, VT, V1, V2),
7792         DAG.getUNDEF(VT), PermMask);
7793   }
7794
7795   return SDValue();
7796 }
7797
7798 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7799 ///
7800 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7801 /// support for floating point shuffles but not integer shuffles. These
7802 /// instructions will incur a domain crossing penalty on some chips though so
7803 /// it is better to avoid lowering through this for integer vectors where
7804 /// possible.
7805 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7806                                        const X86Subtarget *Subtarget,
7807                                        SelectionDAG &DAG) {
7808   SDLoc DL(Op);
7809   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7810   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7811   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7812   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7813   ArrayRef<int> Mask = SVOp->getMask();
7814   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7815
7816   if (isSingleInputShuffleMask(Mask)) {
7817     // Use low duplicate instructions for masks that match their pattern.
7818     if (Subtarget->hasSSE3())
7819       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7820         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7821
7822     // Straight shuffle of a single input vector. Simulate this by using the
7823     // single input as both of the "inputs" to this instruction..
7824     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7825
7826     if (Subtarget->hasAVX()) {
7827       // If we have AVX, we can use VPERMILPS which will allow folding a load
7828       // into the shuffle.
7829       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7830                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7831     }
7832
7833     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7834                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7835   }
7836   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7837   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7838
7839   // If we have a single input, insert that into V1 if we can do so cheaply.
7840   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7841     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7842             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7843       return Insertion;
7844     // Try inverting the insertion since for v2 masks it is easy to do and we
7845     // can't reliably sort the mask one way or the other.
7846     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7847                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7848     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7849             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7850       return Insertion;
7851   }
7852
7853   // Try to use one of the special instruction patterns to handle two common
7854   // blend patterns if a zero-blend above didn't work.
7855   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7856       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7857     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7858       // We can either use a special instruction to load over the low double or
7859       // to move just the low double.
7860       return DAG.getNode(
7861           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7862           DL, MVT::v2f64, V2,
7863           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7864
7865   if (Subtarget->hasSSE41())
7866     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7867                                                   Subtarget, DAG))
7868       return Blend;
7869
7870   // Use dedicated unpack instructions for masks that match their pattern.
7871   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7872     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7873   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7874     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7875
7876   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7877   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7878                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7879 }
7880
7881 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7882 ///
7883 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7884 /// the integer unit to minimize domain crossing penalties. However, for blends
7885 /// it falls back to the floating point shuffle operation with appropriate bit
7886 /// casting.
7887 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7888                                        const X86Subtarget *Subtarget,
7889                                        SelectionDAG &DAG) {
7890   SDLoc DL(Op);
7891   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7892   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7893   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7894   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7895   ArrayRef<int> Mask = SVOp->getMask();
7896   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7897
7898   if (isSingleInputShuffleMask(Mask)) {
7899     // Check for being able to broadcast a single element.
7900     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7901                                                           Mask, Subtarget, DAG))
7902       return Broadcast;
7903
7904     // Straight shuffle of a single input vector. For everything from SSE2
7905     // onward this has a single fast instruction with no scary immediates.
7906     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7907     V1 = DAG.getBitcast(MVT::v4i32, V1);
7908     int WidenedMask[4] = {
7909         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7910         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7911     return DAG.getBitcast(
7912         MVT::v2i64,
7913         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7914                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7915   }
7916   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7917   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7918   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7919   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7920
7921   // If we have a blend of two PACKUS operations an the blend aligns with the
7922   // low and half halves, we can just merge the PACKUS operations. This is
7923   // particularly important as it lets us merge shuffles that this routine itself
7924   // creates.
7925   auto GetPackNode = [](SDValue V) {
7926     while (V.getOpcode() == ISD::BITCAST)
7927       V = V.getOperand(0);
7928
7929     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7930   };
7931   if (SDValue V1Pack = GetPackNode(V1))
7932     if (SDValue V2Pack = GetPackNode(V2))
7933       return DAG.getBitcast(MVT::v2i64,
7934                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7935                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7936                                                      : V1Pack.getOperand(1),
7937                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7938                                                      : V2Pack.getOperand(1)));
7939
7940   // Try to use shift instructions.
7941   if (SDValue Shift =
7942           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7943     return Shift;
7944
7945   // When loading a scalar and then shuffling it into a vector we can often do
7946   // the insertion cheaply.
7947   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7948           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7949     return Insertion;
7950   // Try inverting the insertion since for v2 masks it is easy to do and we
7951   // can't reliably sort the mask one way or the other.
7952   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7953   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7954           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7955     return Insertion;
7956
7957   // We have different paths for blend lowering, but they all must use the
7958   // *exact* same predicate.
7959   bool IsBlendSupported = Subtarget->hasSSE41();
7960   if (IsBlendSupported)
7961     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7962                                                   Subtarget, DAG))
7963       return Blend;
7964
7965   // Use dedicated unpack instructions for masks that match their pattern.
7966   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7967     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7968   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7969     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7970
7971   // Try to use byte rotation instructions.
7972   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7973   if (Subtarget->hasSSSE3())
7974     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7975             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7976       return Rotate;
7977
7978   // If we have direct support for blends, we should lower by decomposing into
7979   // a permute. That will be faster than the domain cross.
7980   if (IsBlendSupported)
7981     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7982                                                       Mask, DAG);
7983
7984   // We implement this with SHUFPD which is pretty lame because it will likely
7985   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7986   // However, all the alternatives are still more cycles and newer chips don't
7987   // have this problem. It would be really nice if x86 had better shuffles here.
7988   V1 = DAG.getBitcast(MVT::v2f64, V1);
7989   V2 = DAG.getBitcast(MVT::v2f64, V2);
7990   return DAG.getBitcast(MVT::v2i64,
7991                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7992 }
7993
7994 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7995 ///
7996 /// This is used to disable more specialized lowerings when the shufps lowering
7997 /// will happen to be efficient.
7998 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7999   // This routine only handles 128-bit shufps.
8000   assert(Mask.size() == 4 && "Unsupported mask size!");
8001
8002   // To lower with a single SHUFPS we need to have the low half and high half
8003   // each requiring a single input.
8004   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8005     return false;
8006   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8007     return false;
8008
8009   return true;
8010 }
8011
8012 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8013 ///
8014 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8015 /// It makes no assumptions about whether this is the *best* lowering, it simply
8016 /// uses it.
8017 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8018                                             ArrayRef<int> Mask, SDValue V1,
8019                                             SDValue V2, SelectionDAG &DAG) {
8020   SDValue LowV = V1, HighV = V2;
8021   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8022
8023   int NumV2Elements =
8024       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8025
8026   if (NumV2Elements == 1) {
8027     int V2Index =
8028         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8029         Mask.begin();
8030
8031     // Compute the index adjacent to V2Index and in the same half by toggling
8032     // the low bit.
8033     int V2AdjIndex = V2Index ^ 1;
8034
8035     if (Mask[V2AdjIndex] == -1) {
8036       // Handles all the cases where we have a single V2 element and an undef.
8037       // This will only ever happen in the high lanes because we commute the
8038       // vector otherwise.
8039       if (V2Index < 2)
8040         std::swap(LowV, HighV);
8041       NewMask[V2Index] -= 4;
8042     } else {
8043       // Handle the case where the V2 element ends up adjacent to a V1 element.
8044       // To make this work, blend them together as the first step.
8045       int V1Index = V2AdjIndex;
8046       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8047       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8048                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8049
8050       // Now proceed to reconstruct the final blend as we have the necessary
8051       // high or low half formed.
8052       if (V2Index < 2) {
8053         LowV = V2;
8054         HighV = V1;
8055       } else {
8056         HighV = V2;
8057       }
8058       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8059       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8060     }
8061   } else if (NumV2Elements == 2) {
8062     if (Mask[0] < 4 && Mask[1] < 4) {
8063       // Handle the easy case where we have V1 in the low lanes and V2 in the
8064       // high lanes.
8065       NewMask[2] -= 4;
8066       NewMask[3] -= 4;
8067     } else if (Mask[2] < 4 && Mask[3] < 4) {
8068       // We also handle the reversed case because this utility may get called
8069       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8070       // arrange things in the right direction.
8071       NewMask[0] -= 4;
8072       NewMask[1] -= 4;
8073       HighV = V1;
8074       LowV = V2;
8075     } else {
8076       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8077       // trying to place elements directly, just blend them and set up the final
8078       // shuffle to place them.
8079
8080       // The first two blend mask elements are for V1, the second two are for
8081       // V2.
8082       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8083                           Mask[2] < 4 ? Mask[2] : Mask[3],
8084                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8085                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8086       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8087                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8088
8089       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8090       // a blend.
8091       LowV = HighV = V1;
8092       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8093       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8094       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8095       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8096     }
8097   }
8098   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8099                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8100 }
8101
8102 /// \brief Lower 4-lane 32-bit floating point shuffles.
8103 ///
8104 /// Uses instructions exclusively from the floating point unit to minimize
8105 /// domain crossing penalties, as these are sufficient to implement all v4f32
8106 /// shuffles.
8107 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8108                                        const X86Subtarget *Subtarget,
8109                                        SelectionDAG &DAG) {
8110   SDLoc DL(Op);
8111   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8112   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8113   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8114   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8115   ArrayRef<int> Mask = SVOp->getMask();
8116   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8117
8118   int NumV2Elements =
8119       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8120
8121   if (NumV2Elements == 0) {
8122     // Check for being able to broadcast a single element.
8123     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8124                                                           Mask, Subtarget, DAG))
8125       return Broadcast;
8126
8127     // Use even/odd duplicate instructions for masks that match their pattern.
8128     if (Subtarget->hasSSE3()) {
8129       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8130         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8131       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8132         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8133     }
8134
8135     if (Subtarget->hasAVX()) {
8136       // If we have AVX, we can use VPERMILPS which will allow folding a load
8137       // into the shuffle.
8138       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8139                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8140     }
8141
8142     // Otherwise, use a straight shuffle of a single input vector. We pass the
8143     // input vector to both operands to simulate this with a SHUFPS.
8144     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8145                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8146   }
8147
8148   // There are special ways we can lower some single-element blends. However, we
8149   // have custom ways we can lower more complex single-element blends below that
8150   // we defer to if both this and BLENDPS fail to match, so restrict this to
8151   // when the V2 input is targeting element 0 of the mask -- that is the fast
8152   // case here.
8153   if (NumV2Elements == 1 && Mask[0] >= 4)
8154     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8155                                                          Mask, Subtarget, DAG))
8156       return V;
8157
8158   if (Subtarget->hasSSE41()) {
8159     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8160                                                   Subtarget, DAG))
8161       return Blend;
8162
8163     // Use INSERTPS if we can complete the shuffle efficiently.
8164     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8165       return V;
8166
8167     if (!isSingleSHUFPSMask(Mask))
8168       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8169               DL, MVT::v4f32, V1, V2, Mask, DAG))
8170         return BlendPerm;
8171   }
8172
8173   // Use dedicated unpack instructions for masks that match their pattern.
8174   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8175     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8176   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8177     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8178   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8179     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8180   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8181     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8182
8183   // Otherwise fall back to a SHUFPS lowering strategy.
8184   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8185 }
8186
8187 /// \brief Lower 4-lane i32 vector shuffles.
8188 ///
8189 /// We try to handle these with integer-domain shuffles where we can, but for
8190 /// blends we use the floating point domain blend instructions.
8191 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8192                                        const X86Subtarget *Subtarget,
8193                                        SelectionDAG &DAG) {
8194   SDLoc DL(Op);
8195   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8196   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8197   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8198   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8199   ArrayRef<int> Mask = SVOp->getMask();
8200   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8201
8202   // Whenever we can lower this as a zext, that instruction is strictly faster
8203   // than any alternative. It also allows us to fold memory operands into the
8204   // shuffle in many cases.
8205   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8206                                                          Mask, Subtarget, DAG))
8207     return ZExt;
8208
8209   int NumV2Elements =
8210       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8211
8212   if (NumV2Elements == 0) {
8213     // Check for being able to broadcast a single element.
8214     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8215                                                           Mask, Subtarget, DAG))
8216       return Broadcast;
8217
8218     // Straight shuffle of a single input vector. For everything from SSE2
8219     // onward this has a single fast instruction with no scary immediates.
8220     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8221     // but we aren't actually going to use the UNPCK instruction because doing
8222     // so prevents folding a load into this instruction or making a copy.
8223     const int UnpackLoMask[] = {0, 0, 1, 1};
8224     const int UnpackHiMask[] = {2, 2, 3, 3};
8225     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8226       Mask = UnpackLoMask;
8227     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8228       Mask = UnpackHiMask;
8229
8230     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8231                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8232   }
8233
8234   // Try to use shift instructions.
8235   if (SDValue Shift =
8236           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8237     return Shift;
8238
8239   // There are special ways we can lower some single-element blends.
8240   if (NumV2Elements == 1)
8241     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8242                                                          Mask, Subtarget, DAG))
8243       return V;
8244
8245   // We have different paths for blend lowering, but they all must use the
8246   // *exact* same predicate.
8247   bool IsBlendSupported = Subtarget->hasSSE41();
8248   if (IsBlendSupported)
8249     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8250                                                   Subtarget, DAG))
8251       return Blend;
8252
8253   if (SDValue Masked =
8254           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8255     return Masked;
8256
8257   // Use dedicated unpack instructions for masks that match their pattern.
8258   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8259     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8260   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8261     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8262   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8263     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8264   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8265     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8266
8267   // Try to use byte rotation instructions.
8268   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8269   if (Subtarget->hasSSSE3())
8270     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8271             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8272       return Rotate;
8273
8274   // If we have direct support for blends, we should lower by decomposing into
8275   // a permute. That will be faster than the domain cross.
8276   if (IsBlendSupported)
8277     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8278                                                       Mask, DAG);
8279
8280   // Try to lower by permuting the inputs into an unpack instruction.
8281   if (SDValue Unpack =
8282           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8283     return Unpack;
8284
8285   // We implement this with SHUFPS because it can blend from two vectors.
8286   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8287   // up the inputs, bypassing domain shift penalties that we would encur if we
8288   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8289   // relevant.
8290   return DAG.getBitcast(
8291       MVT::v4i32,
8292       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8293                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8294 }
8295
8296 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8297 /// shuffle lowering, and the most complex part.
8298 ///
8299 /// The lowering strategy is to try to form pairs of input lanes which are
8300 /// targeted at the same half of the final vector, and then use a dword shuffle
8301 /// to place them onto the right half, and finally unpack the paired lanes into
8302 /// their final position.
8303 ///
8304 /// The exact breakdown of how to form these dword pairs and align them on the
8305 /// correct sides is really tricky. See the comments within the function for
8306 /// more of the details.
8307 ///
8308 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8309 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8310 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8311 /// vector, form the analogous 128-bit 8-element Mask.
8312 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8313     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8314     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8315   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8316   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8317
8318   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8319   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8320   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8321
8322   SmallVector<int, 4> LoInputs;
8323   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8324                [](int M) { return M >= 0; });
8325   std::sort(LoInputs.begin(), LoInputs.end());
8326   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8327   SmallVector<int, 4> HiInputs;
8328   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8329                [](int M) { return M >= 0; });
8330   std::sort(HiInputs.begin(), HiInputs.end());
8331   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8332   int NumLToL =
8333       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8334   int NumHToL = LoInputs.size() - NumLToL;
8335   int NumLToH =
8336       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8337   int NumHToH = HiInputs.size() - NumLToH;
8338   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8339   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8340   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8341   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8342
8343   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8344   // such inputs we can swap two of the dwords across the half mark and end up
8345   // with <=2 inputs to each half in each half. Once there, we can fall through
8346   // to the generic code below. For example:
8347   //
8348   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8349   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8350   //
8351   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8352   // and an existing 2-into-2 on the other half. In this case we may have to
8353   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8354   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8355   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8356   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8357   // half than the one we target for fixing) will be fixed when we re-enter this
8358   // path. We will also combine away any sequence of PSHUFD instructions that
8359   // result into a single instruction. Here is an example of the tricky case:
8360   //
8361   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8362   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8363   //
8364   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8365   //
8366   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8367   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8368   //
8369   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8370   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8371   //
8372   // The result is fine to be handled by the generic logic.
8373   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8374                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8375                           int AOffset, int BOffset) {
8376     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8377            "Must call this with A having 3 or 1 inputs from the A half.");
8378     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8379            "Must call this with B having 1 or 3 inputs from the B half.");
8380     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8381            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8382
8383     bool ThreeAInputs = AToAInputs.size() == 3;
8384
8385     // Compute the index of dword with only one word among the three inputs in
8386     // a half by taking the sum of the half with three inputs and subtracting
8387     // the sum of the actual three inputs. The difference is the remaining
8388     // slot.
8389     int ADWord, BDWord;
8390     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8391     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8392     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8393     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8394     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8395     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8396     int TripleNonInputIdx =
8397         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8398     TripleDWord = TripleNonInputIdx / 2;
8399
8400     // We use xor with one to compute the adjacent DWord to whichever one the
8401     // OneInput is in.
8402     OneInputDWord = (OneInput / 2) ^ 1;
8403
8404     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8405     // and BToA inputs. If there is also such a problem with the BToB and AToB
8406     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8407     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8408     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8409     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8410       // Compute how many inputs will be flipped by swapping these DWords. We
8411       // need
8412       // to balance this to ensure we don't form a 3-1 shuffle in the other
8413       // half.
8414       int NumFlippedAToBInputs =
8415           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8416           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8417       int NumFlippedBToBInputs =
8418           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8419           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8420       if ((NumFlippedAToBInputs == 1 &&
8421            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8422           (NumFlippedBToBInputs == 1 &&
8423            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8424         // We choose whether to fix the A half or B half based on whether that
8425         // half has zero flipped inputs. At zero, we may not be able to fix it
8426         // with that half. We also bias towards fixing the B half because that
8427         // will more commonly be the high half, and we have to bias one way.
8428         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8429                                                        ArrayRef<int> Inputs) {
8430           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8431           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8432                                          PinnedIdx ^ 1) != Inputs.end();
8433           // Determine whether the free index is in the flipped dword or the
8434           // unflipped dword based on where the pinned index is. We use this bit
8435           // in an xor to conditionally select the adjacent dword.
8436           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8437           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8438                                              FixFreeIdx) != Inputs.end();
8439           if (IsFixIdxInput == IsFixFreeIdxInput)
8440             FixFreeIdx += 1;
8441           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8442                                         FixFreeIdx) != Inputs.end();
8443           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8444                  "We need to be changing the number of flipped inputs!");
8445           int PSHUFHalfMask[] = {0, 1, 2, 3};
8446           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8447           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8448                           MVT::v8i16, V,
8449                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8450
8451           for (int &M : Mask)
8452             if (M != -1 && M == FixIdx)
8453               M = FixFreeIdx;
8454             else if (M != -1 && M == FixFreeIdx)
8455               M = FixIdx;
8456         };
8457         if (NumFlippedBToBInputs != 0) {
8458           int BPinnedIdx =
8459               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8460           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8461         } else {
8462           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8463           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8464           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8465         }
8466       }
8467     }
8468
8469     int PSHUFDMask[] = {0, 1, 2, 3};
8470     PSHUFDMask[ADWord] = BDWord;
8471     PSHUFDMask[BDWord] = ADWord;
8472     V = DAG.getBitcast(
8473         VT,
8474         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8475                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8476
8477     // Adjust the mask to match the new locations of A and B.
8478     for (int &M : Mask)
8479       if (M != -1 && M/2 == ADWord)
8480         M = 2 * BDWord + M % 2;
8481       else if (M != -1 && M/2 == BDWord)
8482         M = 2 * ADWord + M % 2;
8483
8484     // Recurse back into this routine to re-compute state now that this isn't
8485     // a 3 and 1 problem.
8486     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8487                                                      DAG);
8488   };
8489   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8490     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8491   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8492     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8493
8494   // At this point there are at most two inputs to the low and high halves from
8495   // each half. That means the inputs can always be grouped into dwords and
8496   // those dwords can then be moved to the correct half with a dword shuffle.
8497   // We use at most one low and one high word shuffle to collect these paired
8498   // inputs into dwords, and finally a dword shuffle to place them.
8499   int PSHUFLMask[4] = {-1, -1, -1, -1};
8500   int PSHUFHMask[4] = {-1, -1, -1, -1};
8501   int PSHUFDMask[4] = {-1, -1, -1, -1};
8502
8503   // First fix the masks for all the inputs that are staying in their
8504   // original halves. This will then dictate the targets of the cross-half
8505   // shuffles.
8506   auto fixInPlaceInputs =
8507       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8508                     MutableArrayRef<int> SourceHalfMask,
8509                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8510     if (InPlaceInputs.empty())
8511       return;
8512     if (InPlaceInputs.size() == 1) {
8513       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8514           InPlaceInputs[0] - HalfOffset;
8515       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8516       return;
8517     }
8518     if (IncomingInputs.empty()) {
8519       // Just fix all of the in place inputs.
8520       for (int Input : InPlaceInputs) {
8521         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8522         PSHUFDMask[Input / 2] = Input / 2;
8523       }
8524       return;
8525     }
8526
8527     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8528     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8529         InPlaceInputs[0] - HalfOffset;
8530     // Put the second input next to the first so that they are packed into
8531     // a dword. We find the adjacent index by toggling the low bit.
8532     int AdjIndex = InPlaceInputs[0] ^ 1;
8533     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8534     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8535     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8536   };
8537   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8538   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8539
8540   // Now gather the cross-half inputs and place them into a free dword of
8541   // their target half.
8542   // FIXME: This operation could almost certainly be simplified dramatically to
8543   // look more like the 3-1 fixing operation.
8544   auto moveInputsToRightHalf = [&PSHUFDMask](
8545       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8546       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8547       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8548       int DestOffset) {
8549     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8550       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8551     };
8552     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8553                                                int Word) {
8554       int LowWord = Word & ~1;
8555       int HighWord = Word | 1;
8556       return isWordClobbered(SourceHalfMask, LowWord) ||
8557              isWordClobbered(SourceHalfMask, HighWord);
8558     };
8559
8560     if (IncomingInputs.empty())
8561       return;
8562
8563     if (ExistingInputs.empty()) {
8564       // Map any dwords with inputs from them into the right half.
8565       for (int Input : IncomingInputs) {
8566         // If the source half mask maps over the inputs, turn those into
8567         // swaps and use the swapped lane.
8568         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8569           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8570             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8571                 Input - SourceOffset;
8572             // We have to swap the uses in our half mask in one sweep.
8573             for (int &M : HalfMask)
8574               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8575                 M = Input;
8576               else if (M == Input)
8577                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8578           } else {
8579             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8580                        Input - SourceOffset &&
8581                    "Previous placement doesn't match!");
8582           }
8583           // Note that this correctly re-maps both when we do a swap and when
8584           // we observe the other side of the swap above. We rely on that to
8585           // avoid swapping the members of the input list directly.
8586           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8587         }
8588
8589         // Map the input's dword into the correct half.
8590         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8591           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8592         else
8593           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8594                      Input / 2 &&
8595                  "Previous placement doesn't match!");
8596       }
8597
8598       // And just directly shift any other-half mask elements to be same-half
8599       // as we will have mirrored the dword containing the element into the
8600       // same position within that half.
8601       for (int &M : HalfMask)
8602         if (M >= SourceOffset && M < SourceOffset + 4) {
8603           M = M - SourceOffset + DestOffset;
8604           assert(M >= 0 && "This should never wrap below zero!");
8605         }
8606       return;
8607     }
8608
8609     // Ensure we have the input in a viable dword of its current half. This
8610     // is particularly tricky because the original position may be clobbered
8611     // by inputs being moved and *staying* in that half.
8612     if (IncomingInputs.size() == 1) {
8613       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8614         int InputFixed = std::find(std::begin(SourceHalfMask),
8615                                    std::end(SourceHalfMask), -1) -
8616                          std::begin(SourceHalfMask) + SourceOffset;
8617         SourceHalfMask[InputFixed - SourceOffset] =
8618             IncomingInputs[0] - SourceOffset;
8619         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8620                      InputFixed);
8621         IncomingInputs[0] = InputFixed;
8622       }
8623     } else if (IncomingInputs.size() == 2) {
8624       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8625           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8626         // We have two non-adjacent or clobbered inputs we need to extract from
8627         // the source half. To do this, we need to map them into some adjacent
8628         // dword slot in the source mask.
8629         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8630                               IncomingInputs[1] - SourceOffset};
8631
8632         // If there is a free slot in the source half mask adjacent to one of
8633         // the inputs, place the other input in it. We use (Index XOR 1) to
8634         // compute an adjacent index.
8635         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8636             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8637           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8638           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8639           InputsFixed[1] = InputsFixed[0] ^ 1;
8640         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8641                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8642           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8643           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8644           InputsFixed[0] = InputsFixed[1] ^ 1;
8645         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8646                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8647           // The two inputs are in the same DWord but it is clobbered and the
8648           // adjacent DWord isn't used at all. Move both inputs to the free
8649           // slot.
8650           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8651           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8652           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8653           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8654         } else {
8655           // The only way we hit this point is if there is no clobbering
8656           // (because there are no off-half inputs to this half) and there is no
8657           // free slot adjacent to one of the inputs. In this case, we have to
8658           // swap an input with a non-input.
8659           for (int i = 0; i < 4; ++i)
8660             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8661                    "We can't handle any clobbers here!");
8662           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8663                  "Cannot have adjacent inputs here!");
8664
8665           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8666           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8667
8668           // We also have to update the final source mask in this case because
8669           // it may need to undo the above swap.
8670           for (int &M : FinalSourceHalfMask)
8671             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8672               M = InputsFixed[1] + SourceOffset;
8673             else if (M == InputsFixed[1] + SourceOffset)
8674               M = (InputsFixed[0] ^ 1) + SourceOffset;
8675
8676           InputsFixed[1] = InputsFixed[0] ^ 1;
8677         }
8678
8679         // Point everything at the fixed inputs.
8680         for (int &M : HalfMask)
8681           if (M == IncomingInputs[0])
8682             M = InputsFixed[0] + SourceOffset;
8683           else if (M == IncomingInputs[1])
8684             M = InputsFixed[1] + SourceOffset;
8685
8686         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8687         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8688       }
8689     } else {
8690       llvm_unreachable("Unhandled input size!");
8691     }
8692
8693     // Now hoist the DWord down to the right half.
8694     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8695     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8696     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8697     for (int &M : HalfMask)
8698       for (int Input : IncomingInputs)
8699         if (M == Input)
8700           M = FreeDWord * 2 + Input % 2;
8701   };
8702   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8703                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8704   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8705                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8706
8707   // Now enact all the shuffles we've computed to move the inputs into their
8708   // target half.
8709   if (!isNoopShuffleMask(PSHUFLMask))
8710     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8711                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8712   if (!isNoopShuffleMask(PSHUFHMask))
8713     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8714                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8715   if (!isNoopShuffleMask(PSHUFDMask))
8716     V = DAG.getBitcast(
8717         VT,
8718         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8719                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8720
8721   // At this point, each half should contain all its inputs, and we can then
8722   // just shuffle them into their final position.
8723   assert(std::count_if(LoMask.begin(), LoMask.end(),
8724                        [](int M) { return M >= 4; }) == 0 &&
8725          "Failed to lift all the high half inputs to the low mask!");
8726   assert(std::count_if(HiMask.begin(), HiMask.end(),
8727                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8728          "Failed to lift all the low half inputs to the high mask!");
8729
8730   // Do a half shuffle for the low mask.
8731   if (!isNoopShuffleMask(LoMask))
8732     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8733                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8734
8735   // Do a half shuffle with the high mask after shifting its values down.
8736   for (int &M : HiMask)
8737     if (M >= 0)
8738       M -= 4;
8739   if (!isNoopShuffleMask(HiMask))
8740     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8741                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8742
8743   return V;
8744 }
8745
8746 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8747 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8748                                           SDValue V2, ArrayRef<int> Mask,
8749                                           SelectionDAG &DAG, bool &V1InUse,
8750                                           bool &V2InUse) {
8751   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8752   SDValue V1Mask[16];
8753   SDValue V2Mask[16];
8754   V1InUse = false;
8755   V2InUse = false;
8756
8757   int Size = Mask.size();
8758   int Scale = 16 / Size;
8759   for (int i = 0; i < 16; ++i) {
8760     if (Mask[i / Scale] == -1) {
8761       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8762     } else {
8763       const int ZeroMask = 0x80;
8764       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8765                                           : ZeroMask;
8766       int V2Idx = Mask[i / Scale] < Size
8767                       ? ZeroMask
8768                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8769       if (Zeroable[i / Scale])
8770         V1Idx = V2Idx = ZeroMask;
8771       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8772       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8773       V1InUse |= (ZeroMask != V1Idx);
8774       V2InUse |= (ZeroMask != V2Idx);
8775     }
8776   }
8777
8778   if (V1InUse)
8779     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8780                      DAG.getBitcast(MVT::v16i8, V1),
8781                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8782   if (V2InUse)
8783     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8784                      DAG.getBitcast(MVT::v16i8, V2),
8785                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8786
8787   // If we need shuffled inputs from both, blend the two.
8788   SDValue V;
8789   if (V1InUse && V2InUse)
8790     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8791   else
8792     V = V1InUse ? V1 : V2;
8793
8794   // Cast the result back to the correct type.
8795   return DAG.getBitcast(VT, V);
8796 }
8797
8798 /// \brief Generic lowering of 8-lane i16 shuffles.
8799 ///
8800 /// This handles both single-input shuffles and combined shuffle/blends with
8801 /// two inputs. The single input shuffles are immediately delegated to
8802 /// a dedicated lowering routine.
8803 ///
8804 /// The blends are lowered in one of three fundamental ways. If there are few
8805 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8806 /// of the input is significantly cheaper when lowered as an interleaving of
8807 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8808 /// halves of the inputs separately (making them have relatively few inputs)
8809 /// and then concatenate them.
8810 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8811                                        const X86Subtarget *Subtarget,
8812                                        SelectionDAG &DAG) {
8813   SDLoc DL(Op);
8814   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8815   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8816   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8817   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8818   ArrayRef<int> OrigMask = SVOp->getMask();
8819   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8820                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8821   MutableArrayRef<int> Mask(MaskStorage);
8822
8823   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8824
8825   // Whenever we can lower this as a zext, that instruction is strictly faster
8826   // than any alternative.
8827   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8828           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8829     return ZExt;
8830
8831   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8832   (void)isV1;
8833   auto isV2 = [](int M) { return M >= 8; };
8834
8835   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8836
8837   if (NumV2Inputs == 0) {
8838     // Check for being able to broadcast a single element.
8839     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8840                                                           Mask, Subtarget, DAG))
8841       return Broadcast;
8842
8843     // Try to use shift instructions.
8844     if (SDValue Shift =
8845             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8846       return Shift;
8847
8848     // Use dedicated unpack instructions for masks that match their pattern.
8849     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8850       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8851     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8852       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8853
8854     // Try to use byte rotation instructions.
8855     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8856                                                         Mask, Subtarget, DAG))
8857       return Rotate;
8858
8859     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8860                                                      Subtarget, DAG);
8861   }
8862
8863   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8864          "All single-input shuffles should be canonicalized to be V1-input "
8865          "shuffles.");
8866
8867   // Try to use shift instructions.
8868   if (SDValue Shift =
8869           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8870     return Shift;
8871
8872   // See if we can use SSE4A Extraction / Insertion.
8873   if (Subtarget->hasSSE4A())
8874     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8875       return V;
8876
8877   // There are special ways we can lower some single-element blends.
8878   if (NumV2Inputs == 1)
8879     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8880                                                          Mask, Subtarget, DAG))
8881       return V;
8882
8883   // We have different paths for blend lowering, but they all must use the
8884   // *exact* same predicate.
8885   bool IsBlendSupported = Subtarget->hasSSE41();
8886   if (IsBlendSupported)
8887     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8888                                                   Subtarget, DAG))
8889       return Blend;
8890
8891   if (SDValue Masked =
8892           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8893     return Masked;
8894
8895   // Use dedicated unpack instructions for masks that match their pattern.
8896   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8897     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8898   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8899     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8900
8901   // Try to use byte rotation instructions.
8902   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8903           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8904     return Rotate;
8905
8906   if (SDValue BitBlend =
8907           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8908     return BitBlend;
8909
8910   if (SDValue Unpack =
8911           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8912     return Unpack;
8913
8914   // If we can't directly blend but can use PSHUFB, that will be better as it
8915   // can both shuffle and set up the inefficient blend.
8916   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8917     bool V1InUse, V2InUse;
8918     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8919                                       V1InUse, V2InUse);
8920   }
8921
8922   // We can always bit-blend if we have to so the fallback strategy is to
8923   // decompose into single-input permutes and blends.
8924   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8925                                                       Mask, DAG);
8926 }
8927
8928 /// \brief Check whether a compaction lowering can be done by dropping even
8929 /// elements and compute how many times even elements must be dropped.
8930 ///
8931 /// This handles shuffles which take every Nth element where N is a power of
8932 /// two. Example shuffle masks:
8933 ///
8934 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8935 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8936 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8937 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8938 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8939 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8940 ///
8941 /// Any of these lanes can of course be undef.
8942 ///
8943 /// This routine only supports N <= 3.
8944 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8945 /// for larger N.
8946 ///
8947 /// \returns N above, or the number of times even elements must be dropped if
8948 /// there is such a number. Otherwise returns zero.
8949 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8950   // Figure out whether we're looping over two inputs or just one.
8951   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8952
8953   // The modulus for the shuffle vector entries is based on whether this is
8954   // a single input or not.
8955   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8956   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8957          "We should only be called with masks with a power-of-2 size!");
8958
8959   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8960
8961   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8962   // and 2^3 simultaneously. This is because we may have ambiguity with
8963   // partially undef inputs.
8964   bool ViableForN[3] = {true, true, true};
8965
8966   for (int i = 0, e = Mask.size(); i < e; ++i) {
8967     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8968     // want.
8969     if (Mask[i] == -1)
8970       continue;
8971
8972     bool IsAnyViable = false;
8973     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8974       if (ViableForN[j]) {
8975         uint64_t N = j + 1;
8976
8977         // The shuffle mask must be equal to (i * 2^N) % M.
8978         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8979           IsAnyViable = true;
8980         else
8981           ViableForN[j] = false;
8982       }
8983     // Early exit if we exhaust the possible powers of two.
8984     if (!IsAnyViable)
8985       break;
8986   }
8987
8988   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8989     if (ViableForN[j])
8990       return j + 1;
8991
8992   // Return 0 as there is no viable power of two.
8993   return 0;
8994 }
8995
8996 /// \brief Generic lowering of v16i8 shuffles.
8997 ///
8998 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8999 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9000 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9001 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9002 /// back together.
9003 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9004                                        const X86Subtarget *Subtarget,
9005                                        SelectionDAG &DAG) {
9006   SDLoc DL(Op);
9007   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9008   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9009   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9010   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9011   ArrayRef<int> Mask = SVOp->getMask();
9012   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9013
9014   // Try to use shift instructions.
9015   if (SDValue Shift =
9016           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9017     return Shift;
9018
9019   // Try to use byte rotation instructions.
9020   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9021           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9022     return Rotate;
9023
9024   // Try to use a zext lowering.
9025   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9026           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9027     return ZExt;
9028
9029   // See if we can use SSE4A Extraction / Insertion.
9030   if (Subtarget->hasSSE4A())
9031     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9032       return V;
9033
9034   int NumV2Elements =
9035       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9036
9037   // For single-input shuffles, there are some nicer lowering tricks we can use.
9038   if (NumV2Elements == 0) {
9039     // Check for being able to broadcast a single element.
9040     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9041                                                           Mask, Subtarget, DAG))
9042       return Broadcast;
9043
9044     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9045     // Notably, this handles splat and partial-splat shuffles more efficiently.
9046     // However, it only makes sense if the pre-duplication shuffle simplifies
9047     // things significantly. Currently, this means we need to be able to
9048     // express the pre-duplication shuffle as an i16 shuffle.
9049     //
9050     // FIXME: We should check for other patterns which can be widened into an
9051     // i16 shuffle as well.
9052     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9053       for (int i = 0; i < 16; i += 2)
9054         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9055           return false;
9056
9057       return true;
9058     };
9059     auto tryToWidenViaDuplication = [&]() -> SDValue {
9060       if (!canWidenViaDuplication(Mask))
9061         return SDValue();
9062       SmallVector<int, 4> LoInputs;
9063       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9064                    [](int M) { return M >= 0 && M < 8; });
9065       std::sort(LoInputs.begin(), LoInputs.end());
9066       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9067                      LoInputs.end());
9068       SmallVector<int, 4> HiInputs;
9069       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9070                    [](int M) { return M >= 8; });
9071       std::sort(HiInputs.begin(), HiInputs.end());
9072       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9073                      HiInputs.end());
9074
9075       bool TargetLo = LoInputs.size() >= HiInputs.size();
9076       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9077       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9078
9079       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9080       SmallDenseMap<int, int, 8> LaneMap;
9081       for (int I : InPlaceInputs) {
9082         PreDupI16Shuffle[I/2] = I/2;
9083         LaneMap[I] = I;
9084       }
9085       int j = TargetLo ? 0 : 4, je = j + 4;
9086       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9087         // Check if j is already a shuffle of this input. This happens when
9088         // there are two adjacent bytes after we move the low one.
9089         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9090           // If we haven't yet mapped the input, search for a slot into which
9091           // we can map it.
9092           while (j < je && PreDupI16Shuffle[j] != -1)
9093             ++j;
9094
9095           if (j == je)
9096             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9097             return SDValue();
9098
9099           // Map this input with the i16 shuffle.
9100           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9101         }
9102
9103         // Update the lane map based on the mapping we ended up with.
9104         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9105       }
9106       V1 = DAG.getBitcast(
9107           MVT::v16i8,
9108           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9109                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9110
9111       // Unpack the bytes to form the i16s that will be shuffled into place.
9112       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9113                        MVT::v16i8, V1, V1);
9114
9115       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9116       for (int i = 0; i < 16; ++i)
9117         if (Mask[i] != -1) {
9118           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9119           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9120           if (PostDupI16Shuffle[i / 2] == -1)
9121             PostDupI16Shuffle[i / 2] = MappedMask;
9122           else
9123             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9124                    "Conflicting entrties in the original shuffle!");
9125         }
9126       return DAG.getBitcast(
9127           MVT::v16i8,
9128           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9129                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9130     };
9131     if (SDValue V = tryToWidenViaDuplication())
9132       return V;
9133   }
9134
9135   if (SDValue Masked =
9136           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9137     return Masked;
9138
9139   // Use dedicated unpack instructions for masks that match their pattern.
9140   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9141                                          0, 16, 1, 17, 2, 18, 3, 19,
9142                                          // High half.
9143                                          4, 20, 5, 21, 6, 22, 7, 23}))
9144     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9145   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9146                                          8, 24, 9, 25, 10, 26, 11, 27,
9147                                          // High half.
9148                                          12, 28, 13, 29, 14, 30, 15, 31}))
9149     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9150
9151   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9152   // with PSHUFB. It is important to do this before we attempt to generate any
9153   // blends but after all of the single-input lowerings. If the single input
9154   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9155   // want to preserve that and we can DAG combine any longer sequences into
9156   // a PSHUFB in the end. But once we start blending from multiple inputs,
9157   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9158   // and there are *very* few patterns that would actually be faster than the
9159   // PSHUFB approach because of its ability to zero lanes.
9160   //
9161   // FIXME: The only exceptions to the above are blends which are exact
9162   // interleavings with direct instructions supporting them. We currently don't
9163   // handle those well here.
9164   if (Subtarget->hasSSSE3()) {
9165     bool V1InUse = false;
9166     bool V2InUse = false;
9167
9168     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9169                                                 DAG, V1InUse, V2InUse);
9170
9171     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9172     // do so. This avoids using them to handle blends-with-zero which is
9173     // important as a single pshufb is significantly faster for that.
9174     if (V1InUse && V2InUse) {
9175       if (Subtarget->hasSSE41())
9176         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9177                                                       Mask, Subtarget, DAG))
9178           return Blend;
9179
9180       // We can use an unpack to do the blending rather than an or in some
9181       // cases. Even though the or may be (very minorly) more efficient, we
9182       // preference this lowering because there are common cases where part of
9183       // the complexity of the shuffles goes away when we do the final blend as
9184       // an unpack.
9185       // FIXME: It might be worth trying to detect if the unpack-feeding
9186       // shuffles will both be pshufb, in which case we shouldn't bother with
9187       // this.
9188       if (SDValue Unpack =
9189               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9190         return Unpack;
9191     }
9192
9193     return PSHUFB;
9194   }
9195
9196   // There are special ways we can lower some single-element blends.
9197   if (NumV2Elements == 1)
9198     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9199                                                          Mask, Subtarget, DAG))
9200       return V;
9201
9202   if (SDValue BitBlend =
9203           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9204     return BitBlend;
9205
9206   // Check whether a compaction lowering can be done. This handles shuffles
9207   // which take every Nth element for some even N. See the helper function for
9208   // details.
9209   //
9210   // We special case these as they can be particularly efficiently handled with
9211   // the PACKUSB instruction on x86 and they show up in common patterns of
9212   // rearranging bytes to truncate wide elements.
9213   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9214     // NumEvenDrops is the power of two stride of the elements. Another way of
9215     // thinking about it is that we need to drop the even elements this many
9216     // times to get the original input.
9217     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9218
9219     // First we need to zero all the dropped bytes.
9220     assert(NumEvenDrops <= 3 &&
9221            "No support for dropping even elements more than 3 times.");
9222     // We use the mask type to pick which bytes are preserved based on how many
9223     // elements are dropped.
9224     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9225     SDValue ByteClearMask = DAG.getBitcast(
9226         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9227     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9228     if (!IsSingleInput)
9229       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9230
9231     // Now pack things back together.
9232     V1 = DAG.getBitcast(MVT::v8i16, V1);
9233     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9234     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9235     for (int i = 1; i < NumEvenDrops; ++i) {
9236       Result = DAG.getBitcast(MVT::v8i16, Result);
9237       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9238     }
9239
9240     return Result;
9241   }
9242
9243   // Handle multi-input cases by blending single-input shuffles.
9244   if (NumV2Elements > 0)
9245     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9246                                                       Mask, DAG);
9247
9248   // The fallback path for single-input shuffles widens this into two v8i16
9249   // vectors with unpacks, shuffles those, and then pulls them back together
9250   // with a pack.
9251   SDValue V = V1;
9252
9253   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9254   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9255   for (int i = 0; i < 16; ++i)
9256     if (Mask[i] >= 0)
9257       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9258
9259   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9260
9261   SDValue VLoHalf, VHiHalf;
9262   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9263   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9264   // i16s.
9265   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9266                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9267       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9268                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9269     // Use a mask to drop the high bytes.
9270     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9271     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9272                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9273
9274     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9275     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9276
9277     // Squash the masks to point directly into VLoHalf.
9278     for (int &M : LoBlendMask)
9279       if (M >= 0)
9280         M /= 2;
9281     for (int &M : HiBlendMask)
9282       if (M >= 0)
9283         M /= 2;
9284   } else {
9285     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9286     // VHiHalf so that we can blend them as i16s.
9287     VLoHalf = DAG.getBitcast(
9288         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9289     VHiHalf = DAG.getBitcast(
9290         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9291   }
9292
9293   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9294   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9295
9296   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9297 }
9298
9299 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9300 ///
9301 /// This routine breaks down the specific type of 128-bit shuffle and
9302 /// dispatches to the lowering routines accordingly.
9303 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9304                                         MVT VT, const X86Subtarget *Subtarget,
9305                                         SelectionDAG &DAG) {
9306   switch (VT.SimpleTy) {
9307   case MVT::v2i64:
9308     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9309   case MVT::v2f64:
9310     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9311   case MVT::v4i32:
9312     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9313   case MVT::v4f32:
9314     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9315   case MVT::v8i16:
9316     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9317   case MVT::v16i8:
9318     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9319
9320   default:
9321     llvm_unreachable("Unimplemented!");
9322   }
9323 }
9324
9325 /// \brief Helper function to test whether a shuffle mask could be
9326 /// simplified by widening the elements being shuffled.
9327 ///
9328 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9329 /// leaves it in an unspecified state.
9330 ///
9331 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9332 /// shuffle masks. The latter have the special property of a '-2' representing
9333 /// a zero-ed lane of a vector.
9334 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9335                                     SmallVectorImpl<int> &WidenedMask) {
9336   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9337     // If both elements are undef, its trivial.
9338     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9339       WidenedMask.push_back(SM_SentinelUndef);
9340       continue;
9341     }
9342
9343     // Check for an undef mask and a mask value properly aligned to fit with
9344     // a pair of values. If we find such a case, use the non-undef mask's value.
9345     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9346       WidenedMask.push_back(Mask[i + 1] / 2);
9347       continue;
9348     }
9349     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9350       WidenedMask.push_back(Mask[i] / 2);
9351       continue;
9352     }
9353
9354     // When zeroing, we need to spread the zeroing across both lanes to widen.
9355     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9356       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9357           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9358         WidenedMask.push_back(SM_SentinelZero);
9359         continue;
9360       }
9361       return false;
9362     }
9363
9364     // Finally check if the two mask values are adjacent and aligned with
9365     // a pair.
9366     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9367       WidenedMask.push_back(Mask[i] / 2);
9368       continue;
9369     }
9370
9371     // Otherwise we can't safely widen the elements used in this shuffle.
9372     return false;
9373   }
9374   assert(WidenedMask.size() == Mask.size() / 2 &&
9375          "Incorrect size of mask after widening the elements!");
9376
9377   return true;
9378 }
9379
9380 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9381 ///
9382 /// This routine just extracts two subvectors, shuffles them independently, and
9383 /// then concatenates them back together. This should work effectively with all
9384 /// AVX vector shuffle types.
9385 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9386                                           SDValue V2, ArrayRef<int> Mask,
9387                                           SelectionDAG &DAG) {
9388   assert(VT.getSizeInBits() >= 256 &&
9389          "Only for 256-bit or wider vector shuffles!");
9390   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9391   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9392
9393   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9394   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9395
9396   int NumElements = VT.getVectorNumElements();
9397   int SplitNumElements = NumElements / 2;
9398   MVT ScalarVT = VT.getScalarType();
9399   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9400
9401   // Rather than splitting build-vectors, just build two narrower build
9402   // vectors. This helps shuffling with splats and zeros.
9403   auto SplitVector = [&](SDValue V) {
9404     while (V.getOpcode() == ISD::BITCAST)
9405       V = V->getOperand(0);
9406
9407     MVT OrigVT = V.getSimpleValueType();
9408     int OrigNumElements = OrigVT.getVectorNumElements();
9409     int OrigSplitNumElements = OrigNumElements / 2;
9410     MVT OrigScalarVT = OrigVT.getScalarType();
9411     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9412
9413     SDValue LoV, HiV;
9414
9415     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9416     if (!BV) {
9417       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9418                         DAG.getIntPtrConstant(0, DL));
9419       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9420                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9421     } else {
9422
9423       SmallVector<SDValue, 16> LoOps, HiOps;
9424       for (int i = 0; i < OrigSplitNumElements; ++i) {
9425         LoOps.push_back(BV->getOperand(i));
9426         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9427       }
9428       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9429       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9430     }
9431     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9432                           DAG.getBitcast(SplitVT, HiV));
9433   };
9434
9435   SDValue LoV1, HiV1, LoV2, HiV2;
9436   std::tie(LoV1, HiV1) = SplitVector(V1);
9437   std::tie(LoV2, HiV2) = SplitVector(V2);
9438
9439   // Now create two 4-way blends of these half-width vectors.
9440   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9441     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9442     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9443     for (int i = 0; i < SplitNumElements; ++i) {
9444       int M = HalfMask[i];
9445       if (M >= NumElements) {
9446         if (M >= NumElements + SplitNumElements)
9447           UseHiV2 = true;
9448         else
9449           UseLoV2 = true;
9450         V2BlendMask.push_back(M - NumElements);
9451         V1BlendMask.push_back(-1);
9452         BlendMask.push_back(SplitNumElements + i);
9453       } else if (M >= 0) {
9454         if (M >= SplitNumElements)
9455           UseHiV1 = true;
9456         else
9457           UseLoV1 = true;
9458         V2BlendMask.push_back(-1);
9459         V1BlendMask.push_back(M);
9460         BlendMask.push_back(i);
9461       } else {
9462         V2BlendMask.push_back(-1);
9463         V1BlendMask.push_back(-1);
9464         BlendMask.push_back(-1);
9465       }
9466     }
9467
9468     // Because the lowering happens after all combining takes place, we need to
9469     // manually combine these blend masks as much as possible so that we create
9470     // a minimal number of high-level vector shuffle nodes.
9471
9472     // First try just blending the halves of V1 or V2.
9473     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9474       return DAG.getUNDEF(SplitVT);
9475     if (!UseLoV2 && !UseHiV2)
9476       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9477     if (!UseLoV1 && !UseHiV1)
9478       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9479
9480     SDValue V1Blend, V2Blend;
9481     if (UseLoV1 && UseHiV1) {
9482       V1Blend =
9483         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9484     } else {
9485       // We only use half of V1 so map the usage down into the final blend mask.
9486       V1Blend = UseLoV1 ? LoV1 : HiV1;
9487       for (int i = 0; i < SplitNumElements; ++i)
9488         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9489           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9490     }
9491     if (UseLoV2 && UseHiV2) {
9492       V2Blend =
9493         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9494     } else {
9495       // We only use half of V2 so map the usage down into the final blend mask.
9496       V2Blend = UseLoV2 ? LoV2 : HiV2;
9497       for (int i = 0; i < SplitNumElements; ++i)
9498         if (BlendMask[i] >= SplitNumElements)
9499           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9500     }
9501     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9502   };
9503   SDValue Lo = HalfBlend(LoMask);
9504   SDValue Hi = HalfBlend(HiMask);
9505   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9506 }
9507
9508 /// \brief Either split a vector in halves or decompose the shuffles and the
9509 /// blend.
9510 ///
9511 /// This is provided as a good fallback for many lowerings of non-single-input
9512 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9513 /// between splitting the shuffle into 128-bit components and stitching those
9514 /// back together vs. extracting the single-input shuffles and blending those
9515 /// results.
9516 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9517                                                 SDValue V2, ArrayRef<int> Mask,
9518                                                 SelectionDAG &DAG) {
9519   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9520                                             "lower single-input shuffles as it "
9521                                             "could then recurse on itself.");
9522   int Size = Mask.size();
9523
9524   // If this can be modeled as a broadcast of two elements followed by a blend,
9525   // prefer that lowering. This is especially important because broadcasts can
9526   // often fold with memory operands.
9527   auto DoBothBroadcast = [&] {
9528     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9529     for (int M : Mask)
9530       if (M >= Size) {
9531         if (V2BroadcastIdx == -1)
9532           V2BroadcastIdx = M - Size;
9533         else if (M - Size != V2BroadcastIdx)
9534           return false;
9535       } else if (M >= 0) {
9536         if (V1BroadcastIdx == -1)
9537           V1BroadcastIdx = M;
9538         else if (M != V1BroadcastIdx)
9539           return false;
9540       }
9541     return true;
9542   };
9543   if (DoBothBroadcast())
9544     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9545                                                       DAG);
9546
9547   // If the inputs all stem from a single 128-bit lane of each input, then we
9548   // split them rather than blending because the split will decompose to
9549   // unusually few instructions.
9550   int LaneCount = VT.getSizeInBits() / 128;
9551   int LaneSize = Size / LaneCount;
9552   SmallBitVector LaneInputs[2];
9553   LaneInputs[0].resize(LaneCount, false);
9554   LaneInputs[1].resize(LaneCount, false);
9555   for (int i = 0; i < Size; ++i)
9556     if (Mask[i] >= 0)
9557       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9558   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9559     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9560
9561   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9562   // that the decomposed single-input shuffles don't end up here.
9563   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9564 }
9565
9566 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9567 /// a permutation and blend of those lanes.
9568 ///
9569 /// This essentially blends the out-of-lane inputs to each lane into the lane
9570 /// from a permuted copy of the vector. This lowering strategy results in four
9571 /// instructions in the worst case for a single-input cross lane shuffle which
9572 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9573 /// of. Special cases for each particular shuffle pattern should be handled
9574 /// prior to trying this lowering.
9575 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9576                                                        SDValue V1, SDValue V2,
9577                                                        ArrayRef<int> Mask,
9578                                                        SelectionDAG &DAG) {
9579   // FIXME: This should probably be generalized for 512-bit vectors as well.
9580   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9581   int LaneSize = Mask.size() / 2;
9582
9583   // If there are only inputs from one 128-bit lane, splitting will in fact be
9584   // less expensive. The flags track whether the given lane contains an element
9585   // that crosses to another lane.
9586   bool LaneCrossing[2] = {false, false};
9587   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9588     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9589       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9590   if (!LaneCrossing[0] || !LaneCrossing[1])
9591     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9592
9593   if (isSingleInputShuffleMask(Mask)) {
9594     SmallVector<int, 32> FlippedBlendMask;
9595     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9596       FlippedBlendMask.push_back(
9597           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9598                                   ? Mask[i]
9599                                   : Mask[i] % LaneSize +
9600                                         (i / LaneSize) * LaneSize + Size));
9601
9602     // Flip the vector, and blend the results which should now be in-lane. The
9603     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9604     // 5 for the high source. The value 3 selects the high half of source 2 and
9605     // the value 2 selects the low half of source 2. We only use source 2 to
9606     // allow folding it into a memory operand.
9607     unsigned PERMMask = 3 | 2 << 4;
9608     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9609                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9610     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9611   }
9612
9613   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9614   // will be handled by the above logic and a blend of the results, much like
9615   // other patterns in AVX.
9616   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9617 }
9618
9619 /// \brief Handle lowering 2-lane 128-bit shuffles.
9620 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9621                                         SDValue V2, ArrayRef<int> Mask,
9622                                         const X86Subtarget *Subtarget,
9623                                         SelectionDAG &DAG) {
9624   // TODO: If minimizing size and one of the inputs is a zero vector and the
9625   // the zero vector has only one use, we could use a VPERM2X128 to save the
9626   // instruction bytes needed to explicitly generate the zero vector.
9627
9628   // Blends are faster and handle all the non-lane-crossing cases.
9629   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9630                                                 Subtarget, DAG))
9631     return Blend;
9632
9633   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9634   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9635
9636   // If either input operand is a zero vector, use VPERM2X128 because its mask
9637   // allows us to replace the zero input with an implicit zero.
9638   if (!IsV1Zero && !IsV2Zero) {
9639     // Check for patterns which can be matched with a single insert of a 128-bit
9640     // subvector.
9641     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9642     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9643       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9644                                    VT.getVectorNumElements() / 2);
9645       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9646                                 DAG.getIntPtrConstant(0, DL));
9647       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9648                                 OnlyUsesV1 ? V1 : V2,
9649                                 DAG.getIntPtrConstant(0, DL));
9650       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9651     }
9652   }
9653
9654   // Otherwise form a 128-bit permutation. After accounting for undefs,
9655   // convert the 64-bit shuffle mask selection values into 128-bit
9656   // selection bits by dividing the indexes by 2 and shifting into positions
9657   // defined by a vperm2*128 instruction's immediate control byte.
9658
9659   // The immediate permute control byte looks like this:
9660   //    [1:0] - select 128 bits from sources for low half of destination
9661   //    [2]   - ignore
9662   //    [3]   - zero low half of destination
9663   //    [5:4] - select 128 bits from sources for high half of destination
9664   //    [6]   - ignore
9665   //    [7]   - zero high half of destination
9666
9667   int MaskLO = Mask[0];
9668   if (MaskLO == SM_SentinelUndef)
9669     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9670
9671   int MaskHI = Mask[2];
9672   if (MaskHI == SM_SentinelUndef)
9673     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9674
9675   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9676
9677   // If either input is a zero vector, replace it with an undef input.
9678   // Shuffle mask values <  4 are selecting elements of V1.
9679   // Shuffle mask values >= 4 are selecting elements of V2.
9680   // Adjust each half of the permute mask by clearing the half that was
9681   // selecting the zero vector and setting the zero mask bit.
9682   if (IsV1Zero) {
9683     V1 = DAG.getUNDEF(VT);
9684     if (MaskLO < 4)
9685       PermMask = (PermMask & 0xf0) | 0x08;
9686     if (MaskHI < 4)
9687       PermMask = (PermMask & 0x0f) | 0x80;
9688   }
9689   if (IsV2Zero) {
9690     V2 = DAG.getUNDEF(VT);
9691     if (MaskLO >= 4)
9692       PermMask = (PermMask & 0xf0) | 0x08;
9693     if (MaskHI >= 4)
9694       PermMask = (PermMask & 0x0f) | 0x80;
9695   }
9696
9697   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9698                      DAG.getConstant(PermMask, DL, MVT::i8));
9699 }
9700
9701 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9702 /// shuffling each lane.
9703 ///
9704 /// This will only succeed when the result of fixing the 128-bit lanes results
9705 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9706 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9707 /// the lane crosses early and then use simpler shuffles within each lane.
9708 ///
9709 /// FIXME: It might be worthwhile at some point to support this without
9710 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9711 /// in x86 only floating point has interesting non-repeating shuffles, and even
9712 /// those are still *marginally* more expensive.
9713 static SDValue lowerVectorShuffleByMerging128BitLanes(
9714     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9715     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9716   assert(!isSingleInputShuffleMask(Mask) &&
9717          "This is only useful with multiple inputs.");
9718
9719   int Size = Mask.size();
9720   int LaneSize = 128 / VT.getScalarSizeInBits();
9721   int NumLanes = Size / LaneSize;
9722   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9723
9724   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9725   // check whether the in-128-bit lane shuffles share a repeating pattern.
9726   SmallVector<int, 4> Lanes;
9727   Lanes.resize(NumLanes, -1);
9728   SmallVector<int, 4> InLaneMask;
9729   InLaneMask.resize(LaneSize, -1);
9730   for (int i = 0; i < Size; ++i) {
9731     if (Mask[i] < 0)
9732       continue;
9733
9734     int j = i / LaneSize;
9735
9736     if (Lanes[j] < 0) {
9737       // First entry we've seen for this lane.
9738       Lanes[j] = Mask[i] / LaneSize;
9739     } else if (Lanes[j] != Mask[i] / LaneSize) {
9740       // This doesn't match the lane selected previously!
9741       return SDValue();
9742     }
9743
9744     // Check that within each lane we have a consistent shuffle mask.
9745     int k = i % LaneSize;
9746     if (InLaneMask[k] < 0) {
9747       InLaneMask[k] = Mask[i] % LaneSize;
9748     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9749       // This doesn't fit a repeating in-lane mask.
9750       return SDValue();
9751     }
9752   }
9753
9754   // First shuffle the lanes into place.
9755   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9756                                 VT.getSizeInBits() / 64);
9757   SmallVector<int, 8> LaneMask;
9758   LaneMask.resize(NumLanes * 2, -1);
9759   for (int i = 0; i < NumLanes; ++i)
9760     if (Lanes[i] >= 0) {
9761       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9762       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9763     }
9764
9765   V1 = DAG.getBitcast(LaneVT, V1);
9766   V2 = DAG.getBitcast(LaneVT, V2);
9767   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9768
9769   // Cast it back to the type we actually want.
9770   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9771
9772   // Now do a simple shuffle that isn't lane crossing.
9773   SmallVector<int, 8> NewMask;
9774   NewMask.resize(Size, -1);
9775   for (int i = 0; i < Size; ++i)
9776     if (Mask[i] >= 0)
9777       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9778   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9779          "Must not introduce lane crosses at this point!");
9780
9781   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9782 }
9783
9784 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9785 /// given mask.
9786 ///
9787 /// This returns true if the elements from a particular input are already in the
9788 /// slot required by the given mask and require no permutation.
9789 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9790   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9791   int Size = Mask.size();
9792   for (int i = 0; i < Size; ++i)
9793     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9794       return false;
9795
9796   return true;
9797 }
9798
9799 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9800                                             ArrayRef<int> Mask, SDValue V1,
9801                                             SDValue V2, SelectionDAG &DAG) {
9802
9803   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9804   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9805   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9806   int NumElts = VT.getVectorNumElements();
9807   bool ShufpdMask = true;
9808   bool CommutableMask = true;
9809   unsigned Immediate = 0;
9810   for (int i = 0; i < NumElts; ++i) {
9811     if (Mask[i] < 0)
9812       continue;
9813     int Val = (i & 6) + NumElts * (i & 1);
9814     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9815     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9816       ShufpdMask = false;
9817     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9818       CommutableMask = false;
9819     Immediate |= (Mask[i] % 2) << i;
9820   }
9821   if (ShufpdMask)
9822     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9823                        DAG.getConstant(Immediate, DL, MVT::i8));
9824   if (CommutableMask)
9825     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9826                        DAG.getConstant(Immediate, DL, MVT::i8));
9827   return SDValue();
9828 }
9829
9830 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9831 ///
9832 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9833 /// isn't available.
9834 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9835                                        const X86Subtarget *Subtarget,
9836                                        SelectionDAG &DAG) {
9837   SDLoc DL(Op);
9838   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9839   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9840   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9841   ArrayRef<int> Mask = SVOp->getMask();
9842   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9843
9844   SmallVector<int, 4> WidenedMask;
9845   if (canWidenShuffleElements(Mask, WidenedMask))
9846     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9847                                     DAG);
9848
9849   if (isSingleInputShuffleMask(Mask)) {
9850     // Check for being able to broadcast a single element.
9851     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9852                                                           Mask, Subtarget, DAG))
9853       return Broadcast;
9854
9855     // Use low duplicate instructions for masks that match their pattern.
9856     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9857       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9858
9859     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9860       // Non-half-crossing single input shuffles can be lowerid with an
9861       // interleaved permutation.
9862       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9863                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9864       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9865                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9866     }
9867
9868     // With AVX2 we have direct support for this permutation.
9869     if (Subtarget->hasAVX2())
9870       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9871                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9872
9873     // Otherwise, fall back.
9874     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9875                                                    DAG);
9876   }
9877
9878   // X86 has dedicated unpack instructions that can handle specific blend
9879   // operations: UNPCKH and UNPCKL.
9880   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9881     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9882   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9883     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9884   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9885     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9886   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9887     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9888
9889   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9890                                                 Subtarget, DAG))
9891     return Blend;
9892
9893   // Check if the blend happens to exactly fit that of SHUFPD.
9894   if (SDValue Op =
9895       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9896     return Op;
9897
9898   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9899   // shuffle. However, if we have AVX2 and either inputs are already in place,
9900   // we will be able to shuffle even across lanes the other input in a single
9901   // instruction so skip this pattern.
9902   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9903                                  isShuffleMaskInputInPlace(1, Mask))))
9904     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9905             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9906       return Result;
9907
9908   // If we have AVX2 then we always want to lower with a blend because an v4 we
9909   // can fully permute the elements.
9910   if (Subtarget->hasAVX2())
9911     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9912                                                       Mask, DAG);
9913
9914   // Otherwise fall back on generic lowering.
9915   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9916 }
9917
9918 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9919 ///
9920 /// This routine is only called when we have AVX2 and thus a reasonable
9921 /// instruction set for v4i64 shuffling..
9922 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9923                                        const X86Subtarget *Subtarget,
9924                                        SelectionDAG &DAG) {
9925   SDLoc DL(Op);
9926   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9927   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9928   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9929   ArrayRef<int> Mask = SVOp->getMask();
9930   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9931   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9932
9933   SmallVector<int, 4> WidenedMask;
9934   if (canWidenShuffleElements(Mask, WidenedMask))
9935     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9936                                     DAG);
9937
9938   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9939                                                 Subtarget, DAG))
9940     return Blend;
9941
9942   // Check for being able to broadcast a single element.
9943   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9944                                                         Mask, Subtarget, DAG))
9945     return Broadcast;
9946
9947   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9948   // use lower latency instructions that will operate on both 128-bit lanes.
9949   SmallVector<int, 2> RepeatedMask;
9950   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9951     if (isSingleInputShuffleMask(Mask)) {
9952       int PSHUFDMask[] = {-1, -1, -1, -1};
9953       for (int i = 0; i < 2; ++i)
9954         if (RepeatedMask[i] >= 0) {
9955           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9956           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9957         }
9958       return DAG.getBitcast(
9959           MVT::v4i64,
9960           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9961                       DAG.getBitcast(MVT::v8i32, V1),
9962                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9963     }
9964   }
9965
9966   // AVX2 provides a direct instruction for permuting a single input across
9967   // lanes.
9968   if (isSingleInputShuffleMask(Mask))
9969     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9970                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9971
9972   // Try to use shift instructions.
9973   if (SDValue Shift =
9974           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9975     return Shift;
9976
9977   // Use dedicated unpack instructions for masks that match their pattern.
9978   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9979     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9980   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9981     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9982   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9983     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9984   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9985     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9986
9987   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9988   // shuffle. However, if we have AVX2 and either inputs are already in place,
9989   // we will be able to shuffle even across lanes the other input in a single
9990   // instruction so skip this pattern.
9991   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9992                                  isShuffleMaskInputInPlace(1, Mask))))
9993     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9994             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9995       return Result;
9996
9997   // Otherwise fall back on generic blend lowering.
9998   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9999                                                     Mask, DAG);
10000 }
10001
10002 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10003 ///
10004 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10005 /// isn't available.
10006 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10007                                        const X86Subtarget *Subtarget,
10008                                        SelectionDAG &DAG) {
10009   SDLoc DL(Op);
10010   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10011   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10012   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10013   ArrayRef<int> Mask = SVOp->getMask();
10014   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10015
10016   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10017                                                 Subtarget, DAG))
10018     return Blend;
10019
10020   // Check for being able to broadcast a single element.
10021   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10022                                                         Mask, Subtarget, DAG))
10023     return Broadcast;
10024
10025   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10026   // options to efficiently lower the shuffle.
10027   SmallVector<int, 4> RepeatedMask;
10028   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10029     assert(RepeatedMask.size() == 4 &&
10030            "Repeated masks must be half the mask width!");
10031
10032     // Use even/odd duplicate instructions for masks that match their pattern.
10033     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10034       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10035     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10036       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10037
10038     if (isSingleInputShuffleMask(Mask))
10039       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10040                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10041
10042     // Use dedicated unpack instructions for masks that match their pattern.
10043     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10044       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10045     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10046       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10047     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10048       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10049     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10050       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10051
10052     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10053     // have already handled any direct blends. We also need to squash the
10054     // repeated mask into a simulated v4f32 mask.
10055     for (int i = 0; i < 4; ++i)
10056       if (RepeatedMask[i] >= 8)
10057         RepeatedMask[i] -= 4;
10058     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10059   }
10060
10061   // If we have a single input shuffle with different shuffle patterns in the
10062   // two 128-bit lanes use the variable mask to VPERMILPS.
10063   if (isSingleInputShuffleMask(Mask)) {
10064     SDValue VPermMask[8];
10065     for (int i = 0; i < 8; ++i)
10066       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10067                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10068     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10069       return DAG.getNode(
10070           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10071           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10072
10073     if (Subtarget->hasAVX2())
10074       return DAG.getNode(
10075           X86ISD::VPERMV, DL, MVT::v8f32,
10076           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10077                                                  MVT::v8i32, VPermMask)),
10078           V1);
10079
10080     // Otherwise, fall back.
10081     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10082                                                    DAG);
10083   }
10084
10085   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10086   // shuffle.
10087   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10088           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10089     return Result;
10090
10091   // If we have AVX2 then we always want to lower with a blend because at v8 we
10092   // can fully permute the elements.
10093   if (Subtarget->hasAVX2())
10094     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10095                                                       Mask, DAG);
10096
10097   // Otherwise fall back on generic lowering.
10098   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10099 }
10100
10101 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10102 ///
10103 /// This routine is only called when we have AVX2 and thus a reasonable
10104 /// instruction set for v8i32 shuffling..
10105 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10106                                        const X86Subtarget *Subtarget,
10107                                        SelectionDAG &DAG) {
10108   SDLoc DL(Op);
10109   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10110   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10111   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10112   ArrayRef<int> Mask = SVOp->getMask();
10113   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10114   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10115
10116   // Whenever we can lower this as a zext, that instruction is strictly faster
10117   // than any alternative. It also allows us to fold memory operands into the
10118   // shuffle in many cases.
10119   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10120                                                          Mask, Subtarget, DAG))
10121     return ZExt;
10122
10123   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10124                                                 Subtarget, DAG))
10125     return Blend;
10126
10127   // Check for being able to broadcast a single element.
10128   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10129                                                         Mask, Subtarget, DAG))
10130     return Broadcast;
10131
10132   // If the shuffle mask is repeated in each 128-bit lane we can use more
10133   // efficient instructions that mirror the shuffles across the two 128-bit
10134   // lanes.
10135   SmallVector<int, 4> RepeatedMask;
10136   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10137     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10138     if (isSingleInputShuffleMask(Mask))
10139       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10140                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10141
10142     // Use dedicated unpack instructions for masks that match their pattern.
10143     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10144       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10145     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10146       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10147     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10148       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10149     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10150       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10151   }
10152
10153   // Try to use shift instructions.
10154   if (SDValue Shift =
10155           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10156     return Shift;
10157
10158   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10159           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10160     return Rotate;
10161
10162   // If the shuffle patterns aren't repeated but it is a single input, directly
10163   // generate a cross-lane VPERMD instruction.
10164   if (isSingleInputShuffleMask(Mask)) {
10165     SDValue VPermMask[8];
10166     for (int i = 0; i < 8; ++i)
10167       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10168                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10169     return DAG.getNode(
10170         X86ISD::VPERMV, DL, MVT::v8i32,
10171         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10172   }
10173
10174   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10175   // shuffle.
10176   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10177           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10178     return Result;
10179
10180   // Otherwise fall back on generic blend lowering.
10181   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10182                                                     Mask, DAG);
10183 }
10184
10185 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10186 ///
10187 /// This routine is only called when we have AVX2 and thus a reasonable
10188 /// instruction set for v16i16 shuffling..
10189 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10190                                         const X86Subtarget *Subtarget,
10191                                         SelectionDAG &DAG) {
10192   SDLoc DL(Op);
10193   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10194   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10195   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10196   ArrayRef<int> Mask = SVOp->getMask();
10197   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10198   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10199
10200   // Whenever we can lower this as a zext, that instruction is strictly faster
10201   // than any alternative. It also allows us to fold memory operands into the
10202   // shuffle in many cases.
10203   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10204                                                          Mask, Subtarget, DAG))
10205     return ZExt;
10206
10207   // Check for being able to broadcast a single element.
10208   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10209                                                         Mask, Subtarget, DAG))
10210     return Broadcast;
10211
10212   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10213                                                 Subtarget, DAG))
10214     return Blend;
10215
10216   // Use dedicated unpack instructions for masks that match their pattern.
10217   if (isShuffleEquivalent(V1, V2, Mask,
10218                           {// First 128-bit lane:
10219                            0, 16, 1, 17, 2, 18, 3, 19,
10220                            // Second 128-bit lane:
10221                            8, 24, 9, 25, 10, 26, 11, 27}))
10222     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10223   if (isShuffleEquivalent(V1, V2, Mask,
10224                           {// First 128-bit lane:
10225                            4, 20, 5, 21, 6, 22, 7, 23,
10226                            // Second 128-bit lane:
10227                            12, 28, 13, 29, 14, 30, 15, 31}))
10228     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10229
10230   // Try to use shift instructions.
10231   if (SDValue Shift =
10232           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10233     return Shift;
10234
10235   // Try to use byte rotation instructions.
10236   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10237           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10238     return Rotate;
10239
10240   if (isSingleInputShuffleMask(Mask)) {
10241     // There are no generalized cross-lane shuffle operations available on i16
10242     // element types.
10243     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10244       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10245                                                      Mask, DAG);
10246
10247     SmallVector<int, 8> RepeatedMask;
10248     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10249       // As this is a single-input shuffle, the repeated mask should be
10250       // a strictly valid v8i16 mask that we can pass through to the v8i16
10251       // lowering to handle even the v16 case.
10252       return lowerV8I16GeneralSingleInputVectorShuffle(
10253           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10254     }
10255
10256     SDValue PSHUFBMask[32];
10257     for (int i = 0; i < 16; ++i) {
10258       if (Mask[i] == -1) {
10259         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10260         continue;
10261       }
10262
10263       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10264       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10265       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10266       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10267     }
10268     return DAG.getBitcast(MVT::v16i16,
10269                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10270                                       DAG.getBitcast(MVT::v32i8, V1),
10271                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10272                                                   MVT::v32i8, PSHUFBMask)));
10273   }
10274
10275   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10276   // shuffle.
10277   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10278           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10279     return Result;
10280
10281   // Otherwise fall back on generic lowering.
10282   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10283 }
10284
10285 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10286 ///
10287 /// This routine is only called when we have AVX2 and thus a reasonable
10288 /// instruction set for v32i8 shuffling..
10289 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10290                                        const X86Subtarget *Subtarget,
10291                                        SelectionDAG &DAG) {
10292   SDLoc DL(Op);
10293   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10294   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10295   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10296   ArrayRef<int> Mask = SVOp->getMask();
10297   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10298   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10299
10300   // Whenever we can lower this as a zext, that instruction is strictly faster
10301   // than any alternative. It also allows us to fold memory operands into the
10302   // shuffle in many cases.
10303   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10304                                                          Mask, Subtarget, DAG))
10305     return ZExt;
10306
10307   // Check for being able to broadcast a single element.
10308   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10309                                                         Mask, Subtarget, DAG))
10310     return Broadcast;
10311
10312   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10313                                                 Subtarget, DAG))
10314     return Blend;
10315
10316   // Use dedicated unpack instructions for masks that match their pattern.
10317   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10318   // 256-bit lanes.
10319   if (isShuffleEquivalent(
10320           V1, V2, Mask,
10321           {// First 128-bit lane:
10322            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10323            // Second 128-bit lane:
10324            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10325     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10326   if (isShuffleEquivalent(
10327           V1, V2, Mask,
10328           {// First 128-bit lane:
10329            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10330            // Second 128-bit lane:
10331            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10332     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10333
10334   // Try to use shift instructions.
10335   if (SDValue Shift =
10336           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10337     return Shift;
10338
10339   // Try to use byte rotation instructions.
10340   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10341           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10342     return Rotate;
10343
10344   if (isSingleInputShuffleMask(Mask)) {
10345     // There are no generalized cross-lane shuffle operations available on i8
10346     // element types.
10347     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10348       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10349                                                      Mask, DAG);
10350
10351     SDValue PSHUFBMask[32];
10352     for (int i = 0; i < 32; ++i)
10353       PSHUFBMask[i] =
10354           Mask[i] < 0
10355               ? DAG.getUNDEF(MVT::i8)
10356               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10357                                 MVT::i8);
10358
10359     return DAG.getNode(
10360         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10361         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10362   }
10363
10364   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10365   // shuffle.
10366   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10367           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10368     return Result;
10369
10370   // Otherwise fall back on generic lowering.
10371   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10372 }
10373
10374 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10375 ///
10376 /// This routine either breaks down the specific type of a 256-bit x86 vector
10377 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10378 /// together based on the available instructions.
10379 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10380                                         MVT VT, const X86Subtarget *Subtarget,
10381                                         SelectionDAG &DAG) {
10382   SDLoc DL(Op);
10383   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10384   ArrayRef<int> Mask = SVOp->getMask();
10385
10386   // If we have a single input to the zero element, insert that into V1 if we
10387   // can do so cheaply.
10388   int NumElts = VT.getVectorNumElements();
10389   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10390     return M >= NumElts;
10391   });
10392
10393   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10394     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10395                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10396       return Insertion;
10397
10398   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10399   // check for those subtargets here and avoid much of the subtarget querying in
10400   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10401   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10402   // floating point types there eventually, just immediately cast everything to
10403   // a float and operate entirely in that domain.
10404   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10405     int ElementBits = VT.getScalarSizeInBits();
10406     if (ElementBits < 32)
10407       // No floating point type available, decompose into 128-bit vectors.
10408       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10409
10410     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10411                                 VT.getVectorNumElements());
10412     V1 = DAG.getBitcast(FpVT, V1);
10413     V2 = DAG.getBitcast(FpVT, V2);
10414     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10415   }
10416
10417   switch (VT.SimpleTy) {
10418   case MVT::v4f64:
10419     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10420   case MVT::v4i64:
10421     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10422   case MVT::v8f32:
10423     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10424   case MVT::v8i32:
10425     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10426   case MVT::v16i16:
10427     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10428   case MVT::v32i8:
10429     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10430
10431   default:
10432     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10433   }
10434 }
10435
10436 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10437 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10438                                        const X86Subtarget *Subtarget,
10439                                        SelectionDAG &DAG) {
10440   SDLoc DL(Op);
10441   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10442   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10443   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10444   ArrayRef<int> Mask = SVOp->getMask();
10445   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10446
10447   // X86 has dedicated unpack instructions that can handle specific blend
10448   // operations: UNPCKH and UNPCKL.
10449   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10450     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10451   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10452     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10453
10454   // FIXME: Implement direct support for this type!
10455   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10456 }
10457
10458 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10459 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10460                                        const X86Subtarget *Subtarget,
10461                                        SelectionDAG &DAG) {
10462   SDLoc DL(Op);
10463   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10464   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10465   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10466   ArrayRef<int> Mask = SVOp->getMask();
10467   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10468
10469   // Use dedicated unpack instructions for masks that match their pattern.
10470   if (isShuffleEquivalent(V1, V2, Mask,
10471                           {// First 128-bit lane.
10472                            0, 16, 1, 17, 4, 20, 5, 21,
10473                            // Second 128-bit lane.
10474                            8, 24, 9, 25, 12, 28, 13, 29}))
10475     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10476   if (isShuffleEquivalent(V1, V2, Mask,
10477                           {// First 128-bit lane.
10478                            2, 18, 3, 19, 6, 22, 7, 23,
10479                            // Second 128-bit lane.
10480                            10, 26, 11, 27, 14, 30, 15, 31}))
10481     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10482
10483   // FIXME: Implement direct support for this type!
10484   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10485 }
10486
10487 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10488 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10489                                        const X86Subtarget *Subtarget,
10490                                        SelectionDAG &DAG) {
10491   SDLoc DL(Op);
10492   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10493   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10494   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10495   ArrayRef<int> Mask = SVOp->getMask();
10496   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10497
10498   // X86 has dedicated unpack instructions that can handle specific blend
10499   // operations: UNPCKH and UNPCKL.
10500   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10501     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10502   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10503     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10504
10505   // FIXME: Implement direct support for this type!
10506   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10507 }
10508
10509 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10510 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10511                                        const X86Subtarget *Subtarget,
10512                                        SelectionDAG &DAG) {
10513   SDLoc DL(Op);
10514   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10515   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10516   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10517   ArrayRef<int> Mask = SVOp->getMask();
10518   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10519
10520   // Use dedicated unpack instructions for masks that match their pattern.
10521   if (isShuffleEquivalent(V1, V2, Mask,
10522                           {// First 128-bit lane.
10523                            0, 16, 1, 17, 4, 20, 5, 21,
10524                            // Second 128-bit lane.
10525                            8, 24, 9, 25, 12, 28, 13, 29}))
10526     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10527   if (isShuffleEquivalent(V1, V2, Mask,
10528                           {// First 128-bit lane.
10529                            2, 18, 3, 19, 6, 22, 7, 23,
10530                            // Second 128-bit lane.
10531                            10, 26, 11, 27, 14, 30, 15, 31}))
10532     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10533
10534   // FIXME: Implement direct support for this type!
10535   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10536 }
10537
10538 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10539 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10540                                         const X86Subtarget *Subtarget,
10541                                         SelectionDAG &DAG) {
10542   SDLoc DL(Op);
10543   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10544   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10545   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10546   ArrayRef<int> Mask = SVOp->getMask();
10547   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10548   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10549
10550   // FIXME: Implement direct support for this type!
10551   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10552 }
10553
10554 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10555 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10556                                        const X86Subtarget *Subtarget,
10557                                        SelectionDAG &DAG) {
10558   SDLoc DL(Op);
10559   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10560   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10561   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10562   ArrayRef<int> Mask = SVOp->getMask();
10563   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10564   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10565
10566   // FIXME: Implement direct support for this type!
10567   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10568 }
10569
10570 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10571 ///
10572 /// This routine either breaks down the specific type of a 512-bit x86 vector
10573 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10574 /// together based on the available instructions.
10575 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10576                                         MVT VT, const X86Subtarget *Subtarget,
10577                                         SelectionDAG &DAG) {
10578   SDLoc DL(Op);
10579   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10580   ArrayRef<int> Mask = SVOp->getMask();
10581   assert(Subtarget->hasAVX512() &&
10582          "Cannot lower 512-bit vectors w/ basic ISA!");
10583
10584   // Check for being able to broadcast a single element.
10585   if (SDValue Broadcast =
10586           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10587     return Broadcast;
10588
10589   // Dispatch to each element type for lowering. If we don't have supprot for
10590   // specific element type shuffles at 512 bits, immediately split them and
10591   // lower them. Each lowering routine of a given type is allowed to assume that
10592   // the requisite ISA extensions for that element type are available.
10593   switch (VT.SimpleTy) {
10594   case MVT::v8f64:
10595     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10596   case MVT::v16f32:
10597     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10598   case MVT::v8i64:
10599     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10600   case MVT::v16i32:
10601     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10602   case MVT::v32i16:
10603     if (Subtarget->hasBWI())
10604       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10605     break;
10606   case MVT::v64i8:
10607     if (Subtarget->hasBWI())
10608       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10609     break;
10610
10611   default:
10612     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10613   }
10614
10615   // Otherwise fall back on splitting.
10616   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10617 }
10618
10619 /// \brief Top-level lowering for x86 vector shuffles.
10620 ///
10621 /// This handles decomposition, canonicalization, and lowering of all x86
10622 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10623 /// above in helper routines. The canonicalization attempts to widen shuffles
10624 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10625 /// s.t. only one of the two inputs needs to be tested, etc.
10626 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10627                                   SelectionDAG &DAG) {
10628   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10629   ArrayRef<int> Mask = SVOp->getMask();
10630   SDValue V1 = Op.getOperand(0);
10631   SDValue V2 = Op.getOperand(1);
10632   MVT VT = Op.getSimpleValueType();
10633   int NumElements = VT.getVectorNumElements();
10634   SDLoc dl(Op);
10635
10636   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10637
10638   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10639   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10640   if (V1IsUndef && V2IsUndef)
10641     return DAG.getUNDEF(VT);
10642
10643   // When we create a shuffle node we put the UNDEF node to second operand,
10644   // but in some cases the first operand may be transformed to UNDEF.
10645   // In this case we should just commute the node.
10646   if (V1IsUndef)
10647     return DAG.getCommutedVectorShuffle(*SVOp);
10648
10649   // Check for non-undef masks pointing at an undef vector and make the masks
10650   // undef as well. This makes it easier to match the shuffle based solely on
10651   // the mask.
10652   if (V2IsUndef)
10653     for (int M : Mask)
10654       if (M >= NumElements) {
10655         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10656         for (int &M : NewMask)
10657           if (M >= NumElements)
10658             M = -1;
10659         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10660       }
10661
10662   // We actually see shuffles that are entirely re-arrangements of a set of
10663   // zero inputs. This mostly happens while decomposing complex shuffles into
10664   // simple ones. Directly lower these as a buildvector of zeros.
10665   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10666   if (Zeroable.all())
10667     return getZeroVector(VT, Subtarget, DAG, dl);
10668
10669   // Try to collapse shuffles into using a vector type with fewer elements but
10670   // wider element types. We cap this to not form integers or floating point
10671   // elements wider than 64 bits, but it might be interesting to form i128
10672   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10673   SmallVector<int, 16> WidenedMask;
10674   if (VT.getScalarSizeInBits() < 64 &&
10675       canWidenShuffleElements(Mask, WidenedMask)) {
10676     MVT NewEltVT = VT.isFloatingPoint()
10677                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10678                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10679     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10680     // Make sure that the new vector type is legal. For example, v2f64 isn't
10681     // legal on SSE1.
10682     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10683       V1 = DAG.getBitcast(NewVT, V1);
10684       V2 = DAG.getBitcast(NewVT, V2);
10685       return DAG.getBitcast(
10686           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10687     }
10688   }
10689
10690   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10691   for (int M : SVOp->getMask())
10692     if (M < 0)
10693       ++NumUndefElements;
10694     else if (M < NumElements)
10695       ++NumV1Elements;
10696     else
10697       ++NumV2Elements;
10698
10699   // Commute the shuffle as needed such that more elements come from V1 than
10700   // V2. This allows us to match the shuffle pattern strictly on how many
10701   // elements come from V1 without handling the symmetric cases.
10702   if (NumV2Elements > NumV1Elements)
10703     return DAG.getCommutedVectorShuffle(*SVOp);
10704
10705   // When the number of V1 and V2 elements are the same, try to minimize the
10706   // number of uses of V2 in the low half of the vector. When that is tied,
10707   // ensure that the sum of indices for V1 is equal to or lower than the sum
10708   // indices for V2. When those are equal, try to ensure that the number of odd
10709   // indices for V1 is lower than the number of odd indices for V2.
10710   if (NumV1Elements == NumV2Elements) {
10711     int LowV1Elements = 0, LowV2Elements = 0;
10712     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10713       if (M >= NumElements)
10714         ++LowV2Elements;
10715       else if (M >= 0)
10716         ++LowV1Elements;
10717     if (LowV2Elements > LowV1Elements) {
10718       return DAG.getCommutedVectorShuffle(*SVOp);
10719     } else if (LowV2Elements == LowV1Elements) {
10720       int SumV1Indices = 0, SumV2Indices = 0;
10721       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10722         if (SVOp->getMask()[i] >= NumElements)
10723           SumV2Indices += i;
10724         else if (SVOp->getMask()[i] >= 0)
10725           SumV1Indices += i;
10726       if (SumV2Indices < SumV1Indices) {
10727         return DAG.getCommutedVectorShuffle(*SVOp);
10728       } else if (SumV2Indices == SumV1Indices) {
10729         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10730         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10731           if (SVOp->getMask()[i] >= NumElements)
10732             NumV2OddIndices += i % 2;
10733           else if (SVOp->getMask()[i] >= 0)
10734             NumV1OddIndices += i % 2;
10735         if (NumV2OddIndices < NumV1OddIndices)
10736           return DAG.getCommutedVectorShuffle(*SVOp);
10737       }
10738     }
10739   }
10740
10741   // For each vector width, delegate to a specialized lowering routine.
10742   if (VT.getSizeInBits() == 128)
10743     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10744
10745   if (VT.getSizeInBits() == 256)
10746     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10747
10748   // Force AVX-512 vectors to be scalarized for now.
10749   // FIXME: Implement AVX-512 support!
10750   if (VT.getSizeInBits() == 512)
10751     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10752
10753   llvm_unreachable("Unimplemented!");
10754 }
10755
10756 // This function assumes its argument is a BUILD_VECTOR of constants or
10757 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10758 // true.
10759 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10760                                     unsigned &MaskValue) {
10761   MaskValue = 0;
10762   unsigned NumElems = BuildVector->getNumOperands();
10763   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10764   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10765   unsigned NumElemsInLane = NumElems / NumLanes;
10766
10767   // Blend for v16i16 should be symmetric for the both lanes.
10768   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10769     SDValue EltCond = BuildVector->getOperand(i);
10770     SDValue SndLaneEltCond =
10771         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10772
10773     int Lane1Cond = -1, Lane2Cond = -1;
10774     if (isa<ConstantSDNode>(EltCond))
10775       Lane1Cond = !isZero(EltCond);
10776     if (isa<ConstantSDNode>(SndLaneEltCond))
10777       Lane2Cond = !isZero(SndLaneEltCond);
10778
10779     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10780       // Lane1Cond != 0, means we want the first argument.
10781       // Lane1Cond == 0, means we want the second argument.
10782       // The encoding of this argument is 0 for the first argument, 1
10783       // for the second. Therefore, invert the condition.
10784       MaskValue |= !Lane1Cond << i;
10785     else if (Lane1Cond < 0)
10786       MaskValue |= !Lane2Cond << i;
10787     else
10788       return false;
10789   }
10790   return true;
10791 }
10792
10793 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10794 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10795                                            const X86Subtarget *Subtarget,
10796                                            SelectionDAG &DAG) {
10797   SDValue Cond = Op.getOperand(0);
10798   SDValue LHS = Op.getOperand(1);
10799   SDValue RHS = Op.getOperand(2);
10800   SDLoc dl(Op);
10801   MVT VT = Op.getSimpleValueType();
10802
10803   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10804     return SDValue();
10805   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10806
10807   // Only non-legal VSELECTs reach this lowering, convert those into generic
10808   // shuffles and re-use the shuffle lowering path for blends.
10809   SmallVector<int, 32> Mask;
10810   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10811     SDValue CondElt = CondBV->getOperand(i);
10812     Mask.push_back(
10813         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10814   }
10815   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10816 }
10817
10818 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10819   // A vselect where all conditions and data are constants can be optimized into
10820   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10821   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10822       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10823       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10824     return SDValue();
10825
10826   // Try to lower this to a blend-style vector shuffle. This can handle all
10827   // constant condition cases.
10828   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10829     return BlendOp;
10830
10831   // Variable blends are only legal from SSE4.1 onward.
10832   if (!Subtarget->hasSSE41())
10833     return SDValue();
10834
10835   // Only some types will be legal on some subtargets. If we can emit a legal
10836   // VSELECT-matching blend, return Op, and but if we need to expand, return
10837   // a null value.
10838   switch (Op.getSimpleValueType().SimpleTy) {
10839   default:
10840     // Most of the vector types have blends past SSE4.1.
10841     return Op;
10842
10843   case MVT::v32i8:
10844     // The byte blends for AVX vectors were introduced only in AVX2.
10845     if (Subtarget->hasAVX2())
10846       return Op;
10847
10848     return SDValue();
10849
10850   case MVT::v8i16:
10851   case MVT::v16i16:
10852     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10853     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10854       return Op;
10855
10856     // FIXME: We should custom lower this by fixing the condition and using i8
10857     // blends.
10858     return SDValue();
10859   }
10860 }
10861
10862 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10863   MVT VT = Op.getSimpleValueType();
10864   SDLoc dl(Op);
10865
10866   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10867     return SDValue();
10868
10869   if (VT.getSizeInBits() == 8) {
10870     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10871                                   Op.getOperand(0), Op.getOperand(1));
10872     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10873                                   DAG.getValueType(VT));
10874     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10875   }
10876
10877   if (VT.getSizeInBits() == 16) {
10878     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10879     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10880     if (Idx == 0)
10881       return DAG.getNode(
10882           ISD::TRUNCATE, dl, MVT::i16,
10883           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10884                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10885                       Op.getOperand(1)));
10886     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10887                                   Op.getOperand(0), Op.getOperand(1));
10888     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10889                                   DAG.getValueType(VT));
10890     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10891   }
10892
10893   if (VT == MVT::f32) {
10894     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10895     // the result back to FR32 register. It's only worth matching if the
10896     // result has a single use which is a store or a bitcast to i32.  And in
10897     // the case of a store, it's not worth it if the index is a constant 0,
10898     // because a MOVSSmr can be used instead, which is smaller and faster.
10899     if (!Op.hasOneUse())
10900       return SDValue();
10901     SDNode *User = *Op.getNode()->use_begin();
10902     if ((User->getOpcode() != ISD::STORE ||
10903          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10904           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10905         (User->getOpcode() != ISD::BITCAST ||
10906          User->getValueType(0) != MVT::i32))
10907       return SDValue();
10908     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10909                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10910                                   Op.getOperand(1));
10911     return DAG.getBitcast(MVT::f32, Extract);
10912   }
10913
10914   if (VT == MVT::i32 || VT == MVT::i64) {
10915     // ExtractPS/pextrq works with constant index.
10916     if (isa<ConstantSDNode>(Op.getOperand(1)))
10917       return Op;
10918   }
10919   return SDValue();
10920 }
10921
10922 /// Extract one bit from mask vector, like v16i1 or v8i1.
10923 /// AVX-512 feature.
10924 SDValue
10925 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10926   SDValue Vec = Op.getOperand(0);
10927   SDLoc dl(Vec);
10928   MVT VecVT = Vec.getSimpleValueType();
10929   SDValue Idx = Op.getOperand(1);
10930   MVT EltVT = Op.getSimpleValueType();
10931
10932   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10933   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10934          "Unexpected vector type in ExtractBitFromMaskVector");
10935
10936   // variable index can't be handled in mask registers,
10937   // extend vector to VR512
10938   if (!isa<ConstantSDNode>(Idx)) {
10939     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10940     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10941     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10942                               ExtVT.getVectorElementType(), Ext, Idx);
10943     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10944   }
10945
10946   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10947   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10948   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10949     rc = getRegClassFor(MVT::v16i1);
10950   unsigned MaxSift = rc->getSize()*8 - 1;
10951   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10952                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10953   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10954                     DAG.getConstant(MaxSift, dl, MVT::i8));
10955   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10956                        DAG.getIntPtrConstant(0, dl));
10957 }
10958
10959 SDValue
10960 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10961                                            SelectionDAG &DAG) const {
10962   SDLoc dl(Op);
10963   SDValue Vec = Op.getOperand(0);
10964   MVT VecVT = Vec.getSimpleValueType();
10965   SDValue Idx = Op.getOperand(1);
10966
10967   if (Op.getSimpleValueType() == MVT::i1)
10968     return ExtractBitFromMaskVector(Op, DAG);
10969
10970   if (!isa<ConstantSDNode>(Idx)) {
10971     if (VecVT.is512BitVector() ||
10972         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10973          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10974
10975       MVT MaskEltVT =
10976         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10977       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10978                                     MaskEltVT.getSizeInBits());
10979
10980       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10981       auto PtrVT = getPointerTy(DAG.getDataLayout());
10982       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10983                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10984                                  DAG.getConstant(0, dl, PtrVT));
10985       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10986       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10987                          DAG.getConstant(0, dl, PtrVT));
10988     }
10989     return SDValue();
10990   }
10991
10992   // If this is a 256-bit vector result, first extract the 128-bit vector and
10993   // then extract the element from the 128-bit vector.
10994   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10995
10996     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10997     // Get the 128-bit vector.
10998     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10999     MVT EltVT = VecVT.getVectorElementType();
11000
11001     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11002
11003     //if (IdxVal >= NumElems/2)
11004     //  IdxVal -= NumElems/2;
11005     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
11006     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11007                        DAG.getConstant(IdxVal, dl, MVT::i32));
11008   }
11009
11010   assert(VecVT.is128BitVector() && "Unexpected vector length");
11011
11012   if (Subtarget->hasSSE41())
11013     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11014       return Res;
11015
11016   MVT VT = Op.getSimpleValueType();
11017   // TODO: handle v16i8.
11018   if (VT.getSizeInBits() == 16) {
11019     SDValue Vec = Op.getOperand(0);
11020     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11021     if (Idx == 0)
11022       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11023                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11024                                      DAG.getBitcast(MVT::v4i32, Vec),
11025                                      Op.getOperand(1)));
11026     // Transform it so it match pextrw which produces a 32-bit result.
11027     MVT EltVT = MVT::i32;
11028     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11029                                   Op.getOperand(0), Op.getOperand(1));
11030     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11031                                   DAG.getValueType(VT));
11032     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11033   }
11034
11035   if (VT.getSizeInBits() == 32) {
11036     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11037     if (Idx == 0)
11038       return Op;
11039
11040     // SHUFPS the element to the lowest double word, then movss.
11041     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11042     MVT VVT = Op.getOperand(0).getSimpleValueType();
11043     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11044                                        DAG.getUNDEF(VVT), Mask);
11045     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11046                        DAG.getIntPtrConstant(0, dl));
11047   }
11048
11049   if (VT.getSizeInBits() == 64) {
11050     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11051     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11052     //        to match extract_elt for f64.
11053     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11054     if (Idx == 0)
11055       return Op;
11056
11057     // UNPCKHPD the element to the lowest double word, then movsd.
11058     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11059     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11060     int Mask[2] = { 1, -1 };
11061     MVT VVT = Op.getOperand(0).getSimpleValueType();
11062     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11063                                        DAG.getUNDEF(VVT), Mask);
11064     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11065                        DAG.getIntPtrConstant(0, dl));
11066   }
11067
11068   return SDValue();
11069 }
11070
11071 /// Insert one bit to mask vector, like v16i1 or v8i1.
11072 /// AVX-512 feature.
11073 SDValue
11074 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11075   SDLoc dl(Op);
11076   SDValue Vec = Op.getOperand(0);
11077   SDValue Elt = Op.getOperand(1);
11078   SDValue Idx = Op.getOperand(2);
11079   MVT VecVT = Vec.getSimpleValueType();
11080
11081   if (!isa<ConstantSDNode>(Idx)) {
11082     // Non constant index. Extend source and destination,
11083     // insert element and then truncate the result.
11084     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11085     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11086     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11087       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11088       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11089     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11090   }
11091
11092   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11093   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11094   if (IdxVal)
11095     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11096                            DAG.getConstant(IdxVal, dl, MVT::i8));
11097   if (Vec.getOpcode() == ISD::UNDEF)
11098     return EltInVec;
11099   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11100 }
11101
11102 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11103                                                   SelectionDAG &DAG) const {
11104   MVT VT = Op.getSimpleValueType();
11105   MVT EltVT = VT.getVectorElementType();
11106
11107   if (EltVT == MVT::i1)
11108     return InsertBitToMaskVector(Op, DAG);
11109
11110   SDLoc dl(Op);
11111   SDValue N0 = Op.getOperand(0);
11112   SDValue N1 = Op.getOperand(1);
11113   SDValue N2 = Op.getOperand(2);
11114   if (!isa<ConstantSDNode>(N2))
11115     return SDValue();
11116   auto *N2C = cast<ConstantSDNode>(N2);
11117   unsigned IdxVal = N2C->getZExtValue();
11118
11119   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11120   // into that, and then insert the subvector back into the result.
11121   if (VT.is256BitVector() || VT.is512BitVector()) {
11122     // With a 256-bit vector, we can insert into the zero element efficiently
11123     // using a blend if we have AVX or AVX2 and the right data type.
11124     if (VT.is256BitVector() && IdxVal == 0) {
11125       // TODO: It is worthwhile to cast integer to floating point and back
11126       // and incur a domain crossing penalty if that's what we'll end up
11127       // doing anyway after extracting to a 128-bit vector.
11128       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11129           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11130         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11131         N2 = DAG.getIntPtrConstant(1, dl);
11132         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11133       }
11134     }
11135
11136     // Get the desired 128-bit vector chunk.
11137     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11138
11139     // Insert the element into the desired chunk.
11140     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11141     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11142
11143     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11144                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11145
11146     // Insert the changed part back into the bigger vector
11147     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11148   }
11149   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11150
11151   if (Subtarget->hasSSE41()) {
11152     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11153       unsigned Opc;
11154       if (VT == MVT::v8i16) {
11155         Opc = X86ISD::PINSRW;
11156       } else {
11157         assert(VT == MVT::v16i8);
11158         Opc = X86ISD::PINSRB;
11159       }
11160
11161       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11162       // argument.
11163       if (N1.getValueType() != MVT::i32)
11164         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11165       if (N2.getValueType() != MVT::i32)
11166         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11167       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11168     }
11169
11170     if (EltVT == MVT::f32) {
11171       // Bits [7:6] of the constant are the source select. This will always be
11172       //   zero here. The DAG Combiner may combine an extract_elt index into
11173       //   these bits. For example (insert (extract, 3), 2) could be matched by
11174       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11175       // Bits [5:4] of the constant are the destination select. This is the
11176       //   value of the incoming immediate.
11177       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11178       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11179
11180       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11181       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11182         // If this is an insertion of 32-bits into the low 32-bits of
11183         // a vector, we prefer to generate a blend with immediate rather
11184         // than an insertps. Blends are simpler operations in hardware and so
11185         // will always have equal or better performance than insertps.
11186         // But if optimizing for size and there's a load folding opportunity,
11187         // generate insertps because blendps does not have a 32-bit memory
11188         // operand form.
11189         N2 = DAG.getIntPtrConstant(1, dl);
11190         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11191         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11192       }
11193       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11194       // Create this as a scalar to vector..
11195       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11196       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11197     }
11198
11199     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11200       // PINSR* works with constant index.
11201       return Op;
11202     }
11203   }
11204
11205   if (EltVT == MVT::i8)
11206     return SDValue();
11207
11208   if (EltVT.getSizeInBits() == 16) {
11209     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11210     // as its second argument.
11211     if (N1.getValueType() != MVT::i32)
11212       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11213     if (N2.getValueType() != MVT::i32)
11214       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11215     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11216   }
11217   return SDValue();
11218 }
11219
11220 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11221   SDLoc dl(Op);
11222   MVT OpVT = Op.getSimpleValueType();
11223
11224   // If this is a 256-bit vector result, first insert into a 128-bit
11225   // vector and then insert into the 256-bit vector.
11226   if (!OpVT.is128BitVector()) {
11227     // Insert into a 128-bit vector.
11228     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11229     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11230                                  OpVT.getVectorNumElements() / SizeFactor);
11231
11232     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11233
11234     // Insert the 128-bit vector.
11235     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11236   }
11237
11238   if (OpVT == MVT::v1i64 &&
11239       Op.getOperand(0).getValueType() == MVT::i64)
11240     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11241
11242   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11243   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11244   return DAG.getBitcast(
11245       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11246 }
11247
11248 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11249 // a simple subregister reference or explicit instructions to grab
11250 // upper bits of a vector.
11251 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11252                                       SelectionDAG &DAG) {
11253   SDLoc dl(Op);
11254   SDValue In =  Op.getOperand(0);
11255   SDValue Idx = Op.getOperand(1);
11256   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11257   MVT ResVT   = Op.getSimpleValueType();
11258   MVT InVT    = In.getSimpleValueType();
11259
11260   if (Subtarget->hasFp256()) {
11261     if (ResVT.is128BitVector() &&
11262         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11263         isa<ConstantSDNode>(Idx)) {
11264       return Extract128BitVector(In, IdxVal, DAG, dl);
11265     }
11266     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11267         isa<ConstantSDNode>(Idx)) {
11268       return Extract256BitVector(In, IdxVal, DAG, dl);
11269     }
11270   }
11271   return SDValue();
11272 }
11273
11274 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11275 // simple superregister reference or explicit instructions to insert
11276 // the upper bits of a vector.
11277 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11278                                      SelectionDAG &DAG) {
11279   if (!Subtarget->hasAVX())
11280     return SDValue();
11281
11282   SDLoc dl(Op);
11283   SDValue Vec = Op.getOperand(0);
11284   SDValue SubVec = Op.getOperand(1);
11285   SDValue Idx = Op.getOperand(2);
11286
11287   if (!isa<ConstantSDNode>(Idx))
11288     return SDValue();
11289
11290   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11291   MVT OpVT = Op.getSimpleValueType();
11292   MVT SubVecVT = SubVec.getSimpleValueType();
11293
11294   // Fold two 16-byte subvector loads into one 32-byte load:
11295   // (insert_subvector (insert_subvector undef, (load addr), 0),
11296   //                   (load addr + 16), Elts/2)
11297   // --> load32 addr
11298   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11299       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11300       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11301     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11302     if (Idx2 && Idx2->getZExtValue() == 0) {
11303       SDValue SubVec2 = Vec.getOperand(1);
11304       // If needed, look through a bitcast to get to the load.
11305       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11306         SubVec2 = SubVec2.getOperand(0);
11307       
11308       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11309         bool Fast;
11310         unsigned Alignment = FirstLd->getAlignment();
11311         unsigned AS = FirstLd->getAddressSpace();
11312         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11313         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11314                                     OpVT, AS, Alignment, &Fast) && Fast) {
11315           SDValue Ops[] = { SubVec2, SubVec };
11316           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11317             return Ld;
11318         }
11319       }
11320     }
11321   }
11322
11323   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11324       SubVecVT.is128BitVector())
11325     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11326
11327   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11328     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11329
11330   if (OpVT.getVectorElementType() == MVT::i1) {
11331     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11332       return Op;
11333     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11334     SDValue Undef = DAG.getUNDEF(OpVT);
11335     unsigned NumElems = OpVT.getVectorNumElements();
11336     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11337
11338     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11339       // Zero upper bits of the Vec
11340       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11341       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11342
11343       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11344                                  SubVec, ZeroIdx);
11345       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11346       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11347     }
11348     if (IdxVal == 0) {
11349       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11350                                  SubVec, ZeroIdx);
11351       // Zero upper bits of the Vec2
11352       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11353       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11354       // Zero lower bits of the Vec
11355       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11356       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11357       // Merge them together
11358       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11359     }
11360   }
11361   return SDValue();
11362 }
11363
11364 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11365 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11366 // one of the above mentioned nodes. It has to be wrapped because otherwise
11367 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11368 // be used to form addressing mode. These wrapped nodes will be selected
11369 // into MOV32ri.
11370 SDValue
11371 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11372   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11373
11374   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11375   // global base reg.
11376   unsigned char OpFlag = 0;
11377   unsigned WrapperKind = X86ISD::Wrapper;
11378   CodeModel::Model M = DAG.getTarget().getCodeModel();
11379
11380   if (Subtarget->isPICStyleRIPRel() &&
11381       (M == CodeModel::Small || M == CodeModel::Kernel))
11382     WrapperKind = X86ISD::WrapperRIP;
11383   else if (Subtarget->isPICStyleGOT())
11384     OpFlag = X86II::MO_GOTOFF;
11385   else if (Subtarget->isPICStyleStubPIC())
11386     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11387
11388   auto PtrVT = getPointerTy(DAG.getDataLayout());
11389   SDValue Result = DAG.getTargetConstantPool(
11390       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11391   SDLoc DL(CP);
11392   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11393   // With PIC, the address is actually $g + Offset.
11394   if (OpFlag) {
11395     Result =
11396         DAG.getNode(ISD::ADD, DL, PtrVT,
11397                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11398   }
11399
11400   return Result;
11401 }
11402
11403 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11404   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11405
11406   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11407   // global base reg.
11408   unsigned char OpFlag = 0;
11409   unsigned WrapperKind = X86ISD::Wrapper;
11410   CodeModel::Model M = DAG.getTarget().getCodeModel();
11411
11412   if (Subtarget->isPICStyleRIPRel() &&
11413       (M == CodeModel::Small || M == CodeModel::Kernel))
11414     WrapperKind = X86ISD::WrapperRIP;
11415   else if (Subtarget->isPICStyleGOT())
11416     OpFlag = X86II::MO_GOTOFF;
11417   else if (Subtarget->isPICStyleStubPIC())
11418     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11419
11420   auto PtrVT = getPointerTy(DAG.getDataLayout());
11421   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11422   SDLoc DL(JT);
11423   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11424
11425   // With PIC, the address is actually $g + Offset.
11426   if (OpFlag)
11427     Result =
11428         DAG.getNode(ISD::ADD, DL, PtrVT,
11429                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11430
11431   return Result;
11432 }
11433
11434 SDValue
11435 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11436   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11437
11438   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11439   // global base reg.
11440   unsigned char OpFlag = 0;
11441   unsigned WrapperKind = X86ISD::Wrapper;
11442   CodeModel::Model M = DAG.getTarget().getCodeModel();
11443
11444   if (Subtarget->isPICStyleRIPRel() &&
11445       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11446     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11447       OpFlag = X86II::MO_GOTPCREL;
11448     WrapperKind = X86ISD::WrapperRIP;
11449   } else if (Subtarget->isPICStyleGOT()) {
11450     OpFlag = X86II::MO_GOT;
11451   } else if (Subtarget->isPICStyleStubPIC()) {
11452     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11453   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11454     OpFlag = X86II::MO_DARWIN_NONLAZY;
11455   }
11456
11457   auto PtrVT = getPointerTy(DAG.getDataLayout());
11458   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11459
11460   SDLoc DL(Op);
11461   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11462
11463   // With PIC, the address is actually $g + Offset.
11464   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11465       !Subtarget->is64Bit()) {
11466     Result =
11467         DAG.getNode(ISD::ADD, DL, PtrVT,
11468                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11469   }
11470
11471   // For symbols that require a load from a stub to get the address, emit the
11472   // load.
11473   if (isGlobalStubReference(OpFlag))
11474     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11475                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11476                          false, false, false, 0);
11477
11478   return Result;
11479 }
11480
11481 SDValue
11482 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11483   // Create the TargetBlockAddressAddress node.
11484   unsigned char OpFlags =
11485     Subtarget->ClassifyBlockAddressReference();
11486   CodeModel::Model M = DAG.getTarget().getCodeModel();
11487   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11488   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11489   SDLoc dl(Op);
11490   auto PtrVT = getPointerTy(DAG.getDataLayout());
11491   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11492
11493   if (Subtarget->isPICStyleRIPRel() &&
11494       (M == CodeModel::Small || M == CodeModel::Kernel))
11495     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11496   else
11497     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11498
11499   // With PIC, the address is actually $g + Offset.
11500   if (isGlobalRelativeToPICBase(OpFlags)) {
11501     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11502                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11503   }
11504
11505   return Result;
11506 }
11507
11508 SDValue
11509 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11510                                       int64_t Offset, SelectionDAG &DAG) const {
11511   // Create the TargetGlobalAddress node, folding in the constant
11512   // offset if it is legal.
11513   unsigned char OpFlags =
11514       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11515   CodeModel::Model M = DAG.getTarget().getCodeModel();
11516   auto PtrVT = getPointerTy(DAG.getDataLayout());
11517   SDValue Result;
11518   if (OpFlags == X86II::MO_NO_FLAG &&
11519       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11520     // A direct static reference to a global.
11521     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11522     Offset = 0;
11523   } else {
11524     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11525   }
11526
11527   if (Subtarget->isPICStyleRIPRel() &&
11528       (M == CodeModel::Small || M == CodeModel::Kernel))
11529     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11530   else
11531     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11532
11533   // With PIC, the address is actually $g + Offset.
11534   if (isGlobalRelativeToPICBase(OpFlags)) {
11535     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11536                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11537   }
11538
11539   // For globals that require a load from a stub to get the address, emit the
11540   // load.
11541   if (isGlobalStubReference(OpFlags))
11542     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11543                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11544                          false, false, false, 0);
11545
11546   // If there was a non-zero offset that we didn't fold, create an explicit
11547   // addition for it.
11548   if (Offset != 0)
11549     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11550                          DAG.getConstant(Offset, dl, PtrVT));
11551
11552   return Result;
11553 }
11554
11555 SDValue
11556 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11557   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11558   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11559   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11560 }
11561
11562 static SDValue
11563 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11564            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11565            unsigned char OperandFlags, bool LocalDynamic = false) {
11566   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11567   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11568   SDLoc dl(GA);
11569   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11570                                            GA->getValueType(0),
11571                                            GA->getOffset(),
11572                                            OperandFlags);
11573
11574   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11575                                            : X86ISD::TLSADDR;
11576
11577   if (InFlag) {
11578     SDValue Ops[] = { Chain,  TGA, *InFlag };
11579     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11580   } else {
11581     SDValue Ops[]  = { Chain, TGA };
11582     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11583   }
11584
11585   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11586   MFI->setAdjustsStack(true);
11587   MFI->setHasCalls(true);
11588
11589   SDValue Flag = Chain.getValue(1);
11590   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11591 }
11592
11593 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11594 static SDValue
11595 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11596                                 const EVT PtrVT) {
11597   SDValue InFlag;
11598   SDLoc dl(GA);  // ? function entry point might be better
11599   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11600                                    DAG.getNode(X86ISD::GlobalBaseReg,
11601                                                SDLoc(), PtrVT), InFlag);
11602   InFlag = Chain.getValue(1);
11603
11604   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11605 }
11606
11607 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11608 static SDValue
11609 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11610                                 const EVT PtrVT) {
11611   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11612                     X86::RAX, X86II::MO_TLSGD);
11613 }
11614
11615 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11616                                            SelectionDAG &DAG,
11617                                            const EVT PtrVT,
11618                                            bool is64Bit) {
11619   SDLoc dl(GA);
11620
11621   // Get the start address of the TLS block for this module.
11622   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11623       .getInfo<X86MachineFunctionInfo>();
11624   MFI->incNumLocalDynamicTLSAccesses();
11625
11626   SDValue Base;
11627   if (is64Bit) {
11628     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11629                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11630   } else {
11631     SDValue InFlag;
11632     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11633         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11634     InFlag = Chain.getValue(1);
11635     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11636                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11637   }
11638
11639   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11640   // of Base.
11641
11642   // Build x@dtpoff.
11643   unsigned char OperandFlags = X86II::MO_DTPOFF;
11644   unsigned WrapperKind = X86ISD::Wrapper;
11645   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11646                                            GA->getValueType(0),
11647                                            GA->getOffset(), OperandFlags);
11648   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11649
11650   // Add x@dtpoff with the base.
11651   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11652 }
11653
11654 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11655 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11656                                    const EVT PtrVT, TLSModel::Model model,
11657                                    bool is64Bit, bool isPIC) {
11658   SDLoc dl(GA);
11659
11660   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11661   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11662                                                          is64Bit ? 257 : 256));
11663
11664   SDValue ThreadPointer =
11665       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11666                   MachinePointerInfo(Ptr), false, false, false, 0);
11667
11668   unsigned char OperandFlags = 0;
11669   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11670   // initialexec.
11671   unsigned WrapperKind = X86ISD::Wrapper;
11672   if (model == TLSModel::LocalExec) {
11673     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11674   } else if (model == TLSModel::InitialExec) {
11675     if (is64Bit) {
11676       OperandFlags = X86II::MO_GOTTPOFF;
11677       WrapperKind = X86ISD::WrapperRIP;
11678     } else {
11679       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11680     }
11681   } else {
11682     llvm_unreachable("Unexpected model");
11683   }
11684
11685   // emit "addl x@ntpoff,%eax" (local exec)
11686   // or "addl x@indntpoff,%eax" (initial exec)
11687   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11688   SDValue TGA =
11689       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11690                                  GA->getOffset(), OperandFlags);
11691   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11692
11693   if (model == TLSModel::InitialExec) {
11694     if (isPIC && !is64Bit) {
11695       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11696                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11697                            Offset);
11698     }
11699
11700     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11701                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11702                          false, false, false, 0);
11703   }
11704
11705   // The address of the thread local variable is the add of the thread
11706   // pointer with the offset of the variable.
11707   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11708 }
11709
11710 SDValue
11711 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11712
11713   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11714   const GlobalValue *GV = GA->getGlobal();
11715   auto PtrVT = getPointerTy(DAG.getDataLayout());
11716
11717   if (Subtarget->isTargetELF()) {
11718     if (DAG.getTarget().Options.EmulatedTLS)
11719       return LowerToTLSEmulatedModel(GA, DAG);
11720     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11721     switch (model) {
11722       case TLSModel::GeneralDynamic:
11723         if (Subtarget->is64Bit())
11724           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11725         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11726       case TLSModel::LocalDynamic:
11727         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11728                                            Subtarget->is64Bit());
11729       case TLSModel::InitialExec:
11730       case TLSModel::LocalExec:
11731         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11732                                    DAG.getTarget().getRelocationModel() ==
11733                                        Reloc::PIC_);
11734     }
11735     llvm_unreachable("Unknown TLS model.");
11736   }
11737
11738   if (Subtarget->isTargetDarwin()) {
11739     // Darwin only has one model of TLS.  Lower to that.
11740     unsigned char OpFlag = 0;
11741     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11742                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11743
11744     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11745     // global base reg.
11746     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11747                  !Subtarget->is64Bit();
11748     if (PIC32)
11749       OpFlag = X86II::MO_TLVP_PIC_BASE;
11750     else
11751       OpFlag = X86II::MO_TLVP;
11752     SDLoc DL(Op);
11753     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11754                                                 GA->getValueType(0),
11755                                                 GA->getOffset(), OpFlag);
11756     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11757
11758     // With PIC32, the address is actually $g + Offset.
11759     if (PIC32)
11760       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11761                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11762                            Offset);
11763
11764     // Lowering the machine isd will make sure everything is in the right
11765     // location.
11766     SDValue Chain = DAG.getEntryNode();
11767     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11768     SDValue Args[] = { Chain, Offset };
11769     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11770
11771     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11772     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11773     MFI->setAdjustsStack(true);
11774
11775     // And our return value (tls address) is in the standard call return value
11776     // location.
11777     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11778     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11779   }
11780
11781   if (Subtarget->isTargetKnownWindowsMSVC() ||
11782       Subtarget->isTargetWindowsGNU()) {
11783     // Just use the implicit TLS architecture
11784     // Need to generate someting similar to:
11785     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11786     //                                  ; from TEB
11787     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11788     //   mov     rcx, qword [rdx+rcx*8]
11789     //   mov     eax, .tls$:tlsvar
11790     //   [rax+rcx] contains the address
11791     // Windows 64bit: gs:0x58
11792     // Windows 32bit: fs:__tls_array
11793
11794     SDLoc dl(GA);
11795     SDValue Chain = DAG.getEntryNode();
11796
11797     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11798     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11799     // use its literal value of 0x2C.
11800     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11801                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11802                                                              256)
11803                                         : Type::getInt32PtrTy(*DAG.getContext(),
11804                                                               257));
11805
11806     SDValue TlsArray = Subtarget->is64Bit()
11807                            ? DAG.getIntPtrConstant(0x58, dl)
11808                            : (Subtarget->isTargetWindowsGNU()
11809                                   ? DAG.getIntPtrConstant(0x2C, dl)
11810                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
11811
11812     SDValue ThreadPointer =
11813         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11814                     false, false, 0);
11815
11816     SDValue res;
11817     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11818       res = ThreadPointer;
11819     } else {
11820       // Load the _tls_index variable
11821       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11822       if (Subtarget->is64Bit())
11823         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11824                              MachinePointerInfo(), MVT::i32, false, false,
11825                              false, 0);
11826       else
11827         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11828                           false, false, 0);
11829
11830       auto &DL = DAG.getDataLayout();
11831       SDValue Scale =
11832           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11833       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11834
11835       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11836     }
11837
11838     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11839                       false, 0);
11840
11841     // Get the offset of start of .tls section
11842     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11843                                              GA->getValueType(0),
11844                                              GA->getOffset(), X86II::MO_SECREL);
11845     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11846
11847     // The address of the thread local variable is the add of the thread
11848     // pointer with the offset of the variable.
11849     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11850   }
11851
11852   llvm_unreachable("TLS not implemented for this target.");
11853 }
11854
11855 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11856 /// and take a 2 x i32 value to shift plus a shift amount.
11857 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11858   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11859   MVT VT = Op.getSimpleValueType();
11860   unsigned VTBits = VT.getSizeInBits();
11861   SDLoc dl(Op);
11862   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11863   SDValue ShOpLo = Op.getOperand(0);
11864   SDValue ShOpHi = Op.getOperand(1);
11865   SDValue ShAmt  = Op.getOperand(2);
11866   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11867   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11868   // during isel.
11869   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11870                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11871   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11872                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11873                        : DAG.getConstant(0, dl, VT);
11874
11875   SDValue Tmp2, Tmp3;
11876   if (Op.getOpcode() == ISD::SHL_PARTS) {
11877     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11878     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11879   } else {
11880     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11881     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11882   }
11883
11884   // If the shift amount is larger or equal than the width of a part we can't
11885   // rely on the results of shld/shrd. Insert a test and select the appropriate
11886   // values for large shift amounts.
11887   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11888                                 DAG.getConstant(VTBits, dl, MVT::i8));
11889   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11890                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11891
11892   SDValue Hi, Lo;
11893   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11894   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11895   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11896
11897   if (Op.getOpcode() == ISD::SHL_PARTS) {
11898     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11899     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11900   } else {
11901     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11902     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11903   }
11904
11905   SDValue Ops[2] = { Lo, Hi };
11906   return DAG.getMergeValues(Ops, dl);
11907 }
11908
11909 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11910                                            SelectionDAG &DAG) const {
11911   SDValue Src = Op.getOperand(0);
11912   MVT SrcVT = Src.getSimpleValueType();
11913   MVT VT = Op.getSimpleValueType();
11914   SDLoc dl(Op);
11915
11916   if (SrcVT.isVector()) {
11917     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11918       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11919                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11920                          DAG.getUNDEF(SrcVT)));
11921     }
11922     if (SrcVT.getVectorElementType() == MVT::i1) {
11923       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11924       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11925                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11926     }
11927     return SDValue();
11928   }
11929
11930   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11931          "Unknown SINT_TO_FP to lower!");
11932
11933   // These are really Legal; return the operand so the caller accepts it as
11934   // Legal.
11935   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11936     return Op;
11937   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11938       Subtarget->is64Bit()) {
11939     return Op;
11940   }
11941
11942   unsigned Size = SrcVT.getSizeInBits()/8;
11943   MachineFunction &MF = DAG.getMachineFunction();
11944   auto PtrVT = getPointerTy(MF.getDataLayout());
11945   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11946   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11947   SDValue Chain = DAG.getStore(
11948       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
11949       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
11950       false, 0);
11951   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11952 }
11953
11954 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11955                                      SDValue StackSlot,
11956                                      SelectionDAG &DAG) const {
11957   // Build the FILD
11958   SDLoc DL(Op);
11959   SDVTList Tys;
11960   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11961   if (useSSE)
11962     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11963   else
11964     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11965
11966   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11967
11968   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11969   MachineMemOperand *MMO;
11970   if (FI) {
11971     int SSFI = FI->getIndex();
11972     MMO = DAG.getMachineFunction().getMachineMemOperand(
11973         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11974         MachineMemOperand::MOLoad, ByteSize, ByteSize);
11975   } else {
11976     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11977     StackSlot = StackSlot.getOperand(1);
11978   }
11979   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11980   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11981                                            X86ISD::FILD, DL,
11982                                            Tys, Ops, SrcVT, MMO);
11983
11984   if (useSSE) {
11985     Chain = Result.getValue(1);
11986     SDValue InFlag = Result.getValue(2);
11987
11988     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11989     // shouldn't be necessary except that RFP cannot be live across
11990     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11991     MachineFunction &MF = DAG.getMachineFunction();
11992     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11993     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11994     auto PtrVT = getPointerTy(MF.getDataLayout());
11995     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11996     Tys = DAG.getVTList(MVT::Other);
11997     SDValue Ops[] = {
11998       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11999     };
12000     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12001         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12002         MachineMemOperand::MOStore, SSFISize, SSFISize);
12003
12004     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12005                                     Ops, Op.getValueType(), MMO);
12006     Result = DAG.getLoad(
12007         Op.getValueType(), DL, Chain, StackSlot,
12008         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12009         false, false, false, 0);
12010   }
12011
12012   return Result;
12013 }
12014
12015 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12016 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12017                                                SelectionDAG &DAG) const {
12018   // This algorithm is not obvious. Here it is what we're trying to output:
12019   /*
12020      movq       %rax,  %xmm0
12021      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12022      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12023      #ifdef __SSE3__
12024        haddpd   %xmm0, %xmm0
12025      #else
12026        pshufd   $0x4e, %xmm0, %xmm1
12027        addpd    %xmm1, %xmm0
12028      #endif
12029   */
12030
12031   SDLoc dl(Op);
12032   LLVMContext *Context = DAG.getContext();
12033
12034   // Build some magic constants.
12035   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12036   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12037   auto PtrVT = getPointerTy(DAG.getDataLayout());
12038   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12039
12040   SmallVector<Constant*,2> CV1;
12041   CV1.push_back(
12042     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12043                                       APInt(64, 0x4330000000000000ULL))));
12044   CV1.push_back(
12045     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12046                                       APInt(64, 0x4530000000000000ULL))));
12047   Constant *C1 = ConstantVector::get(CV1);
12048   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12049
12050   // Load the 64-bit value into an XMM register.
12051   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12052                             Op.getOperand(0));
12053   SDValue CLod0 =
12054       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12055                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12056                   false, false, false, 16);
12057   SDValue Unpck1 =
12058       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12059
12060   SDValue CLod1 =
12061       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12062                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12063                   false, false, false, 16);
12064   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12065   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12066   SDValue Result;
12067
12068   if (Subtarget->hasSSE3()) {
12069     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12070     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12071   } else {
12072     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12073     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12074                                            S2F, 0x4E, DAG);
12075     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12076                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12077   }
12078
12079   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12080                      DAG.getIntPtrConstant(0, dl));
12081 }
12082
12083 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12084 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12085                                                SelectionDAG &DAG) const {
12086   SDLoc dl(Op);
12087   // FP constant to bias correct the final result.
12088   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12089                                    MVT::f64);
12090
12091   // Load the 32-bit value into an XMM register.
12092   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12093                              Op.getOperand(0));
12094
12095   // Zero out the upper parts of the register.
12096   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12097
12098   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12099                      DAG.getBitcast(MVT::v2f64, Load),
12100                      DAG.getIntPtrConstant(0, dl));
12101
12102   // Or the load with the bias.
12103   SDValue Or = DAG.getNode(
12104       ISD::OR, dl, MVT::v2i64,
12105       DAG.getBitcast(MVT::v2i64,
12106                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12107       DAG.getBitcast(MVT::v2i64,
12108                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12109   Or =
12110       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12111                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12112
12113   // Subtract the bias.
12114   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12115
12116   // Handle final rounding.
12117   EVT DestVT = Op.getValueType();
12118
12119   if (DestVT.bitsLT(MVT::f64))
12120     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12121                        DAG.getIntPtrConstant(0, dl));
12122   if (DestVT.bitsGT(MVT::f64))
12123     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12124
12125   // Handle final rounding.
12126   return Sub;
12127 }
12128
12129 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12130                                      const X86Subtarget &Subtarget) {
12131   // The algorithm is the following:
12132   // #ifdef __SSE4_1__
12133   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12134   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12135   //                                 (uint4) 0x53000000, 0xaa);
12136   // #else
12137   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12138   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12139   // #endif
12140   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12141   //     return (float4) lo + fhi;
12142
12143   SDLoc DL(Op);
12144   SDValue V = Op->getOperand(0);
12145   EVT VecIntVT = V.getValueType();
12146   bool Is128 = VecIntVT == MVT::v4i32;
12147   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12148   // If we convert to something else than the supported type, e.g., to v4f64,
12149   // abort early.
12150   if (VecFloatVT != Op->getValueType(0))
12151     return SDValue();
12152
12153   unsigned NumElts = VecIntVT.getVectorNumElements();
12154   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12155          "Unsupported custom type");
12156   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12157
12158   // In the #idef/#else code, we have in common:
12159   // - The vector of constants:
12160   // -- 0x4b000000
12161   // -- 0x53000000
12162   // - A shift:
12163   // -- v >> 16
12164
12165   // Create the splat vector for 0x4b000000.
12166   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12167   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12168                            CstLow, CstLow, CstLow, CstLow};
12169   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12170                                   makeArrayRef(&CstLowArray[0], NumElts));
12171   // Create the splat vector for 0x53000000.
12172   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12173   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12174                             CstHigh, CstHigh, CstHigh, CstHigh};
12175   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12176                                    makeArrayRef(&CstHighArray[0], NumElts));
12177
12178   // Create the right shift.
12179   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12180   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12181                              CstShift, CstShift, CstShift, CstShift};
12182   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12183                                     makeArrayRef(&CstShiftArray[0], NumElts));
12184   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12185
12186   SDValue Low, High;
12187   if (Subtarget.hasSSE41()) {
12188     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12189     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12190     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12191     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12192     // Low will be bitcasted right away, so do not bother bitcasting back to its
12193     // original type.
12194     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12195                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12196     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12197     //                                 (uint4) 0x53000000, 0xaa);
12198     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12199     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12200     // High will be bitcasted right away, so do not bother bitcasting back to
12201     // its original type.
12202     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12203                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12204   } else {
12205     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12206     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12207                                      CstMask, CstMask, CstMask);
12208     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12209     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12210     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12211
12212     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12213     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12214   }
12215
12216   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12217   SDValue CstFAdd = DAG.getConstantFP(
12218       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12219   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12220                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12221   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12222                                    makeArrayRef(&CstFAddArray[0], NumElts));
12223
12224   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12225   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12226   SDValue FHigh =
12227       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12228   //     return (float4) lo + fhi;
12229   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12230   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12231 }
12232
12233 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12234                                                SelectionDAG &DAG) const {
12235   SDValue N0 = Op.getOperand(0);
12236   MVT SVT = N0.getSimpleValueType();
12237   SDLoc dl(Op);
12238
12239   switch (SVT.SimpleTy) {
12240   default:
12241     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12242   case MVT::v4i8:
12243   case MVT::v4i16:
12244   case MVT::v8i8:
12245   case MVT::v8i16: {
12246     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12247     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12248                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12249   }
12250   case MVT::v4i32:
12251   case MVT::v8i32:
12252     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12253   case MVT::v16i8:
12254   case MVT::v16i16:
12255     if (Subtarget->hasAVX512())
12256       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12257                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12258   }
12259   llvm_unreachable(nullptr);
12260 }
12261
12262 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12263                                            SelectionDAG &DAG) const {
12264   SDValue N0 = Op.getOperand(0);
12265   SDLoc dl(Op);
12266   auto PtrVT = getPointerTy(DAG.getDataLayout());
12267
12268   if (Op.getValueType().isVector())
12269     return lowerUINT_TO_FP_vec(Op, DAG);
12270
12271   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12272   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12273   // the optimization here.
12274   if (DAG.SignBitIsZero(N0))
12275     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12276
12277   MVT SrcVT = N0.getSimpleValueType();
12278   MVT DstVT = Op.getSimpleValueType();
12279   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12280     return LowerUINT_TO_FP_i64(Op, DAG);
12281   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12282     return LowerUINT_TO_FP_i32(Op, DAG);
12283   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12284     return SDValue();
12285
12286   // Make a 64-bit buffer, and use it to build an FILD.
12287   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12288   if (SrcVT == MVT::i32) {
12289     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12290     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12291     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12292                                   StackSlot, MachinePointerInfo(),
12293                                   false, false, 0);
12294     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12295                                   OffsetSlot, MachinePointerInfo(),
12296                                   false, false, 0);
12297     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12298     return Fild;
12299   }
12300
12301   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12302   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12303                                StackSlot, MachinePointerInfo(),
12304                                false, false, 0);
12305   // For i64 source, we need to add the appropriate power of 2 if the input
12306   // was negative.  This is the same as the optimization in
12307   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12308   // we must be careful to do the computation in x87 extended precision, not
12309   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12310   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12311   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12312       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12313       MachineMemOperand::MOLoad, 8, 8);
12314
12315   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12316   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12317   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12318                                          MVT::i64, MMO);
12319
12320   APInt FF(32, 0x5F800000ULL);
12321
12322   // Check whether the sign bit is set.
12323   SDValue SignSet = DAG.getSetCC(
12324       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12325       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12326
12327   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12328   SDValue FudgePtr = DAG.getConstantPool(
12329       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12330
12331   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12332   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12333   SDValue Four = DAG.getIntPtrConstant(4, dl);
12334   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12335                                Zero, Four);
12336   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12337
12338   // Load the value out, extending it from f32 to f80.
12339   // FIXME: Avoid the extend by constructing the right constant pool?
12340   SDValue Fudge = DAG.getExtLoad(
12341       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12342       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12343       false, false, false, 4);
12344   // Extend everything to 80 bits to force it to be done on x87.
12345   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12346   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12347                      DAG.getIntPtrConstant(0, dl));
12348 }
12349
12350 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12351 // is legal, or has an f16 source (which needs to be promoted to f32),
12352 // just return an <SDValue(), SDValue()> pair.
12353 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12354 // to i16, i32 or i64, and we lower it to a legal sequence.
12355 // If lowered to the final integer result we return a <result, SDValue()> pair.
12356 // Otherwise we lower it to a sequence ending with a FIST, return a
12357 // <FIST, StackSlot> pair, and the caller is responsible for loading
12358 // the final integer result from StackSlot.
12359 std::pair<SDValue,SDValue>
12360 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12361                                    bool IsSigned, bool IsReplace) const {
12362   SDLoc DL(Op);
12363
12364   EVT DstTy = Op.getValueType();
12365   EVT TheVT = Op.getOperand(0).getValueType();
12366   auto PtrVT = getPointerTy(DAG.getDataLayout());
12367
12368   if (TheVT == MVT::f16)
12369     // We need to promote the f16 to f32 before using the lowering
12370     // in this routine.
12371     return std::make_pair(SDValue(), SDValue());
12372
12373   assert((TheVT == MVT::f32 ||
12374           TheVT == MVT::f64 ||
12375           TheVT == MVT::f80) &&
12376          "Unexpected FP operand type in FP_TO_INTHelper");
12377
12378   // If using FIST to compute an unsigned i64, we'll need some fixup
12379   // to handle values above the maximum signed i64.  A FIST is always
12380   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12381   bool UnsignedFixup = !IsSigned &&
12382                        DstTy == MVT::i64 &&
12383                        (!Subtarget->is64Bit() ||
12384                         !isScalarFPTypeInSSEReg(TheVT));
12385
12386   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12387     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12388     // The low 32 bits of the fist result will have the correct uint32 result.
12389     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12390     DstTy = MVT::i64;
12391   }
12392
12393   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12394          DstTy.getSimpleVT() >= MVT::i16 &&
12395          "Unknown FP_TO_INT to lower!");
12396
12397   // These are really Legal.
12398   if (DstTy == MVT::i32 &&
12399       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12400     return std::make_pair(SDValue(), SDValue());
12401   if (Subtarget->is64Bit() &&
12402       DstTy == MVT::i64 &&
12403       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12404     return std::make_pair(SDValue(), SDValue());
12405
12406   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12407   // stack slot.
12408   MachineFunction &MF = DAG.getMachineFunction();
12409   unsigned MemSize = DstTy.getSizeInBits()/8;
12410   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12411   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12412
12413   unsigned Opc;
12414   switch (DstTy.getSimpleVT().SimpleTy) {
12415   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12416   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12417   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12418   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12419   }
12420
12421   SDValue Chain = DAG.getEntryNode();
12422   SDValue Value = Op.getOperand(0);
12423   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12424
12425   if (UnsignedFixup) {
12426     //
12427     // Conversion to unsigned i64 is implemented with a select,
12428     // depending on whether the source value fits in the range
12429     // of a signed i64.  Let Thresh be the FP equivalent of
12430     // 0x8000000000000000ULL.
12431     //
12432     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12433     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12434     //  Fist-to-mem64 FistSrc
12435     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12436     //  to XOR'ing the high 32 bits with Adjust.
12437     //
12438     // Being a power of 2, Thresh is exactly representable in all FP formats.
12439     // For X87 we'd like to use the smallest FP type for this constant, but
12440     // for DAG type consistency we have to match the FP operand type.
12441
12442     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12443     APFloat::opStatus Status = APFloat::opOK;
12444     bool LosesInfo = false;
12445     if (TheVT == MVT::f64)
12446       // The rounding mode is irrelevant as the conversion should be exact.
12447       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12448                               &LosesInfo);
12449     else if (TheVT == MVT::f80)
12450       Status = Thresh.convert(APFloat::x87DoubleExtended,
12451                               APFloat::rmNearestTiesToEven, &LosesInfo);
12452
12453     assert(Status == APFloat::opOK && !LosesInfo &&
12454            "FP conversion should have been exact");
12455
12456     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12457
12458     SDValue Cmp = DAG.getSetCC(DL,
12459                                getSetCCResultType(DAG.getDataLayout(),
12460                                                   *DAG.getContext(), TheVT),
12461                                Value, ThreshVal, ISD::SETLT);
12462     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12463                            DAG.getConstant(0, DL, MVT::i32),
12464                            DAG.getConstant(0x80000000, DL, MVT::i32));
12465     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12466     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12467                                               *DAG.getContext(), TheVT),
12468                        Value, ThreshVal, ISD::SETLT);
12469     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12470   }
12471
12472   // FIXME This causes a redundant load/store if the SSE-class value is already
12473   // in memory, such as if it is on the callstack.
12474   if (isScalarFPTypeInSSEReg(TheVT)) {
12475     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12476     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12477                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12478                          false, 0);
12479     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12480     SDValue Ops[] = {
12481       Chain, StackSlot, DAG.getValueType(TheVT)
12482     };
12483
12484     MachineMemOperand *MMO =
12485         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12486                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12487     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12488     Chain = Value.getValue(1);
12489     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12490     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12491   }
12492
12493   MachineMemOperand *MMO =
12494       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12495                               MachineMemOperand::MOStore, MemSize, MemSize);
12496
12497   if (UnsignedFixup) {
12498
12499     // Insert the FIST, load its result as two i32's,
12500     // and XOR the high i32 with Adjust.
12501
12502     SDValue FistOps[] = { Chain, Value, StackSlot };
12503     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12504                                            FistOps, DstTy, MMO);
12505
12506     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12507                                 MachinePointerInfo(),
12508                                 false, false, false, 0);
12509     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12510                                    DAG.getConstant(4, DL, PtrVT));
12511
12512     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12513                                  MachinePointerInfo(),
12514                                  false, false, false, 0);
12515     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12516
12517     if (Subtarget->is64Bit()) {
12518       // Join High32 and Low32 into a 64-bit result.
12519       // (High32 << 32) | Low32
12520       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12521       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12522       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12523                            DAG.getConstant(32, DL, MVT::i8));
12524       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12525       return std::make_pair(Result, SDValue());
12526     }
12527
12528     SDValue ResultOps[] = { Low32, High32 };
12529
12530     SDValue pair = IsReplace
12531       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12532       : DAG.getMergeValues(ResultOps, DL);
12533     return std::make_pair(pair, SDValue());
12534   } else {
12535     // Build the FP_TO_INT*_IN_MEM
12536     SDValue Ops[] = { Chain, Value, StackSlot };
12537     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12538                                            Ops, DstTy, MMO);
12539     return std::make_pair(FIST, StackSlot);
12540   }
12541 }
12542
12543 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12544                               const X86Subtarget *Subtarget) {
12545   MVT VT = Op->getSimpleValueType(0);
12546   SDValue In = Op->getOperand(0);
12547   MVT InVT = In.getSimpleValueType();
12548   SDLoc dl(Op);
12549
12550   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12551     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12552
12553   // Optimize vectors in AVX mode:
12554   //
12555   //   v8i16 -> v8i32
12556   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12557   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12558   //   Concat upper and lower parts.
12559   //
12560   //   v4i32 -> v4i64
12561   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12562   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12563   //   Concat upper and lower parts.
12564   //
12565
12566   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12567       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12568       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12569     return SDValue();
12570
12571   if (Subtarget->hasInt256())
12572     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12573
12574   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12575   SDValue Undef = DAG.getUNDEF(InVT);
12576   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12577   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12578   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12579
12580   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12581                              VT.getVectorNumElements()/2);
12582
12583   OpLo = DAG.getBitcast(HVT, OpLo);
12584   OpHi = DAG.getBitcast(HVT, OpHi);
12585
12586   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12587 }
12588
12589 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12590                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12591   MVT VT = Op->getSimpleValueType(0);
12592   SDValue In = Op->getOperand(0);
12593   MVT InVT = In.getSimpleValueType();
12594   SDLoc DL(Op);
12595   unsigned int NumElts = VT.getVectorNumElements();
12596   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12597     return SDValue();
12598
12599   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12600     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12601
12602   assert(InVT.getVectorElementType() == MVT::i1);
12603   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12604   SDValue One =
12605    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12606   SDValue Zero =
12607    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12608
12609   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12610   if (VT.is512BitVector())
12611     return V;
12612   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12613 }
12614
12615 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12616                                SelectionDAG &DAG) {
12617   if (Subtarget->hasFp256())
12618     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12619       return Res;
12620
12621   return SDValue();
12622 }
12623
12624 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12625                                 SelectionDAG &DAG) {
12626   SDLoc DL(Op);
12627   MVT VT = Op.getSimpleValueType();
12628   SDValue In = Op.getOperand(0);
12629   MVT SVT = In.getSimpleValueType();
12630
12631   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12632     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12633
12634   if (Subtarget->hasFp256())
12635     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12636       return Res;
12637
12638   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12639          VT.getVectorNumElements() != SVT.getVectorNumElements());
12640   return SDValue();
12641 }
12642
12643 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12644   SDLoc DL(Op);
12645   MVT VT = Op.getSimpleValueType();
12646   SDValue In = Op.getOperand(0);
12647   MVT InVT = In.getSimpleValueType();
12648
12649   if (VT == MVT::i1) {
12650     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12651            "Invalid scalar TRUNCATE operation");
12652     if (InVT.getSizeInBits() >= 32)
12653       return SDValue();
12654     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12655     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12656   }
12657   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12658          "Invalid TRUNCATE operation");
12659
12660   // move vector to mask - truncate solution for SKX
12661   if (VT.getVectorElementType() == MVT::i1) {
12662     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12663         Subtarget->hasBWI())
12664       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12665     if ((InVT.is256BitVector() || InVT.is128BitVector())
12666         && InVT.getScalarSizeInBits() <= 16 &&
12667         Subtarget->hasBWI() && Subtarget->hasVLX())
12668       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12669     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12670         Subtarget->hasDQI())
12671       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12672     if ((InVT.is256BitVector() || InVT.is128BitVector())
12673         && InVT.getScalarSizeInBits() >= 32 &&
12674         Subtarget->hasDQI() && Subtarget->hasVLX())
12675       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12676   }
12677
12678   if (VT.getVectorElementType() == MVT::i1) {
12679     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12680     unsigned NumElts = InVT.getVectorNumElements();
12681     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12682     if (InVT.getSizeInBits() < 512) {
12683       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12684       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12685       InVT = ExtVT;
12686     }
12687
12688     SDValue OneV =
12689      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12690     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12691     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12692   }
12693
12694   // vpmovqb/w/d, vpmovdb/w, vpmovwb
12695   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12696       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12697     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12698
12699   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12700     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12701     if (Subtarget->hasInt256()) {
12702       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12703       In = DAG.getBitcast(MVT::v8i32, In);
12704       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12705                                 ShufMask);
12706       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12707                          DAG.getIntPtrConstant(0, DL));
12708     }
12709
12710     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12711                                DAG.getIntPtrConstant(0, DL));
12712     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12713                                DAG.getIntPtrConstant(2, DL));
12714     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12715     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12716     static const int ShufMask[] = {0, 2, 4, 6};
12717     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12718   }
12719
12720   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12721     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12722     if (Subtarget->hasInt256()) {
12723       In = DAG.getBitcast(MVT::v32i8, In);
12724
12725       SmallVector<SDValue,32> pshufbMask;
12726       for (unsigned i = 0; i < 2; ++i) {
12727         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12728         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12729         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12730         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12731         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12732         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12733         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12734         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12735         for (unsigned j = 0; j < 8; ++j)
12736           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12737       }
12738       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12739       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12740       In = DAG.getBitcast(MVT::v4i64, In);
12741
12742       static const int ShufMask[] = {0,  2,  -1,  -1};
12743       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12744                                 &ShufMask[0]);
12745       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12746                        DAG.getIntPtrConstant(0, DL));
12747       return DAG.getBitcast(VT, In);
12748     }
12749
12750     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12751                                DAG.getIntPtrConstant(0, DL));
12752
12753     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12754                                DAG.getIntPtrConstant(4, DL));
12755
12756     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12757     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12758
12759     // The PSHUFB mask:
12760     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12761                                    -1, -1, -1, -1, -1, -1, -1, -1};
12762
12763     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12764     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12765     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12766
12767     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12768     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12769
12770     // The MOVLHPS Mask:
12771     static const int ShufMask2[] = {0, 1, 4, 5};
12772     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12773     return DAG.getBitcast(MVT::v8i16, res);
12774   }
12775
12776   // Handle truncation of V256 to V128 using shuffles.
12777   if (!VT.is128BitVector() || !InVT.is256BitVector())
12778     return SDValue();
12779
12780   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12781
12782   unsigned NumElems = VT.getVectorNumElements();
12783   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12784
12785   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12786   // Prepare truncation shuffle mask
12787   for (unsigned i = 0; i != NumElems; ++i)
12788     MaskVec[i] = i * 2;
12789   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12790                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12791   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12792                      DAG.getIntPtrConstant(0, DL));
12793 }
12794
12795 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12796                                            SelectionDAG &DAG) const {
12797   assert(!Op.getSimpleValueType().isVector());
12798
12799   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12800     /*IsSigned=*/ true, /*IsReplace=*/ false);
12801   SDValue FIST = Vals.first, StackSlot = Vals.second;
12802   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12803   if (!FIST.getNode())
12804     return Op;
12805
12806   if (StackSlot.getNode())
12807     // Load the result.
12808     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12809                        FIST, StackSlot, MachinePointerInfo(),
12810                        false, false, false, 0);
12811
12812   // The node is the result.
12813   return FIST;
12814 }
12815
12816 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12817                                            SelectionDAG &DAG) const {
12818   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12819     /*IsSigned=*/ false, /*IsReplace=*/ false);
12820   SDValue FIST = Vals.first, StackSlot = Vals.second;
12821   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12822   if (!FIST.getNode())
12823     return Op;
12824
12825   if (StackSlot.getNode())
12826     // Load the result.
12827     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12828                        FIST, StackSlot, MachinePointerInfo(),
12829                        false, false, false, 0);
12830
12831   // The node is the result.
12832   return FIST;
12833 }
12834
12835 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12836   SDLoc DL(Op);
12837   MVT VT = Op.getSimpleValueType();
12838   SDValue In = Op.getOperand(0);
12839   MVT SVT = In.getSimpleValueType();
12840
12841   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12842
12843   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12844                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12845                                  In, DAG.getUNDEF(SVT)));
12846 }
12847
12848 /// The only differences between FABS and FNEG are the mask and the logic op.
12849 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12850 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12851   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12852          "Wrong opcode for lowering FABS or FNEG.");
12853
12854   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12855
12856   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12857   // into an FNABS. We'll lower the FABS after that if it is still in use.
12858   if (IsFABS)
12859     for (SDNode *User : Op->uses())
12860       if (User->getOpcode() == ISD::FNEG)
12861         return Op;
12862
12863   SDLoc dl(Op);
12864   MVT VT = Op.getSimpleValueType();
12865
12866   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12867   // decide if we should generate a 16-byte constant mask when we only need 4 or
12868   // 8 bytes for the scalar case.
12869
12870   MVT LogicVT;
12871   MVT EltVT;
12872   unsigned NumElts;
12873
12874   if (VT.isVector()) {
12875     LogicVT = VT;
12876     EltVT = VT.getVectorElementType();
12877     NumElts = VT.getVectorNumElements();
12878   } else {
12879     // There are no scalar bitwise logical SSE/AVX instructions, so we
12880     // generate a 16-byte vector constant and logic op even for the scalar case.
12881     // Using a 16-byte mask allows folding the load of the mask with
12882     // the logic op, so it can save (~4 bytes) on code size.
12883     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12884     EltVT = VT;
12885     NumElts = (VT == MVT::f64) ? 2 : 4;
12886   }
12887
12888   unsigned EltBits = EltVT.getSizeInBits();
12889   LLVMContext *Context = DAG.getContext();
12890   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12891   APInt MaskElt =
12892     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12893   Constant *C = ConstantInt::get(*Context, MaskElt);
12894   C = ConstantVector::getSplat(NumElts, C);
12895   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12896   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12897   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12898   SDValue Mask =
12899       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12900                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12901                   false, false, false, Alignment);
12902
12903   SDValue Op0 = Op.getOperand(0);
12904   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12905   unsigned LogicOp =
12906     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12907   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12908
12909   if (VT.isVector())
12910     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12911
12912   // For the scalar case extend to a 128-bit vector, perform the logic op,
12913   // and extract the scalar result back out.
12914   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
12915   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12916   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
12917                      DAG.getIntPtrConstant(0, dl));
12918 }
12919
12920 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12921   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12922   LLVMContext *Context = DAG.getContext();
12923   SDValue Op0 = Op.getOperand(0);
12924   SDValue Op1 = Op.getOperand(1);
12925   SDLoc dl(Op);
12926   MVT VT = Op.getSimpleValueType();
12927   MVT SrcVT = Op1.getSimpleValueType();
12928
12929   // If second operand is smaller, extend it first.
12930   if (SrcVT.bitsLT(VT)) {
12931     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12932     SrcVT = VT;
12933   }
12934   // And if it is bigger, shrink it first.
12935   if (SrcVT.bitsGT(VT)) {
12936     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12937     SrcVT = VT;
12938   }
12939
12940   // At this point the operands and the result should have the same
12941   // type, and that won't be f80 since that is not custom lowered.
12942
12943   const fltSemantics &Sem =
12944       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12945   const unsigned SizeInBits = VT.getSizeInBits();
12946
12947   SmallVector<Constant *, 4> CV(
12948       VT == MVT::f64 ? 2 : 4,
12949       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12950
12951   // First, clear all bits but the sign bit from the second operand (sign).
12952   CV[0] = ConstantFP::get(*Context,
12953                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12954   Constant *C = ConstantVector::get(CV);
12955   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12956   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12957
12958   // Perform all logic operations as 16-byte vectors because there are no
12959   // scalar FP logic instructions in SSE. This allows load folding of the
12960   // constants into the logic instructions.
12961   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12962   SDValue Mask1 =
12963       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12964                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12965                   false, false, false, 16);
12966   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
12967   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
12968
12969   // Next, clear the sign bit from the first operand (magnitude).
12970   // If it's a constant, we can clear it here.
12971   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12972     APFloat APF = Op0CN->getValueAPF();
12973     // If the magnitude is a positive zero, the sign bit alone is enough.
12974     if (APF.isPosZero())
12975       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
12976                          DAG.getIntPtrConstant(0, dl));
12977     APF.clearSign();
12978     CV[0] = ConstantFP::get(*Context, APF);
12979   } else {
12980     CV[0] = ConstantFP::get(
12981         *Context,
12982         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12983   }
12984   C = ConstantVector::get(CV);
12985   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12986   SDValue Val =
12987       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12988                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12989                   false, false, false, 16);
12990   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12991   if (!isa<ConstantFPSDNode>(Op0)) {
12992     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
12993     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
12994   }
12995   // OR the magnitude value with the sign bit.
12996   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
12997   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
12998                      DAG.getIntPtrConstant(0, dl));
12999 }
13000
13001 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13002   SDValue N0 = Op.getOperand(0);
13003   SDLoc dl(Op);
13004   MVT VT = Op.getSimpleValueType();
13005
13006   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13007   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13008                                   DAG.getConstant(1, dl, VT));
13009   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13010 }
13011
13012 // Check whether an OR'd tree is PTEST-able.
13013 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13014                                       SelectionDAG &DAG) {
13015   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13016
13017   if (!Subtarget->hasSSE41())
13018     return SDValue();
13019
13020   if (!Op->hasOneUse())
13021     return SDValue();
13022
13023   SDNode *N = Op.getNode();
13024   SDLoc DL(N);
13025
13026   SmallVector<SDValue, 8> Opnds;
13027   DenseMap<SDValue, unsigned> VecInMap;
13028   SmallVector<SDValue, 8> VecIns;
13029   EVT VT = MVT::Other;
13030
13031   // Recognize a special case where a vector is casted into wide integer to
13032   // test all 0s.
13033   Opnds.push_back(N->getOperand(0));
13034   Opnds.push_back(N->getOperand(1));
13035
13036   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13037     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13038     // BFS traverse all OR'd operands.
13039     if (I->getOpcode() == ISD::OR) {
13040       Opnds.push_back(I->getOperand(0));
13041       Opnds.push_back(I->getOperand(1));
13042       // Re-evaluate the number of nodes to be traversed.
13043       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13044       continue;
13045     }
13046
13047     // Quit if a non-EXTRACT_VECTOR_ELT
13048     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13049       return SDValue();
13050
13051     // Quit if without a constant index.
13052     SDValue Idx = I->getOperand(1);
13053     if (!isa<ConstantSDNode>(Idx))
13054       return SDValue();
13055
13056     SDValue ExtractedFromVec = I->getOperand(0);
13057     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13058     if (M == VecInMap.end()) {
13059       VT = ExtractedFromVec.getValueType();
13060       // Quit if not 128/256-bit vector.
13061       if (!VT.is128BitVector() && !VT.is256BitVector())
13062         return SDValue();
13063       // Quit if not the same type.
13064       if (VecInMap.begin() != VecInMap.end() &&
13065           VT != VecInMap.begin()->first.getValueType())
13066         return SDValue();
13067       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13068       VecIns.push_back(ExtractedFromVec);
13069     }
13070     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13071   }
13072
13073   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13074          "Not extracted from 128-/256-bit vector.");
13075
13076   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13077
13078   for (DenseMap<SDValue, unsigned>::const_iterator
13079         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13080     // Quit if not all elements are used.
13081     if (I->second != FullMask)
13082       return SDValue();
13083   }
13084
13085   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13086
13087   // Cast all vectors into TestVT for PTEST.
13088   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13089     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13090
13091   // If more than one full vectors are evaluated, OR them first before PTEST.
13092   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13093     // Each iteration will OR 2 nodes and append the result until there is only
13094     // 1 node left, i.e. the final OR'd value of all vectors.
13095     SDValue LHS = VecIns[Slot];
13096     SDValue RHS = VecIns[Slot + 1];
13097     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13098   }
13099
13100   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13101                      VecIns.back(), VecIns.back());
13102 }
13103
13104 /// \brief return true if \c Op has a use that doesn't just read flags.
13105 static bool hasNonFlagsUse(SDValue Op) {
13106   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13107        ++UI) {
13108     SDNode *User = *UI;
13109     unsigned UOpNo = UI.getOperandNo();
13110     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13111       // Look pass truncate.
13112       UOpNo = User->use_begin().getOperandNo();
13113       User = *User->use_begin();
13114     }
13115
13116     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13117         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13118       return true;
13119   }
13120   return false;
13121 }
13122
13123 /// Emit nodes that will be selected as "test Op0,Op0", or something
13124 /// equivalent.
13125 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13126                                     SelectionDAG &DAG) const {
13127   if (Op.getValueType() == MVT::i1) {
13128     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13129     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13130                        DAG.getConstant(0, dl, MVT::i8));
13131   }
13132   // CF and OF aren't always set the way we want. Determine which
13133   // of these we need.
13134   bool NeedCF = false;
13135   bool NeedOF = false;
13136   switch (X86CC) {
13137   default: break;
13138   case X86::COND_A: case X86::COND_AE:
13139   case X86::COND_B: case X86::COND_BE:
13140     NeedCF = true;
13141     break;
13142   case X86::COND_G: case X86::COND_GE:
13143   case X86::COND_L: case X86::COND_LE:
13144   case X86::COND_O: case X86::COND_NO: {
13145     // Check if we really need to set the
13146     // Overflow flag. If NoSignedWrap is present
13147     // that is not actually needed.
13148     switch (Op->getOpcode()) {
13149     case ISD::ADD:
13150     case ISD::SUB:
13151     case ISD::MUL:
13152     case ISD::SHL: {
13153       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13154       if (BinNode->Flags.hasNoSignedWrap())
13155         break;
13156     }
13157     default:
13158       NeedOF = true;
13159       break;
13160     }
13161     break;
13162   }
13163   }
13164   // See if we can use the EFLAGS value from the operand instead of
13165   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13166   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13167   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13168     // Emit a CMP with 0, which is the TEST pattern.
13169     //if (Op.getValueType() == MVT::i1)
13170     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13171     //                     DAG.getConstant(0, MVT::i1));
13172     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13173                        DAG.getConstant(0, dl, Op.getValueType()));
13174   }
13175   unsigned Opcode = 0;
13176   unsigned NumOperands = 0;
13177
13178   // Truncate operations may prevent the merge of the SETCC instruction
13179   // and the arithmetic instruction before it. Attempt to truncate the operands
13180   // of the arithmetic instruction and use a reduced bit-width instruction.
13181   bool NeedTruncation = false;
13182   SDValue ArithOp = Op;
13183   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13184     SDValue Arith = Op->getOperand(0);
13185     // Both the trunc and the arithmetic op need to have one user each.
13186     if (Arith->hasOneUse())
13187       switch (Arith.getOpcode()) {
13188         default: break;
13189         case ISD::ADD:
13190         case ISD::SUB:
13191         case ISD::AND:
13192         case ISD::OR:
13193         case ISD::XOR: {
13194           NeedTruncation = true;
13195           ArithOp = Arith;
13196         }
13197       }
13198   }
13199
13200   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13201   // which may be the result of a CAST.  We use the variable 'Op', which is the
13202   // non-casted variable when we check for possible users.
13203   switch (ArithOp.getOpcode()) {
13204   case ISD::ADD:
13205     // Due to an isel shortcoming, be conservative if this add is likely to be
13206     // selected as part of a load-modify-store instruction. When the root node
13207     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13208     // uses of other nodes in the match, such as the ADD in this case. This
13209     // leads to the ADD being left around and reselected, with the result being
13210     // two adds in the output.  Alas, even if none our users are stores, that
13211     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13212     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13213     // climbing the DAG back to the root, and it doesn't seem to be worth the
13214     // effort.
13215     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13216          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13217       if (UI->getOpcode() != ISD::CopyToReg &&
13218           UI->getOpcode() != ISD::SETCC &&
13219           UI->getOpcode() != ISD::STORE)
13220         goto default_case;
13221
13222     if (ConstantSDNode *C =
13223         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13224       // An add of one will be selected as an INC.
13225       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13226         Opcode = X86ISD::INC;
13227         NumOperands = 1;
13228         break;
13229       }
13230
13231       // An add of negative one (subtract of one) will be selected as a DEC.
13232       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13233         Opcode = X86ISD::DEC;
13234         NumOperands = 1;
13235         break;
13236       }
13237     }
13238
13239     // Otherwise use a regular EFLAGS-setting add.
13240     Opcode = X86ISD::ADD;
13241     NumOperands = 2;
13242     break;
13243   case ISD::SHL:
13244   case ISD::SRL:
13245     // If we have a constant logical shift that's only used in a comparison
13246     // against zero turn it into an equivalent AND. This allows turning it into
13247     // a TEST instruction later.
13248     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13249         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13250       EVT VT = Op.getValueType();
13251       unsigned BitWidth = VT.getSizeInBits();
13252       unsigned ShAmt = Op->getConstantOperandVal(1);
13253       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13254         break;
13255       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13256                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13257                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13258       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13259         break;
13260       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13261                                 DAG.getConstant(Mask, dl, VT));
13262       DAG.ReplaceAllUsesWith(Op, New);
13263       Op = New;
13264     }
13265     break;
13266
13267   case ISD::AND:
13268     // If the primary and result isn't used, don't bother using X86ISD::AND,
13269     // because a TEST instruction will be better.
13270     if (!hasNonFlagsUse(Op))
13271       break;
13272     // FALL THROUGH
13273   case ISD::SUB:
13274   case ISD::OR:
13275   case ISD::XOR:
13276     // Due to the ISEL shortcoming noted above, be conservative if this op is
13277     // likely to be selected as part of a load-modify-store instruction.
13278     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13279            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13280       if (UI->getOpcode() == ISD::STORE)
13281         goto default_case;
13282
13283     // Otherwise use a regular EFLAGS-setting instruction.
13284     switch (ArithOp.getOpcode()) {
13285     default: llvm_unreachable("unexpected operator!");
13286     case ISD::SUB: Opcode = X86ISD::SUB; break;
13287     case ISD::XOR: Opcode = X86ISD::XOR; break;
13288     case ISD::AND: Opcode = X86ISD::AND; break;
13289     case ISD::OR: {
13290       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13291         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13292         if (EFLAGS.getNode())
13293           return EFLAGS;
13294       }
13295       Opcode = X86ISD::OR;
13296       break;
13297     }
13298     }
13299
13300     NumOperands = 2;
13301     break;
13302   case X86ISD::ADD:
13303   case X86ISD::SUB:
13304   case X86ISD::INC:
13305   case X86ISD::DEC:
13306   case X86ISD::OR:
13307   case X86ISD::XOR:
13308   case X86ISD::AND:
13309     return SDValue(Op.getNode(), 1);
13310   default:
13311   default_case:
13312     break;
13313   }
13314
13315   // If we found that truncation is beneficial, perform the truncation and
13316   // update 'Op'.
13317   if (NeedTruncation) {
13318     EVT VT = Op.getValueType();
13319     SDValue WideVal = Op->getOperand(0);
13320     EVT WideVT = WideVal.getValueType();
13321     unsigned ConvertedOp = 0;
13322     // Use a target machine opcode to prevent further DAGCombine
13323     // optimizations that may separate the arithmetic operations
13324     // from the setcc node.
13325     switch (WideVal.getOpcode()) {
13326       default: break;
13327       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13328       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13329       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13330       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13331       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13332     }
13333
13334     if (ConvertedOp) {
13335       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13336       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13337         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13338         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13339         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13340       }
13341     }
13342   }
13343
13344   if (Opcode == 0)
13345     // Emit a CMP with 0, which is the TEST pattern.
13346     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13347                        DAG.getConstant(0, dl, Op.getValueType()));
13348
13349   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13350   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13351
13352   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13353   DAG.ReplaceAllUsesWith(Op, New);
13354   return SDValue(New.getNode(), 1);
13355 }
13356
13357 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13358 /// equivalent.
13359 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13360                                    SDLoc dl, SelectionDAG &DAG) const {
13361   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13362     if (C->getAPIntValue() == 0)
13363       return EmitTest(Op0, X86CC, dl, DAG);
13364
13365      if (Op0.getValueType() == MVT::i1)
13366        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13367   }
13368
13369   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13370        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13371     // Do the comparison at i32 if it's smaller, besides the Atom case.
13372     // This avoids subregister aliasing issues. Keep the smaller reference
13373     // if we're optimizing for size, however, as that'll allow better folding
13374     // of memory operations.
13375     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13376         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13377         !Subtarget->isAtom()) {
13378       unsigned ExtendOp =
13379           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13380       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13381       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13382     }
13383     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13384     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13385     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13386                               Op0, Op1);
13387     return SDValue(Sub.getNode(), 1);
13388   }
13389   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13390 }
13391
13392 /// Convert a comparison if required by the subtarget.
13393 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13394                                                  SelectionDAG &DAG) const {
13395   // If the subtarget does not support the FUCOMI instruction, floating-point
13396   // comparisons have to be converted.
13397   if (Subtarget->hasCMov() ||
13398       Cmp.getOpcode() != X86ISD::CMP ||
13399       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13400       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13401     return Cmp;
13402
13403   // The instruction selector will select an FUCOM instruction instead of
13404   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13405   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13406   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13407   SDLoc dl(Cmp);
13408   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13409   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13410   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13411                             DAG.getConstant(8, dl, MVT::i8));
13412   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13413   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13414 }
13415
13416 /// The minimum architected relative accuracy is 2^-12. We need one
13417 /// Newton-Raphson step to have a good float result (24 bits of precision).
13418 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13419                                             DAGCombinerInfo &DCI,
13420                                             unsigned &RefinementSteps,
13421                                             bool &UseOneConstNR) const {
13422   EVT VT = Op.getValueType();
13423   const char *RecipOp;
13424
13425   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13426   // TODO: Add support for AVX512 (v16f32).
13427   // It is likely not profitable to do this for f64 because a double-precision
13428   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13429   // instructions: convert to single, rsqrtss, convert back to double, refine
13430   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13431   // along with FMA, this could be a throughput win.
13432   if (VT == MVT::f32 && Subtarget->hasSSE1())
13433     RecipOp = "sqrtf";
13434   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13435            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13436     RecipOp = "vec-sqrtf";
13437   else
13438     return SDValue();
13439
13440   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13441   if (!Recips.isEnabled(RecipOp))
13442     return SDValue();
13443
13444   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13445   UseOneConstNR = false;
13446   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13447 }
13448
13449 /// The minimum architected relative accuracy is 2^-12. We need one
13450 /// Newton-Raphson step to have a good float result (24 bits of precision).
13451 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13452                                             DAGCombinerInfo &DCI,
13453                                             unsigned &RefinementSteps) const {
13454   EVT VT = Op.getValueType();
13455   const char *RecipOp;
13456
13457   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13458   // TODO: Add support for AVX512 (v16f32).
13459   // It is likely not profitable to do this for f64 because a double-precision
13460   // reciprocal estimate with refinement on x86 prior to FMA requires
13461   // 15 instructions: convert to single, rcpss, convert back to double, refine
13462   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13463   // along with FMA, this could be a throughput win.
13464   if (VT == MVT::f32 && Subtarget->hasSSE1())
13465     RecipOp = "divf";
13466   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13467            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13468     RecipOp = "vec-divf";
13469   else
13470     return SDValue();
13471
13472   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13473   if (!Recips.isEnabled(RecipOp))
13474     return SDValue();
13475
13476   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13477   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13478 }
13479
13480 /// If we have at least two divisions that use the same divisor, convert to
13481 /// multplication by a reciprocal. This may need to be adjusted for a given
13482 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13483 /// This is because we still need one division to calculate the reciprocal and
13484 /// then we need two multiplies by that reciprocal as replacements for the
13485 /// original divisions.
13486 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13487   return 2;
13488 }
13489
13490 static bool isAllOnes(SDValue V) {
13491   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13492   return C && C->isAllOnesValue();
13493 }
13494
13495 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13496 /// if it's possible.
13497 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13498                                      SDLoc dl, SelectionDAG &DAG) const {
13499   SDValue Op0 = And.getOperand(0);
13500   SDValue Op1 = And.getOperand(1);
13501   if (Op0.getOpcode() == ISD::TRUNCATE)
13502     Op0 = Op0.getOperand(0);
13503   if (Op1.getOpcode() == ISD::TRUNCATE)
13504     Op1 = Op1.getOperand(0);
13505
13506   SDValue LHS, RHS;
13507   if (Op1.getOpcode() == ISD::SHL)
13508     std::swap(Op0, Op1);
13509   if (Op0.getOpcode() == ISD::SHL) {
13510     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13511       if (And00C->getZExtValue() == 1) {
13512         // If we looked past a truncate, check that it's only truncating away
13513         // known zeros.
13514         unsigned BitWidth = Op0.getValueSizeInBits();
13515         unsigned AndBitWidth = And.getValueSizeInBits();
13516         if (BitWidth > AndBitWidth) {
13517           APInt Zeros, Ones;
13518           DAG.computeKnownBits(Op0, Zeros, Ones);
13519           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13520             return SDValue();
13521         }
13522         LHS = Op1;
13523         RHS = Op0.getOperand(1);
13524       }
13525   } else if (Op1.getOpcode() == ISD::Constant) {
13526     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13527     uint64_t AndRHSVal = AndRHS->getZExtValue();
13528     SDValue AndLHS = Op0;
13529
13530     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13531       LHS = AndLHS.getOperand(0);
13532       RHS = AndLHS.getOperand(1);
13533     }
13534
13535     // Use BT if the immediate can't be encoded in a TEST instruction.
13536     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13537       LHS = AndLHS;
13538       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13539     }
13540   }
13541
13542   if (LHS.getNode()) {
13543     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13544     // instruction.  Since the shift amount is in-range-or-undefined, we know
13545     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13546     // the encoding for the i16 version is larger than the i32 version.
13547     // Also promote i16 to i32 for performance / code size reason.
13548     if (LHS.getValueType() == MVT::i8 ||
13549         LHS.getValueType() == MVT::i16)
13550       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13551
13552     // If the operand types disagree, extend the shift amount to match.  Since
13553     // BT ignores high bits (like shifts) we can use anyextend.
13554     if (LHS.getValueType() != RHS.getValueType())
13555       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13556
13557     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13558     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13559     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13560                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13561   }
13562
13563   return SDValue();
13564 }
13565
13566 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13567 /// mask CMPs.
13568 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13569                               SDValue &Op1) {
13570   unsigned SSECC;
13571   bool Swap = false;
13572
13573   // SSE Condition code mapping:
13574   //  0 - EQ
13575   //  1 - LT
13576   //  2 - LE
13577   //  3 - UNORD
13578   //  4 - NEQ
13579   //  5 - NLT
13580   //  6 - NLE
13581   //  7 - ORD
13582   switch (SetCCOpcode) {
13583   default: llvm_unreachable("Unexpected SETCC condition");
13584   case ISD::SETOEQ:
13585   case ISD::SETEQ:  SSECC = 0; break;
13586   case ISD::SETOGT:
13587   case ISD::SETGT:  Swap = true; // Fallthrough
13588   case ISD::SETLT:
13589   case ISD::SETOLT: SSECC = 1; break;
13590   case ISD::SETOGE:
13591   case ISD::SETGE:  Swap = true; // Fallthrough
13592   case ISD::SETLE:
13593   case ISD::SETOLE: SSECC = 2; break;
13594   case ISD::SETUO:  SSECC = 3; break;
13595   case ISD::SETUNE:
13596   case ISD::SETNE:  SSECC = 4; break;
13597   case ISD::SETULE: Swap = true; // Fallthrough
13598   case ISD::SETUGE: SSECC = 5; break;
13599   case ISD::SETULT: Swap = true; // Fallthrough
13600   case ISD::SETUGT: SSECC = 6; break;
13601   case ISD::SETO:   SSECC = 7; break;
13602   case ISD::SETUEQ:
13603   case ISD::SETONE: SSECC = 8; break;
13604   }
13605   if (Swap)
13606     std::swap(Op0, Op1);
13607
13608   return SSECC;
13609 }
13610
13611 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13612 // ones, and then concatenate the result back.
13613 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13614   MVT VT = Op.getSimpleValueType();
13615
13616   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13617          "Unsupported value type for operation");
13618
13619   unsigned NumElems = VT.getVectorNumElements();
13620   SDLoc dl(Op);
13621   SDValue CC = Op.getOperand(2);
13622
13623   // Extract the LHS vectors
13624   SDValue LHS = Op.getOperand(0);
13625   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13626   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13627
13628   // Extract the RHS vectors
13629   SDValue RHS = Op.getOperand(1);
13630   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13631   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13632
13633   // Issue the operation on the smaller types and concatenate the result back
13634   MVT EltVT = VT.getVectorElementType();
13635   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13636   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13637                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13638                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13639 }
13640
13641 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13642   SDValue Op0 = Op.getOperand(0);
13643   SDValue Op1 = Op.getOperand(1);
13644   SDValue CC = Op.getOperand(2);
13645   MVT VT = Op.getSimpleValueType();
13646   SDLoc dl(Op);
13647
13648   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13649          "Unexpected type for boolean compare operation");
13650   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13651   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13652                                DAG.getConstant(-1, dl, VT));
13653   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13654                                DAG.getConstant(-1, dl, VT));
13655   switch (SetCCOpcode) {
13656   default: llvm_unreachable("Unexpected SETCC condition");
13657   case ISD::SETEQ:
13658     // (x == y) -> ~(x ^ y)
13659     return DAG.getNode(ISD::XOR, dl, VT,
13660                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13661                        DAG.getConstant(-1, dl, VT));
13662   case ISD::SETNE:
13663     // (x != y) -> (x ^ y)
13664     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13665   case ISD::SETUGT:
13666   case ISD::SETGT:
13667     // (x > y) -> (x & ~y)
13668     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13669   case ISD::SETULT:
13670   case ISD::SETLT:
13671     // (x < y) -> (~x & y)
13672     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13673   case ISD::SETULE:
13674   case ISD::SETLE:
13675     // (x <= y) -> (~x | y)
13676     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13677   case ISD::SETUGE:
13678   case ISD::SETGE:
13679     // (x >=y) -> (x | ~y)
13680     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13681   }
13682 }
13683
13684 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13685                                      const X86Subtarget *Subtarget) {
13686   SDValue Op0 = Op.getOperand(0);
13687   SDValue Op1 = Op.getOperand(1);
13688   SDValue CC = Op.getOperand(2);
13689   MVT VT = Op.getSimpleValueType();
13690   SDLoc dl(Op);
13691
13692   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13693          Op.getValueType().getScalarType() == MVT::i1 &&
13694          "Cannot set masked compare for this operation");
13695
13696   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13697   unsigned  Opc = 0;
13698   bool Unsigned = false;
13699   bool Swap = false;
13700   unsigned SSECC;
13701   switch (SetCCOpcode) {
13702   default: llvm_unreachable("Unexpected SETCC condition");
13703   case ISD::SETNE:  SSECC = 4; break;
13704   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13705   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13706   case ISD::SETLT:  Swap = true; //fall-through
13707   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13708   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13709   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13710   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13711   case ISD::SETULE: Unsigned = true; //fall-through
13712   case ISD::SETLE:  SSECC = 2; break;
13713   }
13714
13715   if (Swap)
13716     std::swap(Op0, Op1);
13717   if (Opc)
13718     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13719   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13720   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13721                      DAG.getConstant(SSECC, dl, MVT::i8));
13722 }
13723
13724 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13725 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13726 /// return an empty value.
13727 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13728 {
13729   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13730   if (!BV)
13731     return SDValue();
13732
13733   MVT VT = Op1.getSimpleValueType();
13734   MVT EVT = VT.getVectorElementType();
13735   unsigned n = VT.getVectorNumElements();
13736   SmallVector<SDValue, 8> ULTOp1;
13737
13738   for (unsigned i = 0; i < n; ++i) {
13739     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13740     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13741       return SDValue();
13742
13743     // Avoid underflow.
13744     APInt Val = Elt->getAPIntValue();
13745     if (Val == 0)
13746       return SDValue();
13747
13748     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13749   }
13750
13751   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13752 }
13753
13754 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13755                            SelectionDAG &DAG) {
13756   SDValue Op0 = Op.getOperand(0);
13757   SDValue Op1 = Op.getOperand(1);
13758   SDValue CC = Op.getOperand(2);
13759   MVT VT = Op.getSimpleValueType();
13760   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13761   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13762   SDLoc dl(Op);
13763
13764   if (isFP) {
13765 #ifndef NDEBUG
13766     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13767     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13768 #endif
13769
13770     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13771     unsigned Opc = X86ISD::CMPP;
13772     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13773       assert(VT.getVectorNumElements() <= 16);
13774       Opc = X86ISD::CMPM;
13775     }
13776     // In the two special cases we can't handle, emit two comparisons.
13777     if (SSECC == 8) {
13778       unsigned CC0, CC1;
13779       unsigned CombineOpc;
13780       if (SetCCOpcode == ISD::SETUEQ) {
13781         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13782       } else {
13783         assert(SetCCOpcode == ISD::SETONE);
13784         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13785       }
13786
13787       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13788                                  DAG.getConstant(CC0, dl, MVT::i8));
13789       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13790                                  DAG.getConstant(CC1, dl, MVT::i8));
13791       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13792     }
13793     // Handle all other FP comparisons here.
13794     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13795                        DAG.getConstant(SSECC, dl, MVT::i8));
13796   }
13797
13798   // Break 256-bit integer vector compare into smaller ones.
13799   if (VT.is256BitVector() && !Subtarget->hasInt256())
13800     return Lower256IntVSETCC(Op, DAG);
13801
13802   EVT OpVT = Op1.getValueType();
13803   if (OpVT.getVectorElementType() == MVT::i1)
13804     return LowerBoolVSETCC_AVX512(Op, DAG);
13805
13806   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13807   if (Subtarget->hasAVX512()) {
13808     if (Op1.getValueType().is512BitVector() ||
13809         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13810         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13811       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13812
13813     // In AVX-512 architecture setcc returns mask with i1 elements,
13814     // But there is no compare instruction for i8 and i16 elements in KNL.
13815     // We are not talking about 512-bit operands in this case, these
13816     // types are illegal.
13817     if (MaskResult &&
13818         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13819          OpVT.getVectorElementType().getSizeInBits() >= 8))
13820       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13821                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13822   }
13823
13824   // We are handling one of the integer comparisons here.  Since SSE only has
13825   // GT and EQ comparisons for integer, swapping operands and multiple
13826   // operations may be required for some comparisons.
13827   unsigned Opc;
13828   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13829   bool Subus = false;
13830
13831   switch (SetCCOpcode) {
13832   default: llvm_unreachable("Unexpected SETCC condition");
13833   case ISD::SETNE:  Invert = true;
13834   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13835   case ISD::SETLT:  Swap = true;
13836   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13837   case ISD::SETGE:  Swap = true;
13838   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13839                     Invert = true; break;
13840   case ISD::SETULT: Swap = true;
13841   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13842                     FlipSigns = true; break;
13843   case ISD::SETUGE: Swap = true;
13844   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13845                     FlipSigns = true; Invert = true; break;
13846   }
13847
13848   // Special case: Use min/max operations for SETULE/SETUGE
13849   MVT VET = VT.getVectorElementType();
13850   bool hasMinMax =
13851        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13852     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13853
13854   if (hasMinMax) {
13855     switch (SetCCOpcode) {
13856     default: break;
13857     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13858     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13859     }
13860
13861     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13862   }
13863
13864   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13865   if (!MinMax && hasSubus) {
13866     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13867     // Op0 u<= Op1:
13868     //   t = psubus Op0, Op1
13869     //   pcmpeq t, <0..0>
13870     switch (SetCCOpcode) {
13871     default: break;
13872     case ISD::SETULT: {
13873       // If the comparison is against a constant we can turn this into a
13874       // setule.  With psubus, setule does not require a swap.  This is
13875       // beneficial because the constant in the register is no longer
13876       // destructed as the destination so it can be hoisted out of a loop.
13877       // Only do this pre-AVX since vpcmp* is no longer destructive.
13878       if (Subtarget->hasAVX())
13879         break;
13880       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13881       if (ULEOp1.getNode()) {
13882         Op1 = ULEOp1;
13883         Subus = true; Invert = false; Swap = false;
13884       }
13885       break;
13886     }
13887     // Psubus is better than flip-sign because it requires no inversion.
13888     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13889     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13890     }
13891
13892     if (Subus) {
13893       Opc = X86ISD::SUBUS;
13894       FlipSigns = false;
13895     }
13896   }
13897
13898   if (Swap)
13899     std::swap(Op0, Op1);
13900
13901   // Check that the operation in question is available (most are plain SSE2,
13902   // but PCMPGTQ and PCMPEQQ have different requirements).
13903   if (VT == MVT::v2i64) {
13904     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13905       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13906
13907       // First cast everything to the right type.
13908       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13909       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13910
13911       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13912       // bits of the inputs before performing those operations. The lower
13913       // compare is always unsigned.
13914       SDValue SB;
13915       if (FlipSigns) {
13916         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13917       } else {
13918         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13919         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13920         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13921                          Sign, Zero, Sign, Zero);
13922       }
13923       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13924       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13925
13926       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13927       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13928       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13929
13930       // Create masks for only the low parts/high parts of the 64 bit integers.
13931       static const int MaskHi[] = { 1, 1, 3, 3 };
13932       static const int MaskLo[] = { 0, 0, 2, 2 };
13933       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13934       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13935       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13936
13937       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13938       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13939
13940       if (Invert)
13941         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13942
13943       return DAG.getBitcast(VT, Result);
13944     }
13945
13946     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13947       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13948       // pcmpeqd + pshufd + pand.
13949       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13950
13951       // First cast everything to the right type.
13952       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13953       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13954
13955       // Do the compare.
13956       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13957
13958       // Make sure the lower and upper halves are both all-ones.
13959       static const int Mask[] = { 1, 0, 3, 2 };
13960       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13961       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13962
13963       if (Invert)
13964         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13965
13966       return DAG.getBitcast(VT, Result);
13967     }
13968   }
13969
13970   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13971   // bits of the inputs before performing those operations.
13972   if (FlipSigns) {
13973     EVT EltVT = VT.getVectorElementType();
13974     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13975                                  VT);
13976     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13977     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13978   }
13979
13980   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13981
13982   // If the logical-not of the result is required, perform that now.
13983   if (Invert)
13984     Result = DAG.getNOT(dl, Result, VT);
13985
13986   if (MinMax)
13987     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13988
13989   if (Subus)
13990     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13991                          getZeroVector(VT, Subtarget, DAG, dl));
13992
13993   return Result;
13994 }
13995
13996 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13997
13998   MVT VT = Op.getSimpleValueType();
13999
14000   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14001
14002   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14003          && "SetCC type must be 8-bit or 1-bit integer");
14004   SDValue Op0 = Op.getOperand(0);
14005   SDValue Op1 = Op.getOperand(1);
14006   SDLoc dl(Op);
14007   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14008
14009   // Optimize to BT if possible.
14010   // Lower (X & (1 << N)) == 0 to BT(X, N).
14011   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14012   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14013   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14014       Op1.getOpcode() == ISD::Constant &&
14015       cast<ConstantSDNode>(Op1)->isNullValue() &&
14016       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14017     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14018     if (NewSetCC.getNode()) {
14019       if (VT == MVT::i1)
14020         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14021       return NewSetCC;
14022     }
14023   }
14024
14025   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14026   // these.
14027   if (Op1.getOpcode() == ISD::Constant &&
14028       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14029        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14030       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14031
14032     // If the input is a setcc, then reuse the input setcc or use a new one with
14033     // the inverted condition.
14034     if (Op0.getOpcode() == X86ISD::SETCC) {
14035       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14036       bool Invert = (CC == ISD::SETNE) ^
14037         cast<ConstantSDNode>(Op1)->isNullValue();
14038       if (!Invert)
14039         return Op0;
14040
14041       CCode = X86::GetOppositeBranchCondition(CCode);
14042       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14043                                   DAG.getConstant(CCode, dl, MVT::i8),
14044                                   Op0.getOperand(1));
14045       if (VT == MVT::i1)
14046         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14047       return SetCC;
14048     }
14049   }
14050   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14051       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14052       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14053
14054     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14055     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14056   }
14057
14058   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14059   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14060   if (X86CC == X86::COND_INVALID)
14061     return SDValue();
14062
14063   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14064   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14065   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14066                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14067   if (VT == MVT::i1)
14068     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14069   return SetCC;
14070 }
14071
14072 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14073 static bool isX86LogicalCmp(SDValue Op) {
14074   unsigned Opc = Op.getNode()->getOpcode();
14075   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14076       Opc == X86ISD::SAHF)
14077     return true;
14078   if (Op.getResNo() == 1 &&
14079       (Opc == X86ISD::ADD ||
14080        Opc == X86ISD::SUB ||
14081        Opc == X86ISD::ADC ||
14082        Opc == X86ISD::SBB ||
14083        Opc == X86ISD::SMUL ||
14084        Opc == X86ISD::UMUL ||
14085        Opc == X86ISD::INC ||
14086        Opc == X86ISD::DEC ||
14087        Opc == X86ISD::OR ||
14088        Opc == X86ISD::XOR ||
14089        Opc == X86ISD::AND))
14090     return true;
14091
14092   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14093     return true;
14094
14095   return false;
14096 }
14097
14098 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14099   if (V.getOpcode() != ISD::TRUNCATE)
14100     return false;
14101
14102   SDValue VOp0 = V.getOperand(0);
14103   unsigned InBits = VOp0.getValueSizeInBits();
14104   unsigned Bits = V.getValueSizeInBits();
14105   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14106 }
14107
14108 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14109   bool addTest = true;
14110   SDValue Cond  = Op.getOperand(0);
14111   SDValue Op1 = Op.getOperand(1);
14112   SDValue Op2 = Op.getOperand(2);
14113   SDLoc DL(Op);
14114   EVT VT = Op1.getValueType();
14115   SDValue CC;
14116
14117   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14118   // are available or VBLENDV if AVX is available.
14119   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14120   if (Cond.getOpcode() == ISD::SETCC &&
14121       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14122        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14123       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14124     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14125     int SSECC = translateX86FSETCC(
14126         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14127
14128     if (SSECC != 8) {
14129       if (Subtarget->hasAVX512()) {
14130         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14131                                   DAG.getConstant(SSECC, DL, MVT::i8));
14132         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14133       }
14134
14135       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14136                                 DAG.getConstant(SSECC, DL, MVT::i8));
14137
14138       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14139       // of 3 logic instructions for size savings and potentially speed.
14140       // Unfortunately, there is no scalar form of VBLENDV.
14141
14142       // If either operand is a constant, don't try this. We can expect to
14143       // optimize away at least one of the logic instructions later in that
14144       // case, so that sequence would be faster than a variable blend.
14145
14146       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14147       // uses XMM0 as the selection register. That may need just as many
14148       // instructions as the AND/ANDN/OR sequence due to register moves, so
14149       // don't bother.
14150
14151       if (Subtarget->hasAVX() &&
14152           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14153
14154         // Convert to vectors, do a VSELECT, and convert back to scalar.
14155         // All of the conversions should be optimized away.
14156
14157         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14158         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14159         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14160         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14161
14162         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14163         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14164
14165         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14166
14167         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14168                            VSel, DAG.getIntPtrConstant(0, DL));
14169       }
14170       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14171       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14172       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14173     }
14174   }
14175
14176   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14177     SDValue Op1Scalar;
14178     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14179       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14180     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14181       Op1Scalar = Op1.getOperand(0);
14182     SDValue Op2Scalar;
14183     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14184       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14185     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14186       Op2Scalar = Op2.getOperand(0);
14187     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14188       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14189                                       Op1Scalar.getValueType(),
14190                                       Cond, Op1Scalar, Op2Scalar);
14191       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14192         return DAG.getBitcast(VT, newSelect);
14193       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14194       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14195                          DAG.getIntPtrConstant(0, DL));
14196     }
14197   }
14198
14199   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14200     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14201     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14202                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14203     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14204                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14205     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14206                                     Cond, Op1, Op2);
14207     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14208   }
14209
14210   if (Cond.getOpcode() == ISD::SETCC) {
14211     SDValue NewCond = LowerSETCC(Cond, DAG);
14212     if (NewCond.getNode())
14213       Cond = NewCond;
14214   }
14215
14216   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14217   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14218   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14219   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14220   if (Cond.getOpcode() == X86ISD::SETCC &&
14221       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14222       isZero(Cond.getOperand(1).getOperand(1))) {
14223     SDValue Cmp = Cond.getOperand(1);
14224
14225     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14226
14227     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14228         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14229       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14230
14231       SDValue CmpOp0 = Cmp.getOperand(0);
14232       // Apply further optimizations for special cases
14233       // (select (x != 0), -1, 0) -> neg & sbb
14234       // (select (x == 0), 0, -1) -> neg & sbb
14235       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14236         if (YC->isNullValue() &&
14237             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14238           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14239           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14240                                     DAG.getConstant(0, DL,
14241                                                     CmpOp0.getValueType()),
14242                                     CmpOp0);
14243           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14244                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14245                                     SDValue(Neg.getNode(), 1));
14246           return Res;
14247         }
14248
14249       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14250                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14251       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14252
14253       SDValue Res =   // Res = 0 or -1.
14254         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14255                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14256
14257       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14258         Res = DAG.getNOT(DL, Res, Res.getValueType());
14259
14260       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14261       if (!N2C || !N2C->isNullValue())
14262         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14263       return Res;
14264     }
14265   }
14266
14267   // Look past (and (setcc_carry (cmp ...)), 1).
14268   if (Cond.getOpcode() == ISD::AND &&
14269       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14270     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14271     if (C && C->getAPIntValue() == 1)
14272       Cond = Cond.getOperand(0);
14273   }
14274
14275   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14276   // setting operand in place of the X86ISD::SETCC.
14277   unsigned CondOpcode = Cond.getOpcode();
14278   if (CondOpcode == X86ISD::SETCC ||
14279       CondOpcode == X86ISD::SETCC_CARRY) {
14280     CC = Cond.getOperand(0);
14281
14282     SDValue Cmp = Cond.getOperand(1);
14283     unsigned Opc = Cmp.getOpcode();
14284     MVT VT = Op.getSimpleValueType();
14285
14286     bool IllegalFPCMov = false;
14287     if (VT.isFloatingPoint() && !VT.isVector() &&
14288         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14289       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14290
14291     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14292         Opc == X86ISD::BT) { // FIXME
14293       Cond = Cmp;
14294       addTest = false;
14295     }
14296   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14297              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14298              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14299               Cond.getOperand(0).getValueType() != MVT::i8)) {
14300     SDValue LHS = Cond.getOperand(0);
14301     SDValue RHS = Cond.getOperand(1);
14302     unsigned X86Opcode;
14303     unsigned X86Cond;
14304     SDVTList VTs;
14305     switch (CondOpcode) {
14306     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14307     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14308     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14309     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14310     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14311     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14312     default: llvm_unreachable("unexpected overflowing operator");
14313     }
14314     if (CondOpcode == ISD::UMULO)
14315       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14316                           MVT::i32);
14317     else
14318       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14319
14320     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14321
14322     if (CondOpcode == ISD::UMULO)
14323       Cond = X86Op.getValue(2);
14324     else
14325       Cond = X86Op.getValue(1);
14326
14327     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14328     addTest = false;
14329   }
14330
14331   if (addTest) {
14332     // Look past the truncate if the high bits are known zero.
14333     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14334       Cond = Cond.getOperand(0);
14335
14336     // We know the result of AND is compared against zero. Try to match
14337     // it to BT.
14338     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14339       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14340       if (NewSetCC.getNode()) {
14341         CC = NewSetCC.getOperand(0);
14342         Cond = NewSetCC.getOperand(1);
14343         addTest = false;
14344       }
14345     }
14346   }
14347
14348   if (addTest) {
14349     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14350     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14351   }
14352
14353   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14354   // a <  b ?  0 : -1 -> RES = setcc_carry
14355   // a >= b ? -1 :  0 -> RES = setcc_carry
14356   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14357   if (Cond.getOpcode() == X86ISD::SUB) {
14358     Cond = ConvertCmpIfNecessary(Cond, DAG);
14359     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14360
14361     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14362         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14363       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14364                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14365                                 Cond);
14366       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14367         return DAG.getNOT(DL, Res, Res.getValueType());
14368       return Res;
14369     }
14370   }
14371
14372   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14373   // widen the cmov and push the truncate through. This avoids introducing a new
14374   // branch during isel and doesn't add any extensions.
14375   if (Op.getValueType() == MVT::i8 &&
14376       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14377     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14378     if (T1.getValueType() == T2.getValueType() &&
14379         // Blacklist CopyFromReg to avoid partial register stalls.
14380         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14381       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14382       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14383       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14384     }
14385   }
14386
14387   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14388   // condition is true.
14389   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14390   SDValue Ops[] = { Op2, Op1, CC, Cond };
14391   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14392 }
14393
14394 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14395                                        const X86Subtarget *Subtarget,
14396                                        SelectionDAG &DAG) {
14397   MVT VT = Op->getSimpleValueType(0);
14398   SDValue In = Op->getOperand(0);
14399   MVT InVT = In.getSimpleValueType();
14400   MVT VTElt = VT.getVectorElementType();
14401   MVT InVTElt = InVT.getVectorElementType();
14402   SDLoc dl(Op);
14403
14404   // SKX processor
14405   if ((InVTElt == MVT::i1) &&
14406       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14407         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14408
14409        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14410         VTElt.getSizeInBits() <= 16)) ||
14411
14412        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14413         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14414
14415        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14416         VTElt.getSizeInBits() >= 32))))
14417     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14418
14419   unsigned int NumElts = VT.getVectorNumElements();
14420
14421   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14422     return SDValue();
14423
14424   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14425     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14426       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14427     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14428   }
14429
14430   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14431   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14432   SDValue NegOne =
14433    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14434                    ExtVT);
14435   SDValue Zero =
14436    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14437
14438   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14439   if (VT.is512BitVector())
14440     return V;
14441   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14442 }
14443
14444 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14445                                              const X86Subtarget *Subtarget,
14446                                              SelectionDAG &DAG) {
14447   SDValue In = Op->getOperand(0);
14448   MVT VT = Op->getSimpleValueType(0);
14449   MVT InVT = In.getSimpleValueType();
14450   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14451
14452   MVT InSVT = InVT.getScalarType();
14453   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14454
14455   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14456     return SDValue();
14457   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14458     return SDValue();
14459
14460   SDLoc dl(Op);
14461
14462   // SSE41 targets can use the pmovsx* instructions directly.
14463   if (Subtarget->hasSSE41())
14464     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14465
14466   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14467   SDValue Curr = In;
14468   MVT CurrVT = InVT;
14469
14470   // As SRAI is only available on i16/i32 types, we expand only up to i32
14471   // and handle i64 separately.
14472   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14473     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14474     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14475     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14476     Curr = DAG.getBitcast(CurrVT, Curr);
14477   }
14478
14479   SDValue SignExt = Curr;
14480   if (CurrVT != InVT) {
14481     unsigned SignExtShift =
14482         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14483     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14484                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14485   }
14486
14487   if (CurrVT == VT)
14488     return SignExt;
14489
14490   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14491     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14492                                DAG.getConstant(31, dl, MVT::i8));
14493     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14494     return DAG.getBitcast(VT, Ext);
14495   }
14496
14497   return SDValue();
14498 }
14499
14500 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14501                                 SelectionDAG &DAG) {
14502   MVT VT = Op->getSimpleValueType(0);
14503   SDValue In = Op->getOperand(0);
14504   MVT InVT = In.getSimpleValueType();
14505   SDLoc dl(Op);
14506
14507   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14508     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14509
14510   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14511       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14512       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14513     return SDValue();
14514
14515   if (Subtarget->hasInt256())
14516     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14517
14518   // Optimize vectors in AVX mode
14519   // Sign extend  v8i16 to v8i32 and
14520   //              v4i32 to v4i64
14521   //
14522   // Divide input vector into two parts
14523   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14524   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14525   // concat the vectors to original VT
14526
14527   unsigned NumElems = InVT.getVectorNumElements();
14528   SDValue Undef = DAG.getUNDEF(InVT);
14529
14530   SmallVector<int,8> ShufMask1(NumElems, -1);
14531   for (unsigned i = 0; i != NumElems/2; ++i)
14532     ShufMask1[i] = i;
14533
14534   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14535
14536   SmallVector<int,8> ShufMask2(NumElems, -1);
14537   for (unsigned i = 0; i != NumElems/2; ++i)
14538     ShufMask2[i] = i + NumElems/2;
14539
14540   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14541
14542   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14543                                 VT.getVectorNumElements()/2);
14544
14545   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14546   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14547
14548   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14549 }
14550
14551 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14552 // may emit an illegal shuffle but the expansion is still better than scalar
14553 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14554 // we'll emit a shuffle and a arithmetic shift.
14555 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14556 // TODO: It is possible to support ZExt by zeroing the undef values during
14557 // the shuffle phase or after the shuffle.
14558 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14559                                  SelectionDAG &DAG) {
14560   MVT RegVT = Op.getSimpleValueType();
14561   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14562   assert(RegVT.isInteger() &&
14563          "We only custom lower integer vector sext loads.");
14564
14565   // Nothing useful we can do without SSE2 shuffles.
14566   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14567
14568   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14569   SDLoc dl(Ld);
14570   EVT MemVT = Ld->getMemoryVT();
14571   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14572   unsigned RegSz = RegVT.getSizeInBits();
14573
14574   ISD::LoadExtType Ext = Ld->getExtensionType();
14575
14576   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14577          && "Only anyext and sext are currently implemented.");
14578   assert(MemVT != RegVT && "Cannot extend to the same type");
14579   assert(MemVT.isVector() && "Must load a vector from memory");
14580
14581   unsigned NumElems = RegVT.getVectorNumElements();
14582   unsigned MemSz = MemVT.getSizeInBits();
14583   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14584
14585   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14586     // The only way in which we have a legal 256-bit vector result but not the
14587     // integer 256-bit operations needed to directly lower a sextload is if we
14588     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14589     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14590     // correctly legalized. We do this late to allow the canonical form of
14591     // sextload to persist throughout the rest of the DAG combiner -- it wants
14592     // to fold together any extensions it can, and so will fuse a sign_extend
14593     // of an sextload into a sextload targeting a wider value.
14594     SDValue Load;
14595     if (MemSz == 128) {
14596       // Just switch this to a normal load.
14597       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14598                                        "it must be a legal 128-bit vector "
14599                                        "type!");
14600       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14601                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14602                   Ld->isInvariant(), Ld->getAlignment());
14603     } else {
14604       assert(MemSz < 128 &&
14605              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14606       // Do an sext load to a 128-bit vector type. We want to use the same
14607       // number of elements, but elements half as wide. This will end up being
14608       // recursively lowered by this routine, but will succeed as we definitely
14609       // have all the necessary features if we're using AVX1.
14610       EVT HalfEltVT =
14611           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14612       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14613       Load =
14614           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14615                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14616                          Ld->isNonTemporal(), Ld->isInvariant(),
14617                          Ld->getAlignment());
14618     }
14619
14620     // Replace chain users with the new chain.
14621     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14622     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14623
14624     // Finally, do a normal sign-extend to the desired register.
14625     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14626   }
14627
14628   // All sizes must be a power of two.
14629   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14630          "Non-power-of-two elements are not custom lowered!");
14631
14632   // Attempt to load the original value using scalar loads.
14633   // Find the largest scalar type that divides the total loaded size.
14634   MVT SclrLoadTy = MVT::i8;
14635   for (MVT Tp : MVT::integer_valuetypes()) {
14636     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14637       SclrLoadTy = Tp;
14638     }
14639   }
14640
14641   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14642   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14643       (64 <= MemSz))
14644     SclrLoadTy = MVT::f64;
14645
14646   // Calculate the number of scalar loads that we need to perform
14647   // in order to load our vector from memory.
14648   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14649
14650   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14651          "Can only lower sext loads with a single scalar load!");
14652
14653   unsigned loadRegZize = RegSz;
14654   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14655     loadRegZize = 128;
14656
14657   // Represent our vector as a sequence of elements which are the
14658   // largest scalar that we can load.
14659   EVT LoadUnitVecVT = EVT::getVectorVT(
14660       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14661
14662   // Represent the data using the same element type that is stored in
14663   // memory. In practice, we ''widen'' MemVT.
14664   EVT WideVecVT =
14665       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14666                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14667
14668   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14669          "Invalid vector type");
14670
14671   // We can't shuffle using an illegal type.
14672   assert(TLI.isTypeLegal(WideVecVT) &&
14673          "We only lower types that form legal widened vector types");
14674
14675   SmallVector<SDValue, 8> Chains;
14676   SDValue Ptr = Ld->getBasePtr();
14677   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14678                                       TLI.getPointerTy(DAG.getDataLayout()));
14679   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14680
14681   for (unsigned i = 0; i < NumLoads; ++i) {
14682     // Perform a single load.
14683     SDValue ScalarLoad =
14684         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14685                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14686                     Ld->getAlignment());
14687     Chains.push_back(ScalarLoad.getValue(1));
14688     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14689     // another round of DAGCombining.
14690     if (i == 0)
14691       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14692     else
14693       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14694                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14695
14696     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14697   }
14698
14699   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14700
14701   // Bitcast the loaded value to a vector of the original element type, in
14702   // the size of the target vector type.
14703   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14704   unsigned SizeRatio = RegSz / MemSz;
14705
14706   if (Ext == ISD::SEXTLOAD) {
14707     // If we have SSE4.1, we can directly emit a VSEXT node.
14708     if (Subtarget->hasSSE41()) {
14709       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14710       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14711       return Sext;
14712     }
14713
14714     // Otherwise we'll shuffle the small elements in the high bits of the
14715     // larger type and perform an arithmetic shift. If the shift is not legal
14716     // it's better to scalarize.
14717     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14718            "We can't implement a sext load without an arithmetic right shift!");
14719
14720     // Redistribute the loaded elements into the different locations.
14721     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14722     for (unsigned i = 0; i != NumElems; ++i)
14723       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14724
14725     SDValue Shuff = DAG.getVectorShuffle(
14726         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14727
14728     Shuff = DAG.getBitcast(RegVT, Shuff);
14729
14730     // Build the arithmetic shift.
14731     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14732                    MemVT.getVectorElementType().getSizeInBits();
14733     Shuff =
14734         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14735                     DAG.getConstant(Amt, dl, RegVT));
14736
14737     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14738     return Shuff;
14739   }
14740
14741   // Redistribute the loaded elements into the different locations.
14742   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14743   for (unsigned i = 0; i != NumElems; ++i)
14744     ShuffleVec[i * SizeRatio] = i;
14745
14746   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14747                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14748
14749   // Bitcast to the requested type.
14750   Shuff = DAG.getBitcast(RegVT, Shuff);
14751   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14752   return Shuff;
14753 }
14754
14755 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14756 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14757 // from the AND / OR.
14758 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14759   Opc = Op.getOpcode();
14760   if (Opc != ISD::OR && Opc != ISD::AND)
14761     return false;
14762   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14763           Op.getOperand(0).hasOneUse() &&
14764           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14765           Op.getOperand(1).hasOneUse());
14766 }
14767
14768 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14769 // 1 and that the SETCC node has a single use.
14770 static bool isXor1OfSetCC(SDValue Op) {
14771   if (Op.getOpcode() != ISD::XOR)
14772     return false;
14773   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14774   if (N1C && N1C->getAPIntValue() == 1) {
14775     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14776       Op.getOperand(0).hasOneUse();
14777   }
14778   return false;
14779 }
14780
14781 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14782   bool addTest = true;
14783   SDValue Chain = Op.getOperand(0);
14784   SDValue Cond  = Op.getOperand(1);
14785   SDValue Dest  = Op.getOperand(2);
14786   SDLoc dl(Op);
14787   SDValue CC;
14788   bool Inverted = false;
14789
14790   if (Cond.getOpcode() == ISD::SETCC) {
14791     // Check for setcc([su]{add,sub,mul}o == 0).
14792     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14793         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14794         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14795         Cond.getOperand(0).getResNo() == 1 &&
14796         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14797          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14798          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14799          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14800          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14801          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14802       Inverted = true;
14803       Cond = Cond.getOperand(0);
14804     } else {
14805       SDValue NewCond = LowerSETCC(Cond, DAG);
14806       if (NewCond.getNode())
14807         Cond = NewCond;
14808     }
14809   }
14810 #if 0
14811   // FIXME: LowerXALUO doesn't handle these!!
14812   else if (Cond.getOpcode() == X86ISD::ADD  ||
14813            Cond.getOpcode() == X86ISD::SUB  ||
14814            Cond.getOpcode() == X86ISD::SMUL ||
14815            Cond.getOpcode() == X86ISD::UMUL)
14816     Cond = LowerXALUO(Cond, DAG);
14817 #endif
14818
14819   // Look pass (and (setcc_carry (cmp ...)), 1).
14820   if (Cond.getOpcode() == ISD::AND &&
14821       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14822     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14823     if (C && C->getAPIntValue() == 1)
14824       Cond = Cond.getOperand(0);
14825   }
14826
14827   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14828   // setting operand in place of the X86ISD::SETCC.
14829   unsigned CondOpcode = Cond.getOpcode();
14830   if (CondOpcode == X86ISD::SETCC ||
14831       CondOpcode == X86ISD::SETCC_CARRY) {
14832     CC = Cond.getOperand(0);
14833
14834     SDValue Cmp = Cond.getOperand(1);
14835     unsigned Opc = Cmp.getOpcode();
14836     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14837     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14838       Cond = Cmp;
14839       addTest = false;
14840     } else {
14841       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14842       default: break;
14843       case X86::COND_O:
14844       case X86::COND_B:
14845         // These can only come from an arithmetic instruction with overflow,
14846         // e.g. SADDO, UADDO.
14847         Cond = Cond.getNode()->getOperand(1);
14848         addTest = false;
14849         break;
14850       }
14851     }
14852   }
14853   CondOpcode = Cond.getOpcode();
14854   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14855       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14856       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14857        Cond.getOperand(0).getValueType() != MVT::i8)) {
14858     SDValue LHS = Cond.getOperand(0);
14859     SDValue RHS = Cond.getOperand(1);
14860     unsigned X86Opcode;
14861     unsigned X86Cond;
14862     SDVTList VTs;
14863     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14864     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14865     // X86ISD::INC).
14866     switch (CondOpcode) {
14867     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14868     case ISD::SADDO:
14869       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14870         if (C->isOne()) {
14871           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14872           break;
14873         }
14874       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14875     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14876     case ISD::SSUBO:
14877       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14878         if (C->isOne()) {
14879           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14880           break;
14881         }
14882       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14883     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14884     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14885     default: llvm_unreachable("unexpected overflowing operator");
14886     }
14887     if (Inverted)
14888       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14889     if (CondOpcode == ISD::UMULO)
14890       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14891                           MVT::i32);
14892     else
14893       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14894
14895     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14896
14897     if (CondOpcode == ISD::UMULO)
14898       Cond = X86Op.getValue(2);
14899     else
14900       Cond = X86Op.getValue(1);
14901
14902     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14903     addTest = false;
14904   } else {
14905     unsigned CondOpc;
14906     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14907       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14908       if (CondOpc == ISD::OR) {
14909         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14910         // two branches instead of an explicit OR instruction with a
14911         // separate test.
14912         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14913             isX86LogicalCmp(Cmp)) {
14914           CC = Cond.getOperand(0).getOperand(0);
14915           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14916                               Chain, Dest, CC, Cmp);
14917           CC = Cond.getOperand(1).getOperand(0);
14918           Cond = Cmp;
14919           addTest = false;
14920         }
14921       } else { // ISD::AND
14922         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14923         // two branches instead of an explicit AND instruction with a
14924         // separate test. However, we only do this if this block doesn't
14925         // have a fall-through edge, because this requires an explicit
14926         // jmp when the condition is false.
14927         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14928             isX86LogicalCmp(Cmp) &&
14929             Op.getNode()->hasOneUse()) {
14930           X86::CondCode CCode =
14931             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14932           CCode = X86::GetOppositeBranchCondition(CCode);
14933           CC = DAG.getConstant(CCode, dl, MVT::i8);
14934           SDNode *User = *Op.getNode()->use_begin();
14935           // Look for an unconditional branch following this conditional branch.
14936           // We need this because we need to reverse the successors in order
14937           // to implement FCMP_OEQ.
14938           if (User->getOpcode() == ISD::BR) {
14939             SDValue FalseBB = User->getOperand(1);
14940             SDNode *NewBR =
14941               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14942             assert(NewBR == User);
14943             (void)NewBR;
14944             Dest = FalseBB;
14945
14946             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14947                                 Chain, Dest, CC, Cmp);
14948             X86::CondCode CCode =
14949               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14950             CCode = X86::GetOppositeBranchCondition(CCode);
14951             CC = DAG.getConstant(CCode, dl, MVT::i8);
14952             Cond = Cmp;
14953             addTest = false;
14954           }
14955         }
14956       }
14957     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14958       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14959       // It should be transformed during dag combiner except when the condition
14960       // is set by a arithmetics with overflow node.
14961       X86::CondCode CCode =
14962         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14963       CCode = X86::GetOppositeBranchCondition(CCode);
14964       CC = DAG.getConstant(CCode, dl, MVT::i8);
14965       Cond = Cond.getOperand(0).getOperand(1);
14966       addTest = false;
14967     } else if (Cond.getOpcode() == ISD::SETCC &&
14968                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14969       // For FCMP_OEQ, we can emit
14970       // two branches instead of an explicit AND instruction with a
14971       // separate test. However, we only do this if this block doesn't
14972       // have a fall-through edge, because this requires an explicit
14973       // jmp when the condition is false.
14974       if (Op.getNode()->hasOneUse()) {
14975         SDNode *User = *Op.getNode()->use_begin();
14976         // Look for an unconditional branch following this conditional branch.
14977         // We need this because we need to reverse the successors in order
14978         // to implement FCMP_OEQ.
14979         if (User->getOpcode() == ISD::BR) {
14980           SDValue FalseBB = User->getOperand(1);
14981           SDNode *NewBR =
14982             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14983           assert(NewBR == User);
14984           (void)NewBR;
14985           Dest = FalseBB;
14986
14987           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14988                                     Cond.getOperand(0), Cond.getOperand(1));
14989           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14990           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14991           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14992                               Chain, Dest, CC, Cmp);
14993           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14994           Cond = Cmp;
14995           addTest = false;
14996         }
14997       }
14998     } else if (Cond.getOpcode() == ISD::SETCC &&
14999                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15000       // For FCMP_UNE, we can emit
15001       // two branches instead of an explicit AND instruction with a
15002       // separate test. However, we only do this if this block doesn't
15003       // have a fall-through edge, because this requires an explicit
15004       // jmp when the condition is false.
15005       if (Op.getNode()->hasOneUse()) {
15006         SDNode *User = *Op.getNode()->use_begin();
15007         // Look for an unconditional branch following this conditional branch.
15008         // We need this because we need to reverse the successors in order
15009         // to implement FCMP_UNE.
15010         if (User->getOpcode() == ISD::BR) {
15011           SDValue FalseBB = User->getOperand(1);
15012           SDNode *NewBR =
15013             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15014           assert(NewBR == User);
15015           (void)NewBR;
15016
15017           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15018                                     Cond.getOperand(0), Cond.getOperand(1));
15019           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15020           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15021           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15022                               Chain, Dest, CC, Cmp);
15023           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15024           Cond = Cmp;
15025           addTest = false;
15026           Dest = FalseBB;
15027         }
15028       }
15029     }
15030   }
15031
15032   if (addTest) {
15033     // Look pass the truncate if the high bits are known zero.
15034     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15035         Cond = Cond.getOperand(0);
15036
15037     // We know the result of AND is compared against zero. Try to match
15038     // it to BT.
15039     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15040       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15041       if (NewSetCC.getNode()) {
15042         CC = NewSetCC.getOperand(0);
15043         Cond = NewSetCC.getOperand(1);
15044         addTest = false;
15045       }
15046     }
15047   }
15048
15049   if (addTest) {
15050     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15051     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15052     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15053   }
15054   Cond = ConvertCmpIfNecessary(Cond, DAG);
15055   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15056                      Chain, Dest, CC, Cond);
15057 }
15058
15059 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15060 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15061 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15062 // that the guard pages used by the OS virtual memory manager are allocated in
15063 // correct sequence.
15064 SDValue
15065 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15066                                            SelectionDAG &DAG) const {
15067   MachineFunction &MF = DAG.getMachineFunction();
15068   bool SplitStack = MF.shouldSplitStack();
15069   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15070                SplitStack;
15071   SDLoc dl(Op);
15072
15073   if (!Lower) {
15074     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15075     SDNode* Node = Op.getNode();
15076
15077     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15078     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15079         " not tell us which reg is the stack pointer!");
15080     EVT VT = Node->getValueType(0);
15081     SDValue Tmp1 = SDValue(Node, 0);
15082     SDValue Tmp2 = SDValue(Node, 1);
15083     SDValue Tmp3 = Node->getOperand(2);
15084     SDValue Chain = Tmp1.getOperand(0);
15085
15086     // Chain the dynamic stack allocation so that it doesn't modify the stack
15087     // pointer when other instructions are using the stack.
15088     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15089         SDLoc(Node));
15090
15091     SDValue Size = Tmp2.getOperand(1);
15092     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15093     Chain = SP.getValue(1);
15094     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15095     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15096     unsigned StackAlign = TFI.getStackAlignment();
15097     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15098     if (Align > StackAlign)
15099       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15100           DAG.getConstant(-(uint64_t)Align, dl, VT));
15101     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15102
15103     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15104         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15105         SDLoc(Node));
15106
15107     SDValue Ops[2] = { Tmp1, Tmp2 };
15108     return DAG.getMergeValues(Ops, dl);
15109   }
15110
15111   // Get the inputs.
15112   SDValue Chain = Op.getOperand(0);
15113   SDValue Size  = Op.getOperand(1);
15114   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15115   EVT VT = Op.getNode()->getValueType(0);
15116
15117   bool Is64Bit = Subtarget->is64Bit();
15118   MVT SPTy = getPointerTy(DAG.getDataLayout());
15119
15120   if (SplitStack) {
15121     MachineRegisterInfo &MRI = MF.getRegInfo();
15122
15123     if (Is64Bit) {
15124       // The 64 bit implementation of segmented stacks needs to clobber both r10
15125       // r11. This makes it impossible to use it along with nested parameters.
15126       const Function *F = MF.getFunction();
15127
15128       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15129            I != E; ++I)
15130         if (I->hasNestAttr())
15131           report_fatal_error("Cannot use segmented stacks with functions that "
15132                              "have nested arguments.");
15133     }
15134
15135     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15136     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15137     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15138     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15139                                 DAG.getRegister(Vreg, SPTy));
15140     SDValue Ops1[2] = { Value, Chain };
15141     return DAG.getMergeValues(Ops1, dl);
15142   } else {
15143     SDValue Flag;
15144     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15145
15146     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15147     Flag = Chain.getValue(1);
15148     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15149
15150     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15151
15152     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15153     unsigned SPReg = RegInfo->getStackRegister();
15154     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15155     Chain = SP.getValue(1);
15156
15157     if (Align) {
15158       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15159                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15160       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15161     }
15162
15163     SDValue Ops1[2] = { SP, Chain };
15164     return DAG.getMergeValues(Ops1, dl);
15165   }
15166 }
15167
15168 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15169   MachineFunction &MF = DAG.getMachineFunction();
15170   auto PtrVT = getPointerTy(MF.getDataLayout());
15171   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15172
15173   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15174   SDLoc DL(Op);
15175
15176   if (!Subtarget->is64Bit() ||
15177       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15178     // vastart just stores the address of the VarArgsFrameIndex slot into the
15179     // memory location argument.
15180     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15181     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15182                         MachinePointerInfo(SV), false, false, 0);
15183   }
15184
15185   // __va_list_tag:
15186   //   gp_offset         (0 - 6 * 8)
15187   //   fp_offset         (48 - 48 + 8 * 16)
15188   //   overflow_arg_area (point to parameters coming in memory).
15189   //   reg_save_area
15190   SmallVector<SDValue, 8> MemOps;
15191   SDValue FIN = Op.getOperand(1);
15192   // Store gp_offset
15193   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15194                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15195                                                DL, MVT::i32),
15196                                FIN, MachinePointerInfo(SV), false, false, 0);
15197   MemOps.push_back(Store);
15198
15199   // Store fp_offset
15200   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15201   Store = DAG.getStore(Op.getOperand(0), DL,
15202                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15203                                        MVT::i32),
15204                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15205   MemOps.push_back(Store);
15206
15207   // Store ptr to overflow_arg_area
15208   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15209   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15210   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15211                        MachinePointerInfo(SV, 8),
15212                        false, false, 0);
15213   MemOps.push_back(Store);
15214
15215   // Store ptr to reg_save_area.
15216   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15217   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15218   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15219                        MachinePointerInfo(SV, 16), false, false, 0);
15220   MemOps.push_back(Store);
15221   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15222 }
15223
15224 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15225   assert(Subtarget->is64Bit() &&
15226          "LowerVAARG only handles 64-bit va_arg!");
15227   assert(Op.getNode()->getNumOperands() == 4);
15228
15229   MachineFunction &MF = DAG.getMachineFunction();
15230   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15231     // The Win64 ABI uses char* instead of a structure.
15232     return DAG.expandVAArg(Op.getNode());
15233
15234   SDValue Chain = Op.getOperand(0);
15235   SDValue SrcPtr = Op.getOperand(1);
15236   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15237   unsigned Align = Op.getConstantOperandVal(3);
15238   SDLoc dl(Op);
15239
15240   EVT ArgVT = Op.getNode()->getValueType(0);
15241   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15242   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15243   uint8_t ArgMode;
15244
15245   // Decide which area this value should be read from.
15246   // TODO: Implement the AMD64 ABI in its entirety. This simple
15247   // selection mechanism works only for the basic types.
15248   if (ArgVT == MVT::f80) {
15249     llvm_unreachable("va_arg for f80 not yet implemented");
15250   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15251     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15252   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15253     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15254   } else {
15255     llvm_unreachable("Unhandled argument type in LowerVAARG");
15256   }
15257
15258   if (ArgMode == 2) {
15259     // Sanity Check: Make sure using fp_offset makes sense.
15260     assert(!Subtarget->useSoftFloat() &&
15261            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15262            Subtarget->hasSSE1());
15263   }
15264
15265   // Insert VAARG_64 node into the DAG
15266   // VAARG_64 returns two values: Variable Argument Address, Chain
15267   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15268                        DAG.getConstant(ArgMode, dl, MVT::i8),
15269                        DAG.getConstant(Align, dl, MVT::i32)};
15270   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15271   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15272                                           VTs, InstOps, MVT::i64,
15273                                           MachinePointerInfo(SV),
15274                                           /*Align=*/0,
15275                                           /*Volatile=*/false,
15276                                           /*ReadMem=*/true,
15277                                           /*WriteMem=*/true);
15278   Chain = VAARG.getValue(1);
15279
15280   // Load the next argument and return it
15281   return DAG.getLoad(ArgVT, dl,
15282                      Chain,
15283                      VAARG,
15284                      MachinePointerInfo(),
15285                      false, false, false, 0);
15286 }
15287
15288 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15289                            SelectionDAG &DAG) {
15290   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15291   // where a va_list is still an i8*.
15292   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15293   if (Subtarget->isCallingConvWin64(
15294         DAG.getMachineFunction().getFunction()->getCallingConv()))
15295     // Probably a Win64 va_copy.
15296     return DAG.expandVACopy(Op.getNode());
15297
15298   SDValue Chain = Op.getOperand(0);
15299   SDValue DstPtr = Op.getOperand(1);
15300   SDValue SrcPtr = Op.getOperand(2);
15301   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15302   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15303   SDLoc DL(Op);
15304
15305   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15306                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15307                        false, false,
15308                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15309 }
15310
15311 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15312 // amount is a constant. Takes immediate version of shift as input.
15313 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15314                                           SDValue SrcOp, uint64_t ShiftAmt,
15315                                           SelectionDAG &DAG) {
15316   MVT ElementType = VT.getVectorElementType();
15317
15318   // Fold this packed shift into its first operand if ShiftAmt is 0.
15319   if (ShiftAmt == 0)
15320     return SrcOp;
15321
15322   // Check for ShiftAmt >= element width
15323   if (ShiftAmt >= ElementType.getSizeInBits()) {
15324     if (Opc == X86ISD::VSRAI)
15325       ShiftAmt = ElementType.getSizeInBits() - 1;
15326     else
15327       return DAG.getConstant(0, dl, VT);
15328   }
15329
15330   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15331          && "Unknown target vector shift-by-constant node");
15332
15333   // Fold this packed vector shift into a build vector if SrcOp is a
15334   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15335   if (VT == SrcOp.getSimpleValueType() &&
15336       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15337     SmallVector<SDValue, 8> Elts;
15338     unsigned NumElts = SrcOp->getNumOperands();
15339     ConstantSDNode *ND;
15340
15341     switch(Opc) {
15342     default: llvm_unreachable(nullptr);
15343     case X86ISD::VSHLI:
15344       for (unsigned i=0; i!=NumElts; ++i) {
15345         SDValue CurrentOp = SrcOp->getOperand(i);
15346         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15347           Elts.push_back(CurrentOp);
15348           continue;
15349         }
15350         ND = cast<ConstantSDNode>(CurrentOp);
15351         const APInt &C = ND->getAPIntValue();
15352         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15353       }
15354       break;
15355     case X86ISD::VSRLI:
15356       for (unsigned i=0; i!=NumElts; ++i) {
15357         SDValue CurrentOp = SrcOp->getOperand(i);
15358         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15359           Elts.push_back(CurrentOp);
15360           continue;
15361         }
15362         ND = cast<ConstantSDNode>(CurrentOp);
15363         const APInt &C = ND->getAPIntValue();
15364         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15365       }
15366       break;
15367     case X86ISD::VSRAI:
15368       for (unsigned i=0; i!=NumElts; ++i) {
15369         SDValue CurrentOp = SrcOp->getOperand(i);
15370         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15371           Elts.push_back(CurrentOp);
15372           continue;
15373         }
15374         ND = cast<ConstantSDNode>(CurrentOp);
15375         const APInt &C = ND->getAPIntValue();
15376         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15377       }
15378       break;
15379     }
15380
15381     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15382   }
15383
15384   return DAG.getNode(Opc, dl, VT, SrcOp,
15385                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15386 }
15387
15388 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15389 // may or may not be a constant. Takes immediate version of shift as input.
15390 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15391                                    SDValue SrcOp, SDValue ShAmt,
15392                                    SelectionDAG &DAG) {
15393   MVT SVT = ShAmt.getSimpleValueType();
15394   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15395
15396   // Catch shift-by-constant.
15397   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15398     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15399                                       CShAmt->getZExtValue(), DAG);
15400
15401   // Change opcode to non-immediate version
15402   switch (Opc) {
15403     default: llvm_unreachable("Unknown target vector shift node");
15404     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15405     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15406     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15407   }
15408
15409   const X86Subtarget &Subtarget =
15410       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15411   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15412       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15413     // Let the shuffle legalizer expand this shift amount node.
15414     SDValue Op0 = ShAmt.getOperand(0);
15415     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15416     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15417   } else {
15418     // Need to build a vector containing shift amount.
15419     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15420     SmallVector<SDValue, 4> ShOps;
15421     ShOps.push_back(ShAmt);
15422     if (SVT == MVT::i32) {
15423       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15424       ShOps.push_back(DAG.getUNDEF(SVT));
15425     }
15426     ShOps.push_back(DAG.getUNDEF(SVT));
15427
15428     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15429     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15430   }
15431
15432   // The return type has to be a 128-bit type with the same element
15433   // type as the input type.
15434   MVT EltVT = VT.getVectorElementType();
15435   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15436
15437   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15438   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15439 }
15440
15441 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15442 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15443 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15444 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15445                                     SDValue PreservedSrc,
15446                                     const X86Subtarget *Subtarget,
15447                                     SelectionDAG &DAG) {
15448     EVT VT = Op.getValueType();
15449     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15450                                   MVT::i1, VT.getVectorNumElements());
15451     SDValue VMask = SDValue();
15452     unsigned OpcodeSelect = ISD::VSELECT;
15453     SDLoc dl(Op);
15454
15455     assert(MaskVT.isSimple() && "invalid mask type");
15456
15457     if (isAllOnes(Mask))
15458       return Op;
15459
15460     if (MaskVT.bitsGT(Mask.getValueType())) {
15461       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15462                                          MaskVT.getSizeInBits());
15463       VMask = DAG.getBitcast(MaskVT,
15464                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15465     } else {
15466       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15467                                        Mask.getValueType().getSizeInBits());
15468       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15469       // are extracted by EXTRACT_SUBVECTOR.
15470       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15471                           DAG.getBitcast(BitcastVT, Mask),
15472                           DAG.getIntPtrConstant(0, dl));
15473     }
15474
15475     switch (Op.getOpcode()) {
15476       default: break;
15477       case X86ISD::PCMPEQM:
15478       case X86ISD::PCMPGTM:
15479       case X86ISD::CMPM:
15480       case X86ISD::CMPMU:
15481         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15482       case X86ISD::VTRUNC:
15483       case X86ISD::VTRUNCS:
15484       case X86ISD::VTRUNCUS:
15485         // We can't use ISD::VSELECT here because it is not always "Legal"
15486         // for the destination type. For example vpmovqb require only AVX512
15487         // and vselect that can operate on byte element type require BWI
15488         OpcodeSelect = X86ISD::SELECT;
15489         break;
15490     }
15491     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15492       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15493     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15494 }
15495
15496 /// \brief Creates an SDNode for a predicated scalar operation.
15497 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15498 /// The mask is coming as MVT::i8 and it should be truncated
15499 /// to MVT::i1 while lowering masking intrinsics.
15500 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15501 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15502 /// for a scalar instruction.
15503 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15504                                     SDValue PreservedSrc,
15505                                     const X86Subtarget *Subtarget,
15506                                     SelectionDAG &DAG) {
15507     if (isAllOnes(Mask))
15508       return Op;
15509
15510     EVT VT = Op.getValueType();
15511     SDLoc dl(Op);
15512     // The mask should be of type MVT::i1
15513     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15514
15515     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15516       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15517     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15518 }
15519
15520 static int getSEHRegistrationNodeSize(const Function *Fn) {
15521   if (!Fn->hasPersonalityFn())
15522     report_fatal_error(
15523         "querying registration node size for function without personality");
15524   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15525   // WinEHStatePass for the full struct definition.
15526   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15527   case EHPersonality::MSVC_X86SEH: return 24;
15528   case EHPersonality::MSVC_CXX: return 16;
15529   default: break;
15530   }
15531   report_fatal_error("can only recover FP for MSVC EH personality functions");
15532 }
15533
15534 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15535 /// function or when returning to a parent frame after catching an exception, we
15536 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15537 /// Here's the math:
15538 ///   RegNodeBase = EntryEBP - RegNodeSize
15539 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15540 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15541 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15542 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15543                                    SDValue EntryEBP) {
15544   MachineFunction &MF = DAG.getMachineFunction();
15545   SDLoc dl;
15546
15547   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15548   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15549
15550   // It's possible that the parent function no longer has a personality function
15551   // if the exceptional code was optimized away, in which case we just return
15552   // the incoming EBP.
15553   if (!Fn->hasPersonalityFn())
15554     return EntryEBP;
15555
15556   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15557
15558   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15559   // registration.
15560   MCSymbol *OffsetSym =
15561       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15562           GlobalValue::getRealLinkageName(Fn->getName()));
15563   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15564   SDValue RegNodeFrameOffset =
15565       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15566
15567   // RegNodeBase = EntryEBP - RegNodeSize
15568   // ParentFP = RegNodeBase - RegNodeFrameOffset
15569   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15570                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15571   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15572 }
15573
15574 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15575                                        SelectionDAG &DAG) {
15576   SDLoc dl(Op);
15577   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15578   EVT VT = Op.getValueType();
15579   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15580   if (IntrData) {
15581     switch(IntrData->Type) {
15582     case INTR_TYPE_1OP:
15583       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15584     case INTR_TYPE_2OP:
15585       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15586         Op.getOperand(2));
15587     case INTR_TYPE_2OP_IMM8:
15588       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15589                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
15590     case INTR_TYPE_3OP:
15591       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15592         Op.getOperand(2), Op.getOperand(3));
15593     case INTR_TYPE_4OP:
15594       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15595         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15596     case INTR_TYPE_1OP_MASK_RM: {
15597       SDValue Src = Op.getOperand(1);
15598       SDValue PassThru = Op.getOperand(2);
15599       SDValue Mask = Op.getOperand(3);
15600       SDValue RoundingMode;
15601       // We allways add rounding mode to the Node.
15602       // If the rounding mode is not specified, we add the
15603       // "current direction" mode.
15604       if (Op.getNumOperands() == 4)
15605         RoundingMode =
15606           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15607       else
15608         RoundingMode = Op.getOperand(4);
15609       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15610       if (IntrWithRoundingModeOpcode != 0)
15611         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15612             X86::STATIC_ROUNDING::CUR_DIRECTION)
15613           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15614                                       dl, Op.getValueType(), Src, RoundingMode),
15615                                       Mask, PassThru, Subtarget, DAG);
15616       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15617                                               RoundingMode),
15618                                   Mask, PassThru, Subtarget, DAG);
15619     }
15620     case INTR_TYPE_1OP_MASK: {
15621       SDValue Src = Op.getOperand(1);
15622       SDValue PassThru = Op.getOperand(2);
15623       SDValue Mask = Op.getOperand(3);
15624       // We add rounding mode to the Node when
15625       //   - RM Opcode is specified and
15626       //   - RM is not "current direction".
15627       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15628       if (IntrWithRoundingModeOpcode != 0) {
15629         SDValue Rnd = Op.getOperand(4);
15630         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15631         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15632           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15633                                       dl, Op.getValueType(),
15634                                       Src, Rnd),
15635                                       Mask, PassThru, Subtarget, DAG);
15636         }
15637       }
15638       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15639                                   Mask, PassThru, Subtarget, DAG);
15640     }
15641     case INTR_TYPE_SCALAR_MASK_RM: {
15642       SDValue Src1 = Op.getOperand(1);
15643       SDValue Src2 = Op.getOperand(2);
15644       SDValue Src0 = Op.getOperand(3);
15645       SDValue Mask = Op.getOperand(4);
15646       // There are 2 kinds of intrinsics in this group:
15647       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15648       // (2) With rounding mode and sae - 7 operands.
15649       if (Op.getNumOperands() == 6) {
15650         SDValue Sae  = Op.getOperand(5);
15651         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15652         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15653                                                 Sae),
15654                                     Mask, Src0, Subtarget, DAG);
15655       }
15656       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15657       SDValue RoundingMode  = Op.getOperand(5);
15658       SDValue Sae  = Op.getOperand(6);
15659       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15660                                               RoundingMode, Sae),
15661                                   Mask, Src0, Subtarget, DAG);
15662     }
15663     case INTR_TYPE_2OP_MASK: {
15664       SDValue Src1 = Op.getOperand(1);
15665       SDValue Src2 = Op.getOperand(2);
15666       SDValue PassThru = Op.getOperand(3);
15667       SDValue Mask = Op.getOperand(4);
15668       // We specify 2 possible opcodes for intrinsics with rounding modes.
15669       // First, we check if the intrinsic may have non-default rounding mode,
15670       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15671       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15672       if (IntrWithRoundingModeOpcode != 0) {
15673         SDValue Rnd = Op.getOperand(5);
15674         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15675         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15676           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15677                                       dl, Op.getValueType(),
15678                                       Src1, Src2, Rnd),
15679                                       Mask, PassThru, Subtarget, DAG);
15680         }
15681       }
15682       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15683                                               Src1,Src2),
15684                                   Mask, PassThru, Subtarget, DAG);
15685     }
15686     case INTR_TYPE_2OP_MASK_RM: {
15687       SDValue Src1 = Op.getOperand(1);
15688       SDValue Src2 = Op.getOperand(2);
15689       SDValue PassThru = Op.getOperand(3);
15690       SDValue Mask = Op.getOperand(4);
15691       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15692       // First, we check if the intrinsic have rounding mode (6 operands),
15693       // if not, we set rounding mode to "current".
15694       SDValue Rnd;
15695       if (Op.getNumOperands() == 6)
15696         Rnd = Op.getOperand(5);
15697       else
15698         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15699       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15700                                               Src1, Src2, Rnd),
15701                                   Mask, PassThru, Subtarget, DAG);
15702     }
15703     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
15704       SDValue Src1 = Op.getOperand(1);
15705       SDValue Src2 = Op.getOperand(2);
15706       SDValue Src3 = Op.getOperand(3);
15707       SDValue PassThru = Op.getOperand(4);
15708       SDValue Mask = Op.getOperand(5);
15709       SDValue Sae  = Op.getOperand(6);
15710
15711       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
15712                                               Src2, Src3, Sae),
15713                                   Mask, PassThru, Subtarget, DAG);
15714     }
15715     case INTR_TYPE_3OP_MASK_RM: {
15716       SDValue Src1 = Op.getOperand(1);
15717       SDValue Src2 = Op.getOperand(2);
15718       SDValue Imm = Op.getOperand(3);
15719       SDValue PassThru = Op.getOperand(4);
15720       SDValue Mask = Op.getOperand(5);
15721       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15722       // First, we check if the intrinsic have rounding mode (7 operands),
15723       // if not, we set rounding mode to "current".
15724       SDValue Rnd;
15725       if (Op.getNumOperands() == 7)
15726         Rnd = Op.getOperand(6);
15727       else
15728         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15729       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15730         Src1, Src2, Imm, Rnd),
15731         Mask, PassThru, Subtarget, DAG);
15732     }
15733     case INTR_TYPE_3OP_IMM8_MASK:
15734     case INTR_TYPE_3OP_MASK: {
15735       SDValue Src1 = Op.getOperand(1);
15736       SDValue Src2 = Op.getOperand(2);
15737       SDValue Src3 = Op.getOperand(3);
15738       SDValue PassThru = Op.getOperand(4);
15739       SDValue Mask = Op.getOperand(5);
15740
15741       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
15742         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
15743       // We specify 2 possible opcodes for intrinsics with rounding modes.
15744       // First, we check if the intrinsic may have non-default rounding mode,
15745       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15746       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15747       if (IntrWithRoundingModeOpcode != 0) {
15748         SDValue Rnd = Op.getOperand(6);
15749         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15750         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15751           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15752                                       dl, Op.getValueType(),
15753                                       Src1, Src2, Src3, Rnd),
15754                                       Mask, PassThru, Subtarget, DAG);
15755         }
15756       }
15757       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15758                                               Src1, Src2, Src3),
15759                                   Mask, PassThru, Subtarget, DAG);
15760     }
15761     case VPERM_3OP_MASKZ:
15762     case VPERM_3OP_MASK:
15763     case FMA_OP_MASK3:
15764     case FMA_OP_MASKZ:
15765     case FMA_OP_MASK: {
15766       SDValue Src1 = Op.getOperand(1);
15767       SDValue Src2 = Op.getOperand(2);
15768       SDValue Src3 = Op.getOperand(3);
15769       SDValue Mask = Op.getOperand(4);
15770       EVT VT = Op.getValueType();
15771       SDValue PassThru = SDValue();
15772
15773       // set PassThru element
15774       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15775         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15776       else if (IntrData->Type == FMA_OP_MASK3)
15777         PassThru = Src3;
15778       else
15779         PassThru = Src1;
15780
15781       // We specify 2 possible opcodes for intrinsics with rounding modes.
15782       // First, we check if the intrinsic may have non-default rounding mode,
15783       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15784       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15785       if (IntrWithRoundingModeOpcode != 0) {
15786         SDValue Rnd = Op.getOperand(5);
15787         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15788             X86::STATIC_ROUNDING::CUR_DIRECTION)
15789           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15790                                                   dl, Op.getValueType(),
15791                                                   Src1, Src2, Src3, Rnd),
15792                                       Mask, PassThru, Subtarget, DAG);
15793       }
15794       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15795                                               dl, Op.getValueType(),
15796                                               Src1, Src2, Src3),
15797                                   Mask, PassThru, Subtarget, DAG);
15798     }
15799     case CMP_MASK:
15800     case CMP_MASK_CC: {
15801       // Comparison intrinsics with masks.
15802       // Example of transformation:
15803       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15804       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15805       // (i8 (bitcast
15806       //   (v8i1 (insert_subvector undef,
15807       //           (v2i1 (and (PCMPEQM %a, %b),
15808       //                      (extract_subvector
15809       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15810       EVT VT = Op.getOperand(1).getValueType();
15811       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15812                                     VT.getVectorNumElements());
15813       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15814       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15815                                        Mask.getValueType().getSizeInBits());
15816       SDValue Cmp;
15817       if (IntrData->Type == CMP_MASK_CC) {
15818         SDValue CC = Op.getOperand(3);
15819         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15820         // We specify 2 possible opcodes for intrinsics with rounding modes.
15821         // First, we check if the intrinsic may have non-default rounding mode,
15822         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15823         if (IntrData->Opc1 != 0) {
15824           SDValue Rnd = Op.getOperand(5);
15825           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15826               X86::STATIC_ROUNDING::CUR_DIRECTION)
15827             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15828                               Op.getOperand(2), CC, Rnd);
15829         }
15830         //default rounding mode
15831         if(!Cmp.getNode())
15832             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15833                               Op.getOperand(2), CC);
15834
15835       } else {
15836         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15837         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15838                           Op.getOperand(2));
15839       }
15840       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15841                                              DAG.getTargetConstant(0, dl,
15842                                                                    MaskVT),
15843                                              Subtarget, DAG);
15844       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15845                                 DAG.getUNDEF(BitcastVT), CmpMask,
15846                                 DAG.getIntPtrConstant(0, dl));
15847       return DAG.getBitcast(Op.getValueType(), Res);
15848     }
15849     case COMI: { // Comparison intrinsics
15850       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15851       SDValue LHS = Op.getOperand(1);
15852       SDValue RHS = Op.getOperand(2);
15853       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15854       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15855       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15856       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15857                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15858       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15859     }
15860     case VSHIFT:
15861       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15862                                  Op.getOperand(1), Op.getOperand(2), DAG);
15863     case VSHIFT_MASK:
15864       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15865                                                       Op.getSimpleValueType(),
15866                                                       Op.getOperand(1),
15867                                                       Op.getOperand(2), DAG),
15868                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15869                                   DAG);
15870     case COMPRESS_EXPAND_IN_REG: {
15871       SDValue Mask = Op.getOperand(3);
15872       SDValue DataToCompress = Op.getOperand(1);
15873       SDValue PassThru = Op.getOperand(2);
15874       if (isAllOnes(Mask)) // return data as is
15875         return Op.getOperand(1);
15876
15877       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15878                                               DataToCompress),
15879                                   Mask, PassThru, Subtarget, DAG);
15880     }
15881     case BLEND: {
15882       SDValue Mask = Op.getOperand(3);
15883       EVT VT = Op.getValueType();
15884       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15885                                     VT.getVectorNumElements());
15886       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15887                                        Mask.getValueType().getSizeInBits());
15888       SDLoc dl(Op);
15889       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15890                                   DAG.getBitcast(BitcastVT, Mask),
15891                                   DAG.getIntPtrConstant(0, dl));
15892       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15893                          Op.getOperand(2));
15894     }
15895     default:
15896       break;
15897     }
15898   }
15899
15900   switch (IntNo) {
15901   default: return SDValue();    // Don't custom lower most intrinsics.
15902
15903   case Intrinsic::x86_avx2_permd:
15904   case Intrinsic::x86_avx2_permps:
15905     // Operands intentionally swapped. Mask is last operand to intrinsic,
15906     // but second operand for node/instruction.
15907     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15908                        Op.getOperand(2), Op.getOperand(1));
15909
15910   // ptest and testp intrinsics. The intrinsic these come from are designed to
15911   // return an integer value, not just an instruction so lower it to the ptest
15912   // or testp pattern and a setcc for the result.
15913   case Intrinsic::x86_sse41_ptestz:
15914   case Intrinsic::x86_sse41_ptestc:
15915   case Intrinsic::x86_sse41_ptestnzc:
15916   case Intrinsic::x86_avx_ptestz_256:
15917   case Intrinsic::x86_avx_ptestc_256:
15918   case Intrinsic::x86_avx_ptestnzc_256:
15919   case Intrinsic::x86_avx_vtestz_ps:
15920   case Intrinsic::x86_avx_vtestc_ps:
15921   case Intrinsic::x86_avx_vtestnzc_ps:
15922   case Intrinsic::x86_avx_vtestz_pd:
15923   case Intrinsic::x86_avx_vtestc_pd:
15924   case Intrinsic::x86_avx_vtestnzc_pd:
15925   case Intrinsic::x86_avx_vtestz_ps_256:
15926   case Intrinsic::x86_avx_vtestc_ps_256:
15927   case Intrinsic::x86_avx_vtestnzc_ps_256:
15928   case Intrinsic::x86_avx_vtestz_pd_256:
15929   case Intrinsic::x86_avx_vtestc_pd_256:
15930   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15931     bool IsTestPacked = false;
15932     unsigned X86CC;
15933     switch (IntNo) {
15934     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15935     case Intrinsic::x86_avx_vtestz_ps:
15936     case Intrinsic::x86_avx_vtestz_pd:
15937     case Intrinsic::x86_avx_vtestz_ps_256:
15938     case Intrinsic::x86_avx_vtestz_pd_256:
15939       IsTestPacked = true; // Fallthrough
15940     case Intrinsic::x86_sse41_ptestz:
15941     case Intrinsic::x86_avx_ptestz_256:
15942       // ZF = 1
15943       X86CC = X86::COND_E;
15944       break;
15945     case Intrinsic::x86_avx_vtestc_ps:
15946     case Intrinsic::x86_avx_vtestc_pd:
15947     case Intrinsic::x86_avx_vtestc_ps_256:
15948     case Intrinsic::x86_avx_vtestc_pd_256:
15949       IsTestPacked = true; // Fallthrough
15950     case Intrinsic::x86_sse41_ptestc:
15951     case Intrinsic::x86_avx_ptestc_256:
15952       // CF = 1
15953       X86CC = X86::COND_B;
15954       break;
15955     case Intrinsic::x86_avx_vtestnzc_ps:
15956     case Intrinsic::x86_avx_vtestnzc_pd:
15957     case Intrinsic::x86_avx_vtestnzc_ps_256:
15958     case Intrinsic::x86_avx_vtestnzc_pd_256:
15959       IsTestPacked = true; // Fallthrough
15960     case Intrinsic::x86_sse41_ptestnzc:
15961     case Intrinsic::x86_avx_ptestnzc_256:
15962       // ZF and CF = 0
15963       X86CC = X86::COND_A;
15964       break;
15965     }
15966
15967     SDValue LHS = Op.getOperand(1);
15968     SDValue RHS = Op.getOperand(2);
15969     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15970     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15971     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15972     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15973     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15974   }
15975   case Intrinsic::x86_avx512_kortestz_w:
15976   case Intrinsic::x86_avx512_kortestc_w: {
15977     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15978     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15979     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15980     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15981     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15982     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15983     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15984   }
15985
15986   case Intrinsic::x86_sse42_pcmpistria128:
15987   case Intrinsic::x86_sse42_pcmpestria128:
15988   case Intrinsic::x86_sse42_pcmpistric128:
15989   case Intrinsic::x86_sse42_pcmpestric128:
15990   case Intrinsic::x86_sse42_pcmpistrio128:
15991   case Intrinsic::x86_sse42_pcmpestrio128:
15992   case Intrinsic::x86_sse42_pcmpistris128:
15993   case Intrinsic::x86_sse42_pcmpestris128:
15994   case Intrinsic::x86_sse42_pcmpistriz128:
15995   case Intrinsic::x86_sse42_pcmpestriz128: {
15996     unsigned Opcode;
15997     unsigned X86CC;
15998     switch (IntNo) {
15999     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16000     case Intrinsic::x86_sse42_pcmpistria128:
16001       Opcode = X86ISD::PCMPISTRI;
16002       X86CC = X86::COND_A;
16003       break;
16004     case Intrinsic::x86_sse42_pcmpestria128:
16005       Opcode = X86ISD::PCMPESTRI;
16006       X86CC = X86::COND_A;
16007       break;
16008     case Intrinsic::x86_sse42_pcmpistric128:
16009       Opcode = X86ISD::PCMPISTRI;
16010       X86CC = X86::COND_B;
16011       break;
16012     case Intrinsic::x86_sse42_pcmpestric128:
16013       Opcode = X86ISD::PCMPESTRI;
16014       X86CC = X86::COND_B;
16015       break;
16016     case Intrinsic::x86_sse42_pcmpistrio128:
16017       Opcode = X86ISD::PCMPISTRI;
16018       X86CC = X86::COND_O;
16019       break;
16020     case Intrinsic::x86_sse42_pcmpestrio128:
16021       Opcode = X86ISD::PCMPESTRI;
16022       X86CC = X86::COND_O;
16023       break;
16024     case Intrinsic::x86_sse42_pcmpistris128:
16025       Opcode = X86ISD::PCMPISTRI;
16026       X86CC = X86::COND_S;
16027       break;
16028     case Intrinsic::x86_sse42_pcmpestris128:
16029       Opcode = X86ISD::PCMPESTRI;
16030       X86CC = X86::COND_S;
16031       break;
16032     case Intrinsic::x86_sse42_pcmpistriz128:
16033       Opcode = X86ISD::PCMPISTRI;
16034       X86CC = X86::COND_E;
16035       break;
16036     case Intrinsic::x86_sse42_pcmpestriz128:
16037       Opcode = X86ISD::PCMPESTRI;
16038       X86CC = X86::COND_E;
16039       break;
16040     }
16041     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16042     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16043     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16044     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16045                                 DAG.getConstant(X86CC, dl, MVT::i8),
16046                                 SDValue(PCMP.getNode(), 1));
16047     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16048   }
16049
16050   case Intrinsic::x86_sse42_pcmpistri128:
16051   case Intrinsic::x86_sse42_pcmpestri128: {
16052     unsigned Opcode;
16053     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16054       Opcode = X86ISD::PCMPISTRI;
16055     else
16056       Opcode = X86ISD::PCMPESTRI;
16057
16058     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16059     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16060     return DAG.getNode(Opcode, dl, VTs, NewOps);
16061   }
16062
16063   case Intrinsic::x86_seh_lsda: {
16064     // Compute the symbol for the LSDA. We know it'll get emitted later.
16065     MachineFunction &MF = DAG.getMachineFunction();
16066     SDValue Op1 = Op.getOperand(1);
16067     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16068     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16069         GlobalValue::getRealLinkageName(Fn->getName()));
16070
16071     // Generate a simple absolute symbol reference. This intrinsic is only
16072     // supported on 32-bit Windows, which isn't PIC.
16073     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16074     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16075   }
16076
16077   case Intrinsic::x86_seh_recoverfp: {
16078     SDValue FnOp = Op.getOperand(1);
16079     SDValue IncomingFPOp = Op.getOperand(2);
16080     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16081     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16082     if (!Fn)
16083       report_fatal_error(
16084           "llvm.x86.seh.recoverfp must take a function as the first argument");
16085     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16086   }
16087
16088   case Intrinsic::localaddress: {
16089     // Returns one of the stack, base, or frame pointer registers, depending on
16090     // which is used to reference local variables.
16091     MachineFunction &MF = DAG.getMachineFunction();
16092     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16093     unsigned Reg;
16094     if (RegInfo->hasBasePointer(MF))
16095       Reg = RegInfo->getBaseRegister();
16096     else // This function handles the SP or FP case.
16097       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16098     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16099   }
16100   }
16101 }
16102
16103 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16104                               SDValue Src, SDValue Mask, SDValue Base,
16105                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16106                               const X86Subtarget * Subtarget) {
16107   SDLoc dl(Op);
16108   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16109   if (!C)
16110     llvm_unreachable("Invalid scale type");
16111   unsigned ScaleVal = C->getZExtValue();
16112   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16113     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16114
16115   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16116   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16117                              Index.getSimpleValueType().getVectorNumElements());
16118   SDValue MaskInReg;
16119   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16120   if (MaskC)
16121     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16122   else {
16123     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16124                                      Mask.getValueType().getSizeInBits());
16125
16126     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16127     // are extracted by EXTRACT_SUBVECTOR.
16128     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16129                             DAG.getBitcast(BitcastVT, Mask),
16130                             DAG.getIntPtrConstant(0, dl));
16131   }
16132   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16133   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16134   SDValue Segment = DAG.getRegister(0, MVT::i32);
16135   if (Src.getOpcode() == ISD::UNDEF)
16136     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16137   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16138   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16139   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16140   return DAG.getMergeValues(RetOps, dl);
16141 }
16142
16143 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16144                                SDValue Src, SDValue Mask, SDValue Base,
16145                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16146   SDLoc dl(Op);
16147   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16148   if (!C)
16149     llvm_unreachable("Invalid scale type");
16150   unsigned ScaleVal = C->getZExtValue();
16151   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16152     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16153
16154   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16155   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16156   SDValue Segment = DAG.getRegister(0, MVT::i32);
16157   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16158                              Index.getSimpleValueType().getVectorNumElements());
16159   SDValue MaskInReg;
16160   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16161   if (MaskC)
16162     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16163   else {
16164     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16165                                      Mask.getValueType().getSizeInBits());
16166
16167     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16168     // are extracted by EXTRACT_SUBVECTOR.
16169     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16170                             DAG.getBitcast(BitcastVT, Mask),
16171                             DAG.getIntPtrConstant(0, dl));
16172   }
16173   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16174   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16175   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16176   return SDValue(Res, 1);
16177 }
16178
16179 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16180                                SDValue Mask, SDValue Base, SDValue Index,
16181                                SDValue ScaleOp, SDValue Chain) {
16182   SDLoc dl(Op);
16183   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16184   assert(C && "Invalid scale type");
16185   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16186   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16187   SDValue Segment = DAG.getRegister(0, MVT::i32);
16188   EVT MaskVT =
16189     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16190   SDValue MaskInReg;
16191   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16192   if (MaskC)
16193     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16194   else
16195     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16196   //SDVTList VTs = DAG.getVTList(MVT::Other);
16197   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16198   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16199   return SDValue(Res, 0);
16200 }
16201
16202 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16203 // read performance monitor counters (x86_rdpmc).
16204 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16205                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16206                               SmallVectorImpl<SDValue> &Results) {
16207   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16208   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16209   SDValue LO, HI;
16210
16211   // The ECX register is used to select the index of the performance counter
16212   // to read.
16213   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16214                                    N->getOperand(2));
16215   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16216
16217   // Reads the content of a 64-bit performance counter and returns it in the
16218   // registers EDX:EAX.
16219   if (Subtarget->is64Bit()) {
16220     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16221     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16222                             LO.getValue(2));
16223   } else {
16224     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16225     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16226                             LO.getValue(2));
16227   }
16228   Chain = HI.getValue(1);
16229
16230   if (Subtarget->is64Bit()) {
16231     // The EAX register is loaded with the low-order 32 bits. The EDX register
16232     // is loaded with the supported high-order bits of the counter.
16233     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16234                               DAG.getConstant(32, DL, MVT::i8));
16235     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16236     Results.push_back(Chain);
16237     return;
16238   }
16239
16240   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16241   SDValue Ops[] = { LO, HI };
16242   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16243   Results.push_back(Pair);
16244   Results.push_back(Chain);
16245 }
16246
16247 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16248 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16249 // also used to custom lower READCYCLECOUNTER nodes.
16250 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16251                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16252                               SmallVectorImpl<SDValue> &Results) {
16253   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16254   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16255   SDValue LO, HI;
16256
16257   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16258   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16259   // and the EAX register is loaded with the low-order 32 bits.
16260   if (Subtarget->is64Bit()) {
16261     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16262     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16263                             LO.getValue(2));
16264   } else {
16265     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16266     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16267                             LO.getValue(2));
16268   }
16269   SDValue Chain = HI.getValue(1);
16270
16271   if (Opcode == X86ISD::RDTSCP_DAG) {
16272     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16273
16274     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16275     // the ECX register. Add 'ecx' explicitly to the chain.
16276     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16277                                      HI.getValue(2));
16278     // Explicitly store the content of ECX at the location passed in input
16279     // to the 'rdtscp' intrinsic.
16280     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16281                          MachinePointerInfo(), false, false, 0);
16282   }
16283
16284   if (Subtarget->is64Bit()) {
16285     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16286     // the EAX register is loaded with the low-order 32 bits.
16287     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16288                               DAG.getConstant(32, DL, MVT::i8));
16289     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16290     Results.push_back(Chain);
16291     return;
16292   }
16293
16294   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16295   SDValue Ops[] = { LO, HI };
16296   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16297   Results.push_back(Pair);
16298   Results.push_back(Chain);
16299 }
16300
16301 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16302                                      SelectionDAG &DAG) {
16303   SmallVector<SDValue, 2> Results;
16304   SDLoc DL(Op);
16305   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16306                           Results);
16307   return DAG.getMergeValues(Results, DL);
16308 }
16309
16310 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16311                                     SelectionDAG &DAG) {
16312   MachineFunction &MF = DAG.getMachineFunction();
16313   const Function *Fn = MF.getFunction();
16314   SDLoc dl(Op);
16315   SDValue Chain = Op.getOperand(0);
16316
16317   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16318          "using llvm.x86.seh.restoreframe requires a frame pointer");
16319
16320   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16321   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16322
16323   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16324   unsigned FrameReg =
16325       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16326   unsigned SPReg = RegInfo->getStackRegister();
16327   unsigned SlotSize = RegInfo->getSlotSize();
16328
16329   // Get incoming EBP.
16330   SDValue IncomingEBP =
16331       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16332
16333   // SP is saved in the first field of every registration node, so load
16334   // [EBP-RegNodeSize] into SP.
16335   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16336   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16337                                DAG.getConstant(-RegNodeSize, dl, VT));
16338   SDValue NewSP =
16339       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16340                   false, VT.getScalarSizeInBits() / 8);
16341   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16342
16343   if (!RegInfo->needsStackRealignment(MF)) {
16344     // Adjust EBP to point back to the original frame position.
16345     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16346     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16347   } else {
16348     assert(RegInfo->hasBasePointer(MF) &&
16349            "functions with Win32 EH must use frame or base pointer register");
16350
16351     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16352     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16353     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16354
16355     // Reload the spilled EBP value, now that the stack and base pointers are
16356     // set up.
16357     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16358     X86FI->setHasSEHFramePtrSave(true);
16359     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16360     X86FI->setSEHFramePtrSaveIndex(FI);
16361     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16362                                 MachinePointerInfo(), false, false, false,
16363                                 VT.getScalarSizeInBits() / 8);
16364     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16365   }
16366
16367   return Chain;
16368 }
16369
16370 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16371 /// return truncate Store/MaskedStore Node
16372 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16373                                                SelectionDAG &DAG,
16374                                                MVT ElementType) {
16375   SDLoc dl(Op);
16376   SDValue Mask = Op.getOperand(4);
16377   SDValue DataToTruncate = Op.getOperand(3);
16378   SDValue Addr = Op.getOperand(2);
16379   SDValue Chain = Op.getOperand(0);
16380
16381   EVT VT  = DataToTruncate.getValueType();
16382   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16383                              ElementType, VT.getVectorNumElements());
16384
16385   if (isAllOnes(Mask)) // return just a truncate store
16386     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16387                              MachinePointerInfo(), SVT, false, false,
16388                              SVT.getScalarSizeInBits()/8);
16389
16390   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16391                                 MVT::i1, VT.getVectorNumElements());
16392   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16393                                    Mask.getValueType().getSizeInBits());
16394   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16395   // are extracted by EXTRACT_SUBVECTOR.
16396   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16397                               DAG.getBitcast(BitcastVT, Mask),
16398                               DAG.getIntPtrConstant(0, dl));
16399
16400   MachineMemOperand *MMO = DAG.getMachineFunction().
16401     getMachineMemOperand(MachinePointerInfo(),
16402                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16403                          SVT.getScalarSizeInBits()/8);
16404
16405   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16406                             VMask, SVT, MMO, true);
16407 }
16408
16409 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16410                                       SelectionDAG &DAG) {
16411   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16412
16413   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16414   if (!IntrData) {
16415     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16416       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16417     return SDValue();
16418   }
16419
16420   SDLoc dl(Op);
16421   switch(IntrData->Type) {
16422   default:
16423     llvm_unreachable("Unknown Intrinsic Type");
16424     break;
16425   case RDSEED:
16426   case RDRAND: {
16427     // Emit the node with the right value type.
16428     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16429     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16430
16431     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16432     // Otherwise return the value from Rand, which is always 0, casted to i32.
16433     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16434                       DAG.getConstant(1, dl, Op->getValueType(1)),
16435                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16436                       SDValue(Result.getNode(), 1) };
16437     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16438                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16439                                   Ops);
16440
16441     // Return { result, isValid, chain }.
16442     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16443                        SDValue(Result.getNode(), 2));
16444   }
16445   case GATHER: {
16446   //gather(v1, mask, index, base, scale);
16447     SDValue Chain = Op.getOperand(0);
16448     SDValue Src   = Op.getOperand(2);
16449     SDValue Base  = Op.getOperand(3);
16450     SDValue Index = Op.getOperand(4);
16451     SDValue Mask  = Op.getOperand(5);
16452     SDValue Scale = Op.getOperand(6);
16453     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16454                          Chain, Subtarget);
16455   }
16456   case SCATTER: {
16457   //scatter(base, mask, index, v1, scale);
16458     SDValue Chain = Op.getOperand(0);
16459     SDValue Base  = Op.getOperand(2);
16460     SDValue Mask  = Op.getOperand(3);
16461     SDValue Index = Op.getOperand(4);
16462     SDValue Src   = Op.getOperand(5);
16463     SDValue Scale = Op.getOperand(6);
16464     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16465                           Scale, Chain);
16466   }
16467   case PREFETCH: {
16468     SDValue Hint = Op.getOperand(6);
16469     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16470     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16471     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16472     SDValue Chain = Op.getOperand(0);
16473     SDValue Mask  = Op.getOperand(2);
16474     SDValue Index = Op.getOperand(3);
16475     SDValue Base  = Op.getOperand(4);
16476     SDValue Scale = Op.getOperand(5);
16477     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16478   }
16479   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16480   case RDTSC: {
16481     SmallVector<SDValue, 2> Results;
16482     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16483                             Results);
16484     return DAG.getMergeValues(Results, dl);
16485   }
16486   // Read Performance Monitoring Counters.
16487   case RDPMC: {
16488     SmallVector<SDValue, 2> Results;
16489     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16490     return DAG.getMergeValues(Results, dl);
16491   }
16492   // XTEST intrinsics.
16493   case XTEST: {
16494     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16495     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16496     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16497                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16498                                 InTrans);
16499     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16500     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16501                        Ret, SDValue(InTrans.getNode(), 1));
16502   }
16503   // ADC/ADCX/SBB
16504   case ADX: {
16505     SmallVector<SDValue, 2> Results;
16506     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16507     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16508     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16509                                 DAG.getConstant(-1, dl, MVT::i8));
16510     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16511                               Op.getOperand(4), GenCF.getValue(1));
16512     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16513                                  Op.getOperand(5), MachinePointerInfo(),
16514                                  false, false, 0);
16515     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16516                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16517                                 Res.getValue(1));
16518     Results.push_back(SetCC);
16519     Results.push_back(Store);
16520     return DAG.getMergeValues(Results, dl);
16521   }
16522   case COMPRESS_TO_MEM: {
16523     SDLoc dl(Op);
16524     SDValue Mask = Op.getOperand(4);
16525     SDValue DataToCompress = Op.getOperand(3);
16526     SDValue Addr = Op.getOperand(2);
16527     SDValue Chain = Op.getOperand(0);
16528
16529     EVT VT = DataToCompress.getValueType();
16530     if (isAllOnes(Mask)) // return just a store
16531       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16532                           MachinePointerInfo(), false, false,
16533                           VT.getScalarSizeInBits()/8);
16534
16535     SDValue Compressed =
16536       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16537                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16538     return DAG.getStore(Chain, dl, Compressed, Addr,
16539                         MachinePointerInfo(), false, false,
16540                         VT.getScalarSizeInBits()/8);
16541   }
16542   case TRUNCATE_TO_MEM_VI8:
16543     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16544   case TRUNCATE_TO_MEM_VI16:
16545     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16546   case TRUNCATE_TO_MEM_VI32:
16547     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16548   case EXPAND_FROM_MEM: {
16549     SDLoc dl(Op);
16550     SDValue Mask = Op.getOperand(4);
16551     SDValue PassThru = Op.getOperand(3);
16552     SDValue Addr = Op.getOperand(2);
16553     SDValue Chain = Op.getOperand(0);
16554     EVT VT = Op.getValueType();
16555
16556     if (isAllOnes(Mask)) // return just a load
16557       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16558                          false, VT.getScalarSizeInBits()/8);
16559
16560     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16561                                        false, false, false,
16562                                        VT.getScalarSizeInBits()/8);
16563
16564     SDValue Results[] = {
16565       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16566                            Mask, PassThru, Subtarget, DAG), Chain};
16567     return DAG.getMergeValues(Results, dl);
16568   }
16569   }
16570 }
16571
16572 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16573                                            SelectionDAG &DAG) const {
16574   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16575   MFI->setReturnAddressIsTaken(true);
16576
16577   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16578     return SDValue();
16579
16580   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16581   SDLoc dl(Op);
16582   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16583
16584   if (Depth > 0) {
16585     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16586     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16587     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16588     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16589                        DAG.getNode(ISD::ADD, dl, PtrVT,
16590                                    FrameAddr, Offset),
16591                        MachinePointerInfo(), false, false, false, 0);
16592   }
16593
16594   // Just load the return address.
16595   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16596   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16597                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16598 }
16599
16600 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16601   MachineFunction &MF = DAG.getMachineFunction();
16602   MachineFrameInfo *MFI = MF.getFrameInfo();
16603   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16604   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16605   EVT VT = Op.getValueType();
16606
16607   MFI->setFrameAddressIsTaken(true);
16608
16609   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16610     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16611     // is not possible to crawl up the stack without looking at the unwind codes
16612     // simultaneously.
16613     int FrameAddrIndex = FuncInfo->getFAIndex();
16614     if (!FrameAddrIndex) {
16615       // Set up a frame object for the return address.
16616       unsigned SlotSize = RegInfo->getSlotSize();
16617       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16618           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16619       FuncInfo->setFAIndex(FrameAddrIndex);
16620     }
16621     return DAG.getFrameIndex(FrameAddrIndex, VT);
16622   }
16623
16624   unsigned FrameReg =
16625       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16626   SDLoc dl(Op);  // FIXME probably not meaningful
16627   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16628   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16629           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16630          "Invalid Frame Register!");
16631   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16632   while (Depth--)
16633     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16634                             MachinePointerInfo(),
16635                             false, false, false, 0);
16636   return FrameAddr;
16637 }
16638
16639 // FIXME? Maybe this could be a TableGen attribute on some registers and
16640 // this table could be generated automatically from RegInfo.
16641 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16642                                               SelectionDAG &DAG) const {
16643   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16644   const MachineFunction &MF = DAG.getMachineFunction();
16645
16646   unsigned Reg = StringSwitch<unsigned>(RegName)
16647                        .Case("esp", X86::ESP)
16648                        .Case("rsp", X86::RSP)
16649                        .Case("ebp", X86::EBP)
16650                        .Case("rbp", X86::RBP)
16651                        .Default(0);
16652
16653   if (Reg == X86::EBP || Reg == X86::RBP) {
16654     if (!TFI.hasFP(MF))
16655       report_fatal_error("register " + StringRef(RegName) +
16656                          " is allocatable: function has no frame pointer");
16657 #ifndef NDEBUG
16658     else {
16659       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16660       unsigned FrameReg =
16661           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16662       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16663              "Invalid Frame Register!");
16664     }
16665 #endif
16666   }
16667
16668   if (Reg)
16669     return Reg;
16670
16671   report_fatal_error("Invalid register name global variable");
16672 }
16673
16674 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16675                                                      SelectionDAG &DAG) const {
16676   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16677   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16678 }
16679
16680 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16681   SDValue Chain     = Op.getOperand(0);
16682   SDValue Offset    = Op.getOperand(1);
16683   SDValue Handler   = Op.getOperand(2);
16684   SDLoc dl      (Op);
16685
16686   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16687   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16688   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16689   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16690           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16691          "Invalid Frame Register!");
16692   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16693   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16694
16695   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16696                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16697                                                        dl));
16698   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16699   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16700                        false, false, 0);
16701   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16702
16703   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16704                      DAG.getRegister(StoreAddrReg, PtrVT));
16705 }
16706
16707 SDValue X86TargetLowering::LowerCATCHRET(SDValue Op, SelectionDAG &DAG) const {
16708   SDValue Chain = Op.getOperand(0);
16709   SDValue Dest = Op.getOperand(1);
16710   SDLoc DL(Op);
16711
16712   MVT PtrVT = getPointerTy(DAG.getDataLayout());
16713   unsigned ReturnReg = (PtrVT == MVT::i64 ? X86::RAX : X86::EAX);
16714
16715   // Load the address of the destination block.
16716   MachineBasicBlock *DestMBB = cast<BasicBlockSDNode>(Dest)->getBasicBlock();
16717   SDValue BlockPtr = DAG.getMCSymbol(DestMBB->getSymbol(), PtrVT);
16718   unsigned WrapperKind =
16719       Subtarget->isPICStyleRIPRel() ? X86ISD::WrapperRIP : X86ISD::Wrapper;
16720   SDValue WrappedPtr = DAG.getNode(WrapperKind, DL, PtrVT, BlockPtr);
16721   Chain = DAG.getCopyToReg(Chain, DL, ReturnReg, WrappedPtr);
16722   return DAG.getNode(X86ISD::CATCHRET, DL, MVT::Other, Chain,
16723                      DAG.getRegister(ReturnReg, PtrVT));
16724 }
16725
16726 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16727                                                SelectionDAG &DAG) const {
16728   SDLoc DL(Op);
16729   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16730                      DAG.getVTList(MVT::i32, MVT::Other),
16731                      Op.getOperand(0), Op.getOperand(1));
16732 }
16733
16734 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16735                                                 SelectionDAG &DAG) const {
16736   SDLoc DL(Op);
16737   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16738                      Op.getOperand(0), Op.getOperand(1));
16739 }
16740
16741 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16742   return Op.getOperand(0);
16743 }
16744
16745 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16746                                                 SelectionDAG &DAG) const {
16747   SDValue Root = Op.getOperand(0);
16748   SDValue Trmp = Op.getOperand(1); // trampoline
16749   SDValue FPtr = Op.getOperand(2); // nested function
16750   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16751   SDLoc dl (Op);
16752
16753   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16754   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16755
16756   if (Subtarget->is64Bit()) {
16757     SDValue OutChains[6];
16758
16759     // Large code-model.
16760     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16761     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16762
16763     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16764     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16765
16766     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16767
16768     // Load the pointer to the nested function into R11.
16769     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16770     SDValue Addr = Trmp;
16771     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16772                                 Addr, MachinePointerInfo(TrmpAddr),
16773                                 false, false, 0);
16774
16775     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16776                        DAG.getConstant(2, dl, MVT::i64));
16777     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16778                                 MachinePointerInfo(TrmpAddr, 2),
16779                                 false, false, 2);
16780
16781     // Load the 'nest' parameter value into R10.
16782     // R10 is specified in X86CallingConv.td
16783     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16784     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16785                        DAG.getConstant(10, dl, MVT::i64));
16786     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16787                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16788                                 false, false, 0);
16789
16790     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16791                        DAG.getConstant(12, dl, MVT::i64));
16792     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16793                                 MachinePointerInfo(TrmpAddr, 12),
16794                                 false, false, 2);
16795
16796     // Jump to the nested function.
16797     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16798     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16799                        DAG.getConstant(20, dl, MVT::i64));
16800     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16801                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16802                                 false, false, 0);
16803
16804     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16805     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16806                        DAG.getConstant(22, dl, MVT::i64));
16807     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16808                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16809                                 false, false, 0);
16810
16811     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16812   } else {
16813     const Function *Func =
16814       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16815     CallingConv::ID CC = Func->getCallingConv();
16816     unsigned NestReg;
16817
16818     switch (CC) {
16819     default:
16820       llvm_unreachable("Unsupported calling convention");
16821     case CallingConv::C:
16822     case CallingConv::X86_StdCall: {
16823       // Pass 'nest' parameter in ECX.
16824       // Must be kept in sync with X86CallingConv.td
16825       NestReg = X86::ECX;
16826
16827       // Check that ECX wasn't needed by an 'inreg' parameter.
16828       FunctionType *FTy = Func->getFunctionType();
16829       const AttributeSet &Attrs = Func->getAttributes();
16830
16831       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16832         unsigned InRegCount = 0;
16833         unsigned Idx = 1;
16834
16835         for (FunctionType::param_iterator I = FTy->param_begin(),
16836              E = FTy->param_end(); I != E; ++I, ++Idx)
16837           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
16838             auto &DL = DAG.getDataLayout();
16839             // FIXME: should only count parameters that are lowered to integers.
16840             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16841           }
16842
16843         if (InRegCount > 2) {
16844           report_fatal_error("Nest register in use - reduce number of inreg"
16845                              " parameters!");
16846         }
16847       }
16848       break;
16849     }
16850     case CallingConv::X86_FastCall:
16851     case CallingConv::X86_ThisCall:
16852     case CallingConv::Fast:
16853       // Pass 'nest' parameter in EAX.
16854       // Must be kept in sync with X86CallingConv.td
16855       NestReg = X86::EAX;
16856       break;
16857     }
16858
16859     SDValue OutChains[4];
16860     SDValue Addr, Disp;
16861
16862     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16863                        DAG.getConstant(10, dl, MVT::i32));
16864     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16865
16866     // This is storing the opcode for MOV32ri.
16867     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16868     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16869     OutChains[0] = DAG.getStore(Root, dl,
16870                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16871                                 Trmp, MachinePointerInfo(TrmpAddr),
16872                                 false, false, 0);
16873
16874     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16875                        DAG.getConstant(1, dl, MVT::i32));
16876     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16877                                 MachinePointerInfo(TrmpAddr, 1),
16878                                 false, false, 1);
16879
16880     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16881     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16882                        DAG.getConstant(5, dl, MVT::i32));
16883     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16884                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16885                                 false, false, 1);
16886
16887     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16888                        DAG.getConstant(6, dl, MVT::i32));
16889     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16890                                 MachinePointerInfo(TrmpAddr, 6),
16891                                 false, false, 1);
16892
16893     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16894   }
16895 }
16896
16897 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16898                                             SelectionDAG &DAG) const {
16899   /*
16900    The rounding mode is in bits 11:10 of FPSR, and has the following
16901    settings:
16902      00 Round to nearest
16903      01 Round to -inf
16904      10 Round to +inf
16905      11 Round to 0
16906
16907   FLT_ROUNDS, on the other hand, expects the following:
16908     -1 Undefined
16909      0 Round to 0
16910      1 Round to nearest
16911      2 Round to +inf
16912      3 Round to -inf
16913
16914   To perform the conversion, we do:
16915     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16916   */
16917
16918   MachineFunction &MF = DAG.getMachineFunction();
16919   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16920   unsigned StackAlignment = TFI.getStackAlignment();
16921   MVT VT = Op.getSimpleValueType();
16922   SDLoc DL(Op);
16923
16924   // Save FP Control Word to stack slot
16925   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16926   SDValue StackSlot =
16927       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16928
16929   MachineMemOperand *MMO =
16930       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
16931                               MachineMemOperand::MOStore, 2, 2);
16932
16933   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16934   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16935                                           DAG.getVTList(MVT::Other),
16936                                           Ops, MVT::i16, MMO);
16937
16938   // Load FP Control Word from stack slot
16939   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16940                             MachinePointerInfo(), false, false, false, 0);
16941
16942   // Transform as necessary
16943   SDValue CWD1 =
16944     DAG.getNode(ISD::SRL, DL, MVT::i16,
16945                 DAG.getNode(ISD::AND, DL, MVT::i16,
16946                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16947                 DAG.getConstant(11, DL, MVT::i8));
16948   SDValue CWD2 =
16949     DAG.getNode(ISD::SRL, DL, MVT::i16,
16950                 DAG.getNode(ISD::AND, DL, MVT::i16,
16951                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16952                 DAG.getConstant(9, DL, MVT::i8));
16953
16954   SDValue RetVal =
16955     DAG.getNode(ISD::AND, DL, MVT::i16,
16956                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16957                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16958                             DAG.getConstant(1, DL, MVT::i16)),
16959                 DAG.getConstant(3, DL, MVT::i16));
16960
16961   return DAG.getNode((VT.getSizeInBits() < 16 ?
16962                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16963 }
16964
16965 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16966   MVT VT = Op.getSimpleValueType();
16967   EVT OpVT = VT;
16968   unsigned NumBits = VT.getSizeInBits();
16969   SDLoc dl(Op);
16970
16971   Op = Op.getOperand(0);
16972   if (VT == MVT::i8) {
16973     // Zero extend to i32 since there is not an i8 bsr.
16974     OpVT = MVT::i32;
16975     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16976   }
16977
16978   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16979   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16980   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16981
16982   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16983   SDValue Ops[] = {
16984     Op,
16985     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16986     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16987     Op.getValue(1)
16988   };
16989   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16990
16991   // Finally xor with NumBits-1.
16992   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16993                    DAG.getConstant(NumBits - 1, dl, OpVT));
16994
16995   if (VT == MVT::i8)
16996     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16997   return Op;
16998 }
16999
17000 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17001   MVT VT = Op.getSimpleValueType();
17002   EVT OpVT = VT;
17003   unsigned NumBits = VT.getSizeInBits();
17004   SDLoc dl(Op);
17005
17006   Op = Op.getOperand(0);
17007   if (VT == MVT::i8) {
17008     // Zero extend to i32 since there is not an i8 bsr.
17009     OpVT = MVT::i32;
17010     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17011   }
17012
17013   // Issue a bsr (scan bits in reverse).
17014   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17015   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17016
17017   // And xor with NumBits-1.
17018   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17019                    DAG.getConstant(NumBits - 1, dl, OpVT));
17020
17021   if (VT == MVT::i8)
17022     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17023   return Op;
17024 }
17025
17026 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17027   MVT VT = Op.getSimpleValueType();
17028   unsigned NumBits = VT.getSizeInBits();
17029   SDLoc dl(Op);
17030   Op = Op.getOperand(0);
17031
17032   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17033   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17034   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
17035
17036   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17037   SDValue Ops[] = {
17038     Op,
17039     DAG.getConstant(NumBits, dl, VT),
17040     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17041     Op.getValue(1)
17042   };
17043   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17044 }
17045
17046 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17047 // ones, and then concatenate the result back.
17048 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17049   MVT VT = Op.getSimpleValueType();
17050
17051   assert(VT.is256BitVector() && VT.isInteger() &&
17052          "Unsupported value type for operation");
17053
17054   unsigned NumElems = VT.getVectorNumElements();
17055   SDLoc dl(Op);
17056
17057   // Extract the LHS vectors
17058   SDValue LHS = Op.getOperand(0);
17059   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17060   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17061
17062   // Extract the RHS vectors
17063   SDValue RHS = Op.getOperand(1);
17064   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17065   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17066
17067   MVT EltVT = VT.getVectorElementType();
17068   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17069
17070   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17071                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17072                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17073 }
17074
17075 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17076   if (Op.getValueType() == MVT::i1)
17077     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17078                        Op.getOperand(0), Op.getOperand(1));
17079   assert(Op.getSimpleValueType().is256BitVector() &&
17080          Op.getSimpleValueType().isInteger() &&
17081          "Only handle AVX 256-bit vector integer operation");
17082   return Lower256IntArith(Op, DAG);
17083 }
17084
17085 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17086   if (Op.getValueType() == MVT::i1)
17087     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17088                        Op.getOperand(0), Op.getOperand(1));
17089   assert(Op.getSimpleValueType().is256BitVector() &&
17090          Op.getSimpleValueType().isInteger() &&
17091          "Only handle AVX 256-bit vector integer operation");
17092   return Lower256IntArith(Op, DAG);
17093 }
17094
17095 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17096   assert(Op.getSimpleValueType().is256BitVector() &&
17097          Op.getSimpleValueType().isInteger() &&
17098          "Only handle AVX 256-bit vector integer operation");
17099   return Lower256IntArith(Op, DAG);
17100 }
17101
17102 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17103                         SelectionDAG &DAG) {
17104   SDLoc dl(Op);
17105   MVT VT = Op.getSimpleValueType();
17106
17107   if (VT == MVT::i1)
17108     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17109
17110   // Decompose 256-bit ops into smaller 128-bit ops.
17111   if (VT.is256BitVector() && !Subtarget->hasInt256())
17112     return Lower256IntArith(Op, DAG);
17113
17114   SDValue A = Op.getOperand(0);
17115   SDValue B = Op.getOperand(1);
17116
17117   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17118   // pairs, multiply and truncate.
17119   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17120     if (Subtarget->hasInt256()) {
17121       if (VT == MVT::v32i8) {
17122         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17123         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17124         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17125         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17126         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17127         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17128         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17129         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17130                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17131                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17132       }
17133
17134       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17135       return DAG.getNode(
17136           ISD::TRUNCATE, dl, VT,
17137           DAG.getNode(ISD::MUL, dl, ExVT,
17138                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17139                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17140     }
17141
17142     assert(VT == MVT::v16i8 &&
17143            "Pre-AVX2 support only supports v16i8 multiplication");
17144     MVT ExVT = MVT::v8i16;
17145
17146     // Extract the lo parts and sign extend to i16
17147     SDValue ALo, BLo;
17148     if (Subtarget->hasSSE41()) {
17149       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17150       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17151     } else {
17152       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17153                               -1, 4, -1, 5, -1, 6, -1, 7};
17154       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17155       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17156       ALo = DAG.getBitcast(ExVT, ALo);
17157       BLo = DAG.getBitcast(ExVT, BLo);
17158       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17159       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17160     }
17161
17162     // Extract the hi parts and sign extend to i16
17163     SDValue AHi, BHi;
17164     if (Subtarget->hasSSE41()) {
17165       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17166                               -1, -1, -1, -1, -1, -1, -1, -1};
17167       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17168       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17169       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17170       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17171     } else {
17172       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17173                               -1, 12, -1, 13, -1, 14, -1, 15};
17174       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17175       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17176       AHi = DAG.getBitcast(ExVT, AHi);
17177       BHi = DAG.getBitcast(ExVT, BHi);
17178       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17179       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17180     }
17181
17182     // Multiply, mask the lower 8bits of the lo/hi results and pack
17183     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17184     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17185     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17186     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17187     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17188   }
17189
17190   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17191   if (VT == MVT::v4i32) {
17192     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17193            "Should not custom lower when pmuldq is available!");
17194
17195     // Extract the odd parts.
17196     static const int UnpackMask[] = { 1, -1, 3, -1 };
17197     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17198     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17199
17200     // Multiply the even parts.
17201     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17202     // Now multiply odd parts.
17203     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17204
17205     Evens = DAG.getBitcast(VT, Evens);
17206     Odds = DAG.getBitcast(VT, Odds);
17207
17208     // Merge the two vectors back together with a shuffle. This expands into 2
17209     // shuffles.
17210     static const int ShufMask[] = { 0, 4, 2, 6 };
17211     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17212   }
17213
17214   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17215          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17216
17217   //  Ahi = psrlqi(a, 32);
17218   //  Bhi = psrlqi(b, 32);
17219   //
17220   //  AloBlo = pmuludq(a, b);
17221   //  AloBhi = pmuludq(a, Bhi);
17222   //  AhiBlo = pmuludq(Ahi, b);
17223
17224   //  AloBhi = psllqi(AloBhi, 32);
17225   //  AhiBlo = psllqi(AhiBlo, 32);
17226   //  return AloBlo + AloBhi + AhiBlo;
17227
17228   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17229   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17230
17231   SDValue AhiBlo = Ahi;
17232   SDValue AloBhi = Bhi;
17233   // Bit cast to 32-bit vectors for MULUDQ
17234   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17235                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17236   A = DAG.getBitcast(MulVT, A);
17237   B = DAG.getBitcast(MulVT, B);
17238   Ahi = DAG.getBitcast(MulVT, Ahi);
17239   Bhi = DAG.getBitcast(MulVT, Bhi);
17240
17241   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17242   // After shifting right const values the result may be all-zero.
17243   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17244     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17245     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17246   }
17247   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17248     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17249     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17250   }
17251
17252   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17253   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17254 }
17255
17256 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17257   assert(Subtarget->isTargetWin64() && "Unexpected target");
17258   EVT VT = Op.getValueType();
17259   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17260          "Unexpected return type for lowering");
17261
17262   RTLIB::Libcall LC;
17263   bool isSigned;
17264   switch (Op->getOpcode()) {
17265   default: llvm_unreachable("Unexpected request for libcall!");
17266   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17267   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17268   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17269   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17270   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17271   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17272   }
17273
17274   SDLoc dl(Op);
17275   SDValue InChain = DAG.getEntryNode();
17276
17277   TargetLowering::ArgListTy Args;
17278   TargetLowering::ArgListEntry Entry;
17279   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17280     EVT ArgVT = Op->getOperand(i).getValueType();
17281     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17282            "Unexpected argument type for lowering");
17283     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17284     Entry.Node = StackPtr;
17285     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17286                            false, false, 16);
17287     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17288     Entry.Ty = PointerType::get(ArgTy,0);
17289     Entry.isSExt = false;
17290     Entry.isZExt = false;
17291     Args.push_back(Entry);
17292   }
17293
17294   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17295                                          getPointerTy(DAG.getDataLayout()));
17296
17297   TargetLowering::CallLoweringInfo CLI(DAG);
17298   CLI.setDebugLoc(dl).setChain(InChain)
17299     .setCallee(getLibcallCallingConv(LC),
17300                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17301                Callee, std::move(Args), 0)
17302     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17303
17304   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17305   return DAG.getBitcast(VT, CallInfo.first);
17306 }
17307
17308 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17309                              SelectionDAG &DAG) {
17310   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17311   EVT VT = Op0.getValueType();
17312   SDLoc dl(Op);
17313
17314   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17315          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17316
17317   // PMULxD operations multiply each even value (starting at 0) of LHS with
17318   // the related value of RHS and produce a widen result.
17319   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17320   // => <2 x i64> <ae|cg>
17321   //
17322   // In other word, to have all the results, we need to perform two PMULxD:
17323   // 1. one with the even values.
17324   // 2. one with the odd values.
17325   // To achieve #2, with need to place the odd values at an even position.
17326   //
17327   // Place the odd value at an even position (basically, shift all values 1
17328   // step to the left):
17329   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17330   // <a|b|c|d> => <b|undef|d|undef>
17331   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17332   // <e|f|g|h> => <f|undef|h|undef>
17333   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17334
17335   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17336   // ints.
17337   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17338   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17339   unsigned Opcode =
17340       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17341   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17342   // => <2 x i64> <ae|cg>
17343   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17344   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17345   // => <2 x i64> <bf|dh>
17346   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17347
17348   // Shuffle it back into the right order.
17349   SDValue Highs, Lows;
17350   if (VT == MVT::v8i32) {
17351     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17352     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17353     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17354     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17355   } else {
17356     const int HighMask[] = {1, 5, 3, 7};
17357     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17358     const int LowMask[] = {0, 4, 2, 6};
17359     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17360   }
17361
17362   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17363   // unsigned multiply.
17364   if (IsSigned && !Subtarget->hasSSE41()) {
17365     SDValue ShAmt = DAG.getConstant(
17366         31, dl,
17367         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17368     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17369                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17370     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17371                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17372
17373     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17374     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17375   }
17376
17377   // The first result of MUL_LOHI is actually the low value, followed by the
17378   // high value.
17379   SDValue Ops[] = {Lows, Highs};
17380   return DAG.getMergeValues(Ops, dl);
17381 }
17382
17383 // Return true if the required (according to Opcode) shift-imm form is natively
17384 // supported by the Subtarget
17385 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17386                                         unsigned Opcode) {
17387   if (VT.getScalarSizeInBits() < 16)
17388     return false;
17389
17390   if (VT.is512BitVector() &&
17391       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17392     return true;
17393
17394   bool LShift = VT.is128BitVector() ||
17395     (VT.is256BitVector() && Subtarget->hasInt256());
17396
17397   bool AShift = LShift && (Subtarget->hasVLX() ||
17398     (VT != MVT::v2i64 && VT != MVT::v4i64));
17399   return (Opcode == ISD::SRA) ? AShift : LShift;
17400 }
17401
17402 // The shift amount is a variable, but it is the same for all vector lanes.
17403 // These instructions are defined together with shift-immediate.
17404 static
17405 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17406                                       unsigned Opcode) {
17407   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17408 }
17409
17410 // Return true if the required (according to Opcode) variable-shift form is
17411 // natively supported by the Subtarget
17412 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17413                                     unsigned Opcode) {
17414
17415   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17416     return false;
17417
17418   // vXi16 supported only on AVX-512, BWI
17419   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17420     return false;
17421
17422   if (VT.is512BitVector() || Subtarget->hasVLX())
17423     return true;
17424
17425   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17426   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17427   return (Opcode == ISD::SRA) ? AShift : LShift;
17428 }
17429
17430 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17431                                          const X86Subtarget *Subtarget) {
17432   MVT VT = Op.getSimpleValueType();
17433   SDLoc dl(Op);
17434   SDValue R = Op.getOperand(0);
17435   SDValue Amt = Op.getOperand(1);
17436
17437   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17438     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17439
17440   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17441     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17442     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17443     SDValue Ex = DAG.getBitcast(ExVT, R);
17444
17445     if (ShiftAmt >= 32) {
17446       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17447       SDValue Upper =
17448           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17449       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17450                                                  ShiftAmt - 32, DAG);
17451       if (VT == MVT::v2i64)
17452         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17453       if (VT == MVT::v4i64)
17454         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17455                                   {9, 1, 11, 3, 13, 5, 15, 7});
17456     } else {
17457       // SRA upper i32, SHL whole i64 and select lower i32.
17458       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17459                                                  ShiftAmt, DAG);
17460       SDValue Lower =
17461           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17462       Lower = DAG.getBitcast(ExVT, Lower);
17463       if (VT == MVT::v2i64)
17464         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17465       if (VT == MVT::v4i64)
17466         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17467                                   {8, 1, 10, 3, 12, 5, 14, 7});
17468     }
17469     return DAG.getBitcast(VT, Ex);
17470   };
17471
17472   // Optimize shl/srl/sra with constant shift amount.
17473   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17474     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17475       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17476
17477       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17478         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17479
17480       // i64 SRA needs to be performed as partial shifts.
17481       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17482           Op.getOpcode() == ISD::SRA)
17483         return ArithmeticShiftRight64(ShiftAmt);
17484
17485       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17486         unsigned NumElts = VT.getVectorNumElements();
17487         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17488
17489         if (Op.getOpcode() == ISD::SHL) {
17490           // Simple i8 add case
17491           if (ShiftAmt == 1)
17492             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17493
17494           // Make a large shift.
17495           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17496                                                    R, ShiftAmt, DAG);
17497           SHL = DAG.getBitcast(VT, SHL);
17498           // Zero out the rightmost bits.
17499           SmallVector<SDValue, 32> V(
17500               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17501           return DAG.getNode(ISD::AND, dl, VT, SHL,
17502                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17503         }
17504         if (Op.getOpcode() == ISD::SRL) {
17505           // Make a large shift.
17506           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17507                                                    R, ShiftAmt, DAG);
17508           SRL = DAG.getBitcast(VT, SRL);
17509           // Zero out the leftmost bits.
17510           SmallVector<SDValue, 32> V(
17511               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17512           return DAG.getNode(ISD::AND, dl, VT, SRL,
17513                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17514         }
17515         if (Op.getOpcode() == ISD::SRA) {
17516           if (ShiftAmt == 7) {
17517             // ashr(R, 7)  === cmp_slt(R, 0)
17518             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17519             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17520           }
17521
17522           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17523           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17524           SmallVector<SDValue, 32> V(NumElts,
17525                                      DAG.getConstant(128 >> ShiftAmt, dl,
17526                                                      MVT::i8));
17527           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17528           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17529           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17530           return Res;
17531         }
17532         llvm_unreachable("Unknown shift opcode.");
17533       }
17534     }
17535   }
17536
17537   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17538   if (!Subtarget->is64Bit() &&
17539       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17540
17541     // Peek through any splat that was introduced for i64 shift vectorization.
17542     int SplatIndex = -1;
17543     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17544       if (SVN->isSplat()) {
17545         SplatIndex = SVN->getSplatIndex();
17546         Amt = Amt.getOperand(0);
17547         assert(SplatIndex < (int)VT.getVectorNumElements() &&
17548                "Splat shuffle referencing second operand");
17549       }
17550
17551     if (Amt.getOpcode() != ISD::BITCAST ||
17552         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17553       return SDValue();
17554
17555     Amt = Amt.getOperand(0);
17556     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17557                      VT.getVectorNumElements();
17558     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17559     uint64_t ShiftAmt = 0;
17560     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17561     for (unsigned i = 0; i != Ratio; ++i) {
17562       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17563       if (!C)
17564         return SDValue();
17565       // 6 == Log2(64)
17566       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17567     }
17568
17569     // Check remaining shift amounts (if not a splat).
17570     if (SplatIndex < 0) {
17571       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17572         uint64_t ShAmt = 0;
17573         for (unsigned j = 0; j != Ratio; ++j) {
17574           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17575           if (!C)
17576             return SDValue();
17577           // 6 == Log2(64)
17578           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17579         }
17580         if (ShAmt != ShiftAmt)
17581           return SDValue();
17582       }
17583     }
17584
17585     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17586       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17587
17588     if (Op.getOpcode() == ISD::SRA)
17589       return ArithmeticShiftRight64(ShiftAmt);
17590   }
17591
17592   return SDValue();
17593 }
17594
17595 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17596                                         const X86Subtarget* Subtarget) {
17597   MVT VT = Op.getSimpleValueType();
17598   SDLoc dl(Op);
17599   SDValue R = Op.getOperand(0);
17600   SDValue Amt = Op.getOperand(1);
17601
17602   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17603     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17604
17605   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17606     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17607
17608   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17609     SDValue BaseShAmt;
17610     EVT EltVT = VT.getVectorElementType();
17611
17612     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17613       // Check if this build_vector node is doing a splat.
17614       // If so, then set BaseShAmt equal to the splat value.
17615       BaseShAmt = BV->getSplatValue();
17616       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17617         BaseShAmt = SDValue();
17618     } else {
17619       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17620         Amt = Amt.getOperand(0);
17621
17622       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17623       if (SVN && SVN->isSplat()) {
17624         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17625         SDValue InVec = Amt.getOperand(0);
17626         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17627           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17628                  "Unexpected shuffle index found!");
17629           BaseShAmt = InVec.getOperand(SplatIdx);
17630         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17631            if (ConstantSDNode *C =
17632                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17633              if (C->getZExtValue() == SplatIdx)
17634                BaseShAmt = InVec.getOperand(1);
17635            }
17636         }
17637
17638         if (!BaseShAmt)
17639           // Avoid introducing an extract element from a shuffle.
17640           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17641                                   DAG.getIntPtrConstant(SplatIdx, dl));
17642       }
17643     }
17644
17645     if (BaseShAmt.getNode()) {
17646       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17647       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17648         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17649       else if (EltVT.bitsLT(MVT::i32))
17650         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17651
17652       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17653     }
17654   }
17655
17656   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17657   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17658       Amt.getOpcode() == ISD::BITCAST &&
17659       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17660     Amt = Amt.getOperand(0);
17661     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17662                      VT.getVectorNumElements();
17663     std::vector<SDValue> Vals(Ratio);
17664     for (unsigned i = 0; i != Ratio; ++i)
17665       Vals[i] = Amt.getOperand(i);
17666     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17667       for (unsigned j = 0; j != Ratio; ++j)
17668         if (Vals[j] != Amt.getOperand(i + j))
17669           return SDValue();
17670     }
17671
17672     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17673       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17674   }
17675   return SDValue();
17676 }
17677
17678 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17679                           SelectionDAG &DAG) {
17680   MVT VT = Op.getSimpleValueType();
17681   SDLoc dl(Op);
17682   SDValue R = Op.getOperand(0);
17683   SDValue Amt = Op.getOperand(1);
17684
17685   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17686   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17687
17688   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17689     return V;
17690
17691   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17692       return V;
17693
17694   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17695     return Op;
17696
17697   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17698   // shifts per-lane and then shuffle the partial results back together.
17699   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17700     // Splat the shift amounts so the scalar shifts above will catch it.
17701     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17702     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17703     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17704     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17705     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17706   }
17707
17708   // i64 vector arithmetic shift can be emulated with the transform:
17709   // M = lshr(SIGN_BIT, Amt)
17710   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17711   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17712       Op.getOpcode() == ISD::SRA) {
17713     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17714     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17715     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17716     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17717     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17718     return R;
17719   }
17720
17721   // If possible, lower this packed shift into a vector multiply instead of
17722   // expanding it into a sequence of scalar shifts.
17723   // Do this only if the vector shift count is a constant build_vector.
17724   if (Op.getOpcode() == ISD::SHL &&
17725       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17726        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17727       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17728     SmallVector<SDValue, 8> Elts;
17729     EVT SVT = VT.getScalarType();
17730     unsigned SVTBits = SVT.getSizeInBits();
17731     const APInt &One = APInt(SVTBits, 1);
17732     unsigned NumElems = VT.getVectorNumElements();
17733
17734     for (unsigned i=0; i !=NumElems; ++i) {
17735       SDValue Op = Amt->getOperand(i);
17736       if (Op->getOpcode() == ISD::UNDEF) {
17737         Elts.push_back(Op);
17738         continue;
17739       }
17740
17741       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17742       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17743       uint64_t ShAmt = C.getZExtValue();
17744       if (ShAmt >= SVTBits) {
17745         Elts.push_back(DAG.getUNDEF(SVT));
17746         continue;
17747       }
17748       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17749     }
17750     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17751     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17752   }
17753
17754   // Lower SHL with variable shift amount.
17755   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17756     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17757
17758     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17759                      DAG.getConstant(0x3f800000U, dl, VT));
17760     Op = DAG.getBitcast(MVT::v4f32, Op);
17761     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17762     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17763   }
17764
17765   // If possible, lower this shift as a sequence of two shifts by
17766   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17767   // Example:
17768   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17769   //
17770   // Could be rewritten as:
17771   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17772   //
17773   // The advantage is that the two shifts from the example would be
17774   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17775   // the vector shift into four scalar shifts plus four pairs of vector
17776   // insert/extract.
17777   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17778       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17779     unsigned TargetOpcode = X86ISD::MOVSS;
17780     bool CanBeSimplified;
17781     // The splat value for the first packed shift (the 'X' from the example).
17782     SDValue Amt1 = Amt->getOperand(0);
17783     // The splat value for the second packed shift (the 'Y' from the example).
17784     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17785                                         Amt->getOperand(2);
17786
17787     // See if it is possible to replace this node with a sequence of
17788     // two shifts followed by a MOVSS/MOVSD
17789     if (VT == MVT::v4i32) {
17790       // Check if it is legal to use a MOVSS.
17791       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17792                         Amt2 == Amt->getOperand(3);
17793       if (!CanBeSimplified) {
17794         // Otherwise, check if we can still simplify this node using a MOVSD.
17795         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17796                           Amt->getOperand(2) == Amt->getOperand(3);
17797         TargetOpcode = X86ISD::MOVSD;
17798         Amt2 = Amt->getOperand(2);
17799       }
17800     } else {
17801       // Do similar checks for the case where the machine value type
17802       // is MVT::v8i16.
17803       CanBeSimplified = Amt1 == Amt->getOperand(1);
17804       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17805         CanBeSimplified = Amt2 == Amt->getOperand(i);
17806
17807       if (!CanBeSimplified) {
17808         TargetOpcode = X86ISD::MOVSD;
17809         CanBeSimplified = true;
17810         Amt2 = Amt->getOperand(4);
17811         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17812           CanBeSimplified = Amt1 == Amt->getOperand(i);
17813         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17814           CanBeSimplified = Amt2 == Amt->getOperand(j);
17815       }
17816     }
17817
17818     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17819         isa<ConstantSDNode>(Amt2)) {
17820       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17821       EVT CastVT = MVT::v4i32;
17822       SDValue Splat1 =
17823         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17824       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17825       SDValue Splat2 =
17826         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17827       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17828       if (TargetOpcode == X86ISD::MOVSD)
17829         CastVT = MVT::v2i64;
17830       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17831       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17832       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17833                                             BitCast1, DAG);
17834       return DAG.getBitcast(VT, Result);
17835     }
17836   }
17837
17838   // v4i32 Non Uniform Shifts.
17839   // If the shift amount is constant we can shift each lane using the SSE2
17840   // immediate shifts, else we need to zero-extend each lane to the lower i64
17841   // and shift using the SSE2 variable shifts.
17842   // The separate results can then be blended together.
17843   if (VT == MVT::v4i32) {
17844     unsigned Opc = Op.getOpcode();
17845     SDValue Amt0, Amt1, Amt2, Amt3;
17846     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17847       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17848       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17849       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17850       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17851     } else {
17852       // ISD::SHL is handled above but we include it here for completeness.
17853       switch (Opc) {
17854       default:
17855         llvm_unreachable("Unknown target vector shift node");
17856       case ISD::SHL:
17857         Opc = X86ISD::VSHL;
17858         break;
17859       case ISD::SRL:
17860         Opc = X86ISD::VSRL;
17861         break;
17862       case ISD::SRA:
17863         Opc = X86ISD::VSRA;
17864         break;
17865       }
17866       // The SSE2 shifts use the lower i64 as the same shift amount for
17867       // all lanes and the upper i64 is ignored. These shuffle masks
17868       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17869       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17870       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17871       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17872       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17873       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17874     }
17875
17876     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17877     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17878     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17879     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17880     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17881     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17882     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17883   }
17884
17885   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17886     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17887     unsigned ShiftOpcode = Op->getOpcode();
17888
17889     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17890       // On SSE41 targets we make use of the fact that VSELECT lowers
17891       // to PBLENDVB which selects bytes based just on the sign bit.
17892       if (Subtarget->hasSSE41()) {
17893         V0 = DAG.getBitcast(VT, V0);
17894         V1 = DAG.getBitcast(VT, V1);
17895         Sel = DAG.getBitcast(VT, Sel);
17896         return DAG.getBitcast(SelVT,
17897                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17898       }
17899       // On pre-SSE41 targets we test for the sign bit by comparing to
17900       // zero - a negative value will set all bits of the lanes to true
17901       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17902       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17903       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17904       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17905     };
17906
17907     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17908     // We can safely do this using i16 shifts as we're only interested in
17909     // the 3 lower bits of each byte.
17910     Amt = DAG.getBitcast(ExtVT, Amt);
17911     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17912     Amt = DAG.getBitcast(VT, Amt);
17913
17914     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17915       // r = VSELECT(r, shift(r, 4), a);
17916       SDValue M =
17917           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17918       R = SignBitSelect(VT, Amt, M, R);
17919
17920       // a += a
17921       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17922
17923       // r = VSELECT(r, shift(r, 2), a);
17924       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17925       R = SignBitSelect(VT, Amt, M, R);
17926
17927       // a += a
17928       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17929
17930       // return VSELECT(r, shift(r, 1), a);
17931       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17932       R = SignBitSelect(VT, Amt, M, R);
17933       return R;
17934     }
17935
17936     if (Op->getOpcode() == ISD::SRA) {
17937       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17938       // so we can correctly sign extend. We don't care what happens to the
17939       // lower byte.
17940       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17941       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17942       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17943       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17944       ALo = DAG.getBitcast(ExtVT, ALo);
17945       AHi = DAG.getBitcast(ExtVT, AHi);
17946       RLo = DAG.getBitcast(ExtVT, RLo);
17947       RHi = DAG.getBitcast(ExtVT, RHi);
17948
17949       // r = VSELECT(r, shift(r, 4), a);
17950       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17951                                 DAG.getConstant(4, dl, ExtVT));
17952       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17953                                 DAG.getConstant(4, dl, ExtVT));
17954       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17955       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17956
17957       // a += a
17958       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17959       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17960
17961       // r = VSELECT(r, shift(r, 2), a);
17962       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17963                         DAG.getConstant(2, dl, ExtVT));
17964       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17965                         DAG.getConstant(2, dl, ExtVT));
17966       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17967       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17968
17969       // a += a
17970       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17971       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17972
17973       // r = VSELECT(r, shift(r, 1), a);
17974       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17975                         DAG.getConstant(1, dl, ExtVT));
17976       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17977                         DAG.getConstant(1, dl, ExtVT));
17978       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17979       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17980
17981       // Logical shift the result back to the lower byte, leaving a zero upper
17982       // byte
17983       // meaning that we can safely pack with PACKUSWB.
17984       RLo =
17985           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17986       RHi =
17987           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17988       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17989     }
17990   }
17991
17992   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17993   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17994   // solution better.
17995   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17996     MVT ExtVT = MVT::v8i32;
17997     unsigned ExtOpc =
17998         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17999     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18000     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18001     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18002                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18003   }
18004
18005   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
18006     MVT ExtVT = MVT::v8i32;
18007     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18008     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18009     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18010     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18011     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18012     ALo = DAG.getBitcast(ExtVT, ALo);
18013     AHi = DAG.getBitcast(ExtVT, AHi);
18014     RLo = DAG.getBitcast(ExtVT, RLo);
18015     RHi = DAG.getBitcast(ExtVT, RHi);
18016     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18017     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18018     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18019     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18020     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18021   }
18022
18023   if (VT == MVT::v8i16) {
18024     unsigned ShiftOpcode = Op->getOpcode();
18025
18026     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18027       // On SSE41 targets we make use of the fact that VSELECT lowers
18028       // to PBLENDVB which selects bytes based just on the sign bit.
18029       if (Subtarget->hasSSE41()) {
18030         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18031         V0 = DAG.getBitcast(ExtVT, V0);
18032         V1 = DAG.getBitcast(ExtVT, V1);
18033         Sel = DAG.getBitcast(ExtVT, Sel);
18034         return DAG.getBitcast(
18035             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18036       }
18037       // On pre-SSE41 targets we splat the sign bit - a negative value will
18038       // set all bits of the lanes to true and VSELECT uses that in
18039       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18040       SDValue C =
18041           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18042       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18043     };
18044
18045     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18046     if (Subtarget->hasSSE41()) {
18047       // On SSE41 targets we need to replicate the shift mask in both
18048       // bytes for PBLENDVB.
18049       Amt = DAG.getNode(
18050           ISD::OR, dl, VT,
18051           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18052           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18053     } else {
18054       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18055     }
18056
18057     // r = VSELECT(r, shift(r, 8), a);
18058     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18059     R = SignBitSelect(Amt, M, R);
18060
18061     // a += a
18062     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18063
18064     // r = VSELECT(r, shift(r, 4), a);
18065     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18066     R = SignBitSelect(Amt, M, R);
18067
18068     // a += a
18069     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18070
18071     // r = VSELECT(r, shift(r, 2), a);
18072     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18073     R = SignBitSelect(Amt, M, R);
18074
18075     // a += a
18076     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18077
18078     // return VSELECT(r, shift(r, 1), a);
18079     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18080     R = SignBitSelect(Amt, M, R);
18081     return R;
18082   }
18083
18084   // Decompose 256-bit shifts into smaller 128-bit shifts.
18085   if (VT.is256BitVector()) {
18086     unsigned NumElems = VT.getVectorNumElements();
18087     MVT EltVT = VT.getVectorElementType();
18088     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18089
18090     // Extract the two vectors
18091     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18092     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18093
18094     // Recreate the shift amount vectors
18095     SDValue Amt1, Amt2;
18096     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18097       // Constant shift amount
18098       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18099       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18100       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18101
18102       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18103       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18104     } else {
18105       // Variable shift amount
18106       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18107       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18108     }
18109
18110     // Issue new vector shifts for the smaller types
18111     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18112     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18113
18114     // Concatenate the result back
18115     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18116   }
18117
18118   return SDValue();
18119 }
18120
18121 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18122   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18123   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18124   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18125   // has only one use.
18126   SDNode *N = Op.getNode();
18127   SDValue LHS = N->getOperand(0);
18128   SDValue RHS = N->getOperand(1);
18129   unsigned BaseOp = 0;
18130   unsigned Cond = 0;
18131   SDLoc DL(Op);
18132   switch (Op.getOpcode()) {
18133   default: llvm_unreachable("Unknown ovf instruction!");
18134   case ISD::SADDO:
18135     // A subtract of one will be selected as a INC. Note that INC doesn't
18136     // set CF, so we can't do this for UADDO.
18137     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18138       if (C->isOne()) {
18139         BaseOp = X86ISD::INC;
18140         Cond = X86::COND_O;
18141         break;
18142       }
18143     BaseOp = X86ISD::ADD;
18144     Cond = X86::COND_O;
18145     break;
18146   case ISD::UADDO:
18147     BaseOp = X86ISD::ADD;
18148     Cond = X86::COND_B;
18149     break;
18150   case ISD::SSUBO:
18151     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18152     // set CF, so we can't do this for USUBO.
18153     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18154       if (C->isOne()) {
18155         BaseOp = X86ISD::DEC;
18156         Cond = X86::COND_O;
18157         break;
18158       }
18159     BaseOp = X86ISD::SUB;
18160     Cond = X86::COND_O;
18161     break;
18162   case ISD::USUBO:
18163     BaseOp = X86ISD::SUB;
18164     Cond = X86::COND_B;
18165     break;
18166   case ISD::SMULO:
18167     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18168     Cond = X86::COND_O;
18169     break;
18170   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18171     if (N->getValueType(0) == MVT::i8) {
18172       BaseOp = X86ISD::UMUL8;
18173       Cond = X86::COND_O;
18174       break;
18175     }
18176     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18177                                  MVT::i32);
18178     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18179
18180     SDValue SetCC =
18181       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18182                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18183                   SDValue(Sum.getNode(), 2));
18184
18185     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18186   }
18187   }
18188
18189   // Also sets EFLAGS.
18190   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18191   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18192
18193   SDValue SetCC =
18194     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18195                 DAG.getConstant(Cond, DL, MVT::i32),
18196                 SDValue(Sum.getNode(), 1));
18197
18198   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18199 }
18200
18201 /// Returns true if the operand type is exactly twice the native width, and
18202 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18203 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18204 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18205 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18206   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18207
18208   if (OpWidth == 64)
18209     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18210   else if (OpWidth == 128)
18211     return Subtarget->hasCmpxchg16b();
18212   else
18213     return false;
18214 }
18215
18216 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18217   return needsCmpXchgNb(SI->getValueOperand()->getType());
18218 }
18219
18220 // Note: this turns large loads into lock cmpxchg8b/16b.
18221 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18222 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18223   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18224   return needsCmpXchgNb(PTy->getElementType());
18225 }
18226
18227 TargetLoweringBase::AtomicRMWExpansionKind
18228 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18229   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18230   Type *MemType = AI->getType();
18231
18232   // If the operand is too big, we must see if cmpxchg8/16b is available
18233   // and default to library calls otherwise.
18234   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18235     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
18236                                    : AtomicRMWExpansionKind::None;
18237   }
18238
18239   AtomicRMWInst::BinOp Op = AI->getOperation();
18240   switch (Op) {
18241   default:
18242     llvm_unreachable("Unknown atomic operation");
18243   case AtomicRMWInst::Xchg:
18244   case AtomicRMWInst::Add:
18245   case AtomicRMWInst::Sub:
18246     // It's better to use xadd, xsub or xchg for these in all cases.
18247     return AtomicRMWExpansionKind::None;
18248   case AtomicRMWInst::Or:
18249   case AtomicRMWInst::And:
18250   case AtomicRMWInst::Xor:
18251     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18252     // prefix to a normal instruction for these operations.
18253     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
18254                             : AtomicRMWExpansionKind::None;
18255   case AtomicRMWInst::Nand:
18256   case AtomicRMWInst::Max:
18257   case AtomicRMWInst::Min:
18258   case AtomicRMWInst::UMax:
18259   case AtomicRMWInst::UMin:
18260     // These always require a non-trivial set of data operations on x86. We must
18261     // use a cmpxchg loop.
18262     return AtomicRMWExpansionKind::CmpXChg;
18263   }
18264 }
18265
18266 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18267   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18268   // no-sse2). There isn't any reason to disable it if the target processor
18269   // supports it.
18270   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18271 }
18272
18273 LoadInst *
18274 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18275   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18276   Type *MemType = AI->getType();
18277   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18278   // there is no benefit in turning such RMWs into loads, and it is actually
18279   // harmful as it introduces a mfence.
18280   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18281     return nullptr;
18282
18283   auto Builder = IRBuilder<>(AI);
18284   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18285   auto SynchScope = AI->getSynchScope();
18286   // We must restrict the ordering to avoid generating loads with Release or
18287   // ReleaseAcquire orderings.
18288   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18289   auto Ptr = AI->getPointerOperand();
18290
18291   // Before the load we need a fence. Here is an example lifted from
18292   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18293   // is required:
18294   // Thread 0:
18295   //   x.store(1, relaxed);
18296   //   r1 = y.fetch_add(0, release);
18297   // Thread 1:
18298   //   y.fetch_add(42, acquire);
18299   //   r2 = x.load(relaxed);
18300   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18301   // lowered to just a load without a fence. A mfence flushes the store buffer,
18302   // making the optimization clearly correct.
18303   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18304   // otherwise, we might be able to be more aggressive on relaxed idempotent
18305   // rmw. In practice, they do not look useful, so we don't try to be
18306   // especially clever.
18307   if (SynchScope == SingleThread)
18308     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18309     // the IR level, so we must wrap it in an intrinsic.
18310     return nullptr;
18311
18312   if (!hasMFENCE(*Subtarget))
18313     // FIXME: it might make sense to use a locked operation here but on a
18314     // different cache-line to prevent cache-line bouncing. In practice it
18315     // is probably a small win, and x86 processors without mfence are rare
18316     // enough that we do not bother.
18317     return nullptr;
18318
18319   Function *MFence =
18320       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18321   Builder.CreateCall(MFence, {});
18322
18323   // Finally we can emit the atomic load.
18324   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18325           AI->getType()->getPrimitiveSizeInBits());
18326   Loaded->setAtomic(Order, SynchScope);
18327   AI->replaceAllUsesWith(Loaded);
18328   AI->eraseFromParent();
18329   return Loaded;
18330 }
18331
18332 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18333                                  SelectionDAG &DAG) {
18334   SDLoc dl(Op);
18335   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18336     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18337   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18338     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18339
18340   // The only fence that needs an instruction is a sequentially-consistent
18341   // cross-thread fence.
18342   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18343     if (hasMFENCE(*Subtarget))
18344       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18345
18346     SDValue Chain = Op.getOperand(0);
18347     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18348     SDValue Ops[] = {
18349       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18350       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18351       DAG.getRegister(0, MVT::i32),            // Index
18352       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18353       DAG.getRegister(0, MVT::i32),            // Segment.
18354       Zero,
18355       Chain
18356     };
18357     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18358     return SDValue(Res, 0);
18359   }
18360
18361   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18362   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18363 }
18364
18365 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18366                              SelectionDAG &DAG) {
18367   MVT T = Op.getSimpleValueType();
18368   SDLoc DL(Op);
18369   unsigned Reg = 0;
18370   unsigned size = 0;
18371   switch(T.SimpleTy) {
18372   default: llvm_unreachable("Invalid value type!");
18373   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18374   case MVT::i16: Reg = X86::AX;  size = 2; break;
18375   case MVT::i32: Reg = X86::EAX; size = 4; break;
18376   case MVT::i64:
18377     assert(Subtarget->is64Bit() && "Node not type legal!");
18378     Reg = X86::RAX; size = 8;
18379     break;
18380   }
18381   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18382                                   Op.getOperand(2), SDValue());
18383   SDValue Ops[] = { cpIn.getValue(0),
18384                     Op.getOperand(1),
18385                     Op.getOperand(3),
18386                     DAG.getTargetConstant(size, DL, MVT::i8),
18387                     cpIn.getValue(1) };
18388   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18389   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18390   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18391                                            Ops, T, MMO);
18392
18393   SDValue cpOut =
18394     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18395   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18396                                       MVT::i32, cpOut.getValue(2));
18397   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18398                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18399                                 EFLAGS);
18400
18401   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18402   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18403   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18404   return SDValue();
18405 }
18406
18407 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18408                             SelectionDAG &DAG) {
18409   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18410   MVT DstVT = Op.getSimpleValueType();
18411
18412   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18413     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18414     if (DstVT != MVT::f64)
18415       // This conversion needs to be expanded.
18416       return SDValue();
18417
18418     SDValue InVec = Op->getOperand(0);
18419     SDLoc dl(Op);
18420     unsigned NumElts = SrcVT.getVectorNumElements();
18421     EVT SVT = SrcVT.getVectorElementType();
18422
18423     // Widen the vector in input in the case of MVT::v2i32.
18424     // Example: from MVT::v2i32 to MVT::v4i32.
18425     SmallVector<SDValue, 16> Elts;
18426     for (unsigned i = 0, e = NumElts; i != e; ++i)
18427       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18428                                  DAG.getIntPtrConstant(i, dl)));
18429
18430     // Explicitly mark the extra elements as Undef.
18431     Elts.append(NumElts, DAG.getUNDEF(SVT));
18432
18433     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18434     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18435     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18436     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18437                        DAG.getIntPtrConstant(0, dl));
18438   }
18439
18440   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18441          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18442   assert((DstVT == MVT::i64 ||
18443           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18444          "Unexpected custom BITCAST");
18445   // i64 <=> MMX conversions are Legal.
18446   if (SrcVT==MVT::i64 && DstVT.isVector())
18447     return Op;
18448   if (DstVT==MVT::i64 && SrcVT.isVector())
18449     return Op;
18450   // MMX <=> MMX conversions are Legal.
18451   if (SrcVT.isVector() && DstVT.isVector())
18452     return Op;
18453   // All other conversions need to be expanded.
18454   return SDValue();
18455 }
18456
18457 /// Compute the horizontal sum of bytes in V for the elements of VT.
18458 ///
18459 /// Requires V to be a byte vector and VT to be an integer vector type with
18460 /// wider elements than V's type. The width of the elements of VT determines
18461 /// how many bytes of V are summed horizontally to produce each element of the
18462 /// result.
18463 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18464                                       const X86Subtarget *Subtarget,
18465                                       SelectionDAG &DAG) {
18466   SDLoc DL(V);
18467   MVT ByteVecVT = V.getSimpleValueType();
18468   MVT EltVT = VT.getVectorElementType();
18469   int NumElts = VT.getVectorNumElements();
18470   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18471          "Expected value to have byte element type.");
18472   assert(EltVT != MVT::i8 &&
18473          "Horizontal byte sum only makes sense for wider elements!");
18474   unsigned VecSize = VT.getSizeInBits();
18475   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18476
18477   // PSADBW instruction horizontally add all bytes and leave the result in i64
18478   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18479   if (EltVT == MVT::i64) {
18480     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18481     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18482     return DAG.getBitcast(VT, V);
18483   }
18484
18485   if (EltVT == MVT::i32) {
18486     // We unpack the low half and high half into i32s interleaved with zeros so
18487     // that we can use PSADBW to horizontally sum them. The most useful part of
18488     // this is that it lines up the results of two PSADBW instructions to be
18489     // two v2i64 vectors which concatenated are the 4 population counts. We can
18490     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18491     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18492     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18493     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18494
18495     // Do the horizontal sums into two v2i64s.
18496     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18497     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18498                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18499     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18500                        DAG.getBitcast(ByteVecVT, High), Zeros);
18501
18502     // Merge them together.
18503     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18504     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18505                     DAG.getBitcast(ShortVecVT, Low),
18506                     DAG.getBitcast(ShortVecVT, High));
18507
18508     return DAG.getBitcast(VT, V);
18509   }
18510
18511   // The only element type left is i16.
18512   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18513
18514   // To obtain pop count for each i16 element starting from the pop count for
18515   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18516   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18517   // directly supported.
18518   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18519   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18520   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18521   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18522                   DAG.getBitcast(ByteVecVT, V));
18523   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18524 }
18525
18526 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18527                                         const X86Subtarget *Subtarget,
18528                                         SelectionDAG &DAG) {
18529   MVT VT = Op.getSimpleValueType();
18530   MVT EltVT = VT.getVectorElementType();
18531   unsigned VecSize = VT.getSizeInBits();
18532
18533   // Implement a lookup table in register by using an algorithm based on:
18534   // http://wm.ite.pl/articles/sse-popcount.html
18535   //
18536   // The general idea is that every lower byte nibble in the input vector is an
18537   // index into a in-register pre-computed pop count table. We then split up the
18538   // input vector in two new ones: (1) a vector with only the shifted-right
18539   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18540   // masked out higher ones) for each byte. PSHUB is used separately with both
18541   // to index the in-register table. Next, both are added and the result is a
18542   // i8 vector where each element contains the pop count for input byte.
18543   //
18544   // To obtain the pop count for elements != i8, we follow up with the same
18545   // approach and use additional tricks as described below.
18546   //
18547   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18548                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18549                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18550                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18551
18552   int NumByteElts = VecSize / 8;
18553   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18554   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18555   SmallVector<SDValue, 16> LUTVec;
18556   for (int i = 0; i < NumByteElts; ++i)
18557     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18558   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18559   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18560                                   DAG.getConstant(0x0F, DL, MVT::i8));
18561   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18562
18563   // High nibbles
18564   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18565   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18566   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18567
18568   // Low nibbles
18569   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18570
18571   // The input vector is used as the shuffle mask that index elements into the
18572   // LUT. After counting low and high nibbles, add the vector to obtain the
18573   // final pop count per i8 element.
18574   SDValue HighPopCnt =
18575       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18576   SDValue LowPopCnt =
18577       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18578   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18579
18580   if (EltVT == MVT::i8)
18581     return PopCnt;
18582
18583   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18584 }
18585
18586 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18587                                        const X86Subtarget *Subtarget,
18588                                        SelectionDAG &DAG) {
18589   MVT VT = Op.getSimpleValueType();
18590   assert(VT.is128BitVector() &&
18591          "Only 128-bit vector bitmath lowering supported.");
18592
18593   int VecSize = VT.getSizeInBits();
18594   MVT EltVT = VT.getVectorElementType();
18595   int Len = EltVT.getSizeInBits();
18596
18597   // This is the vectorized version of the "best" algorithm from
18598   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18599   // with a minor tweak to use a series of adds + shifts instead of vector
18600   // multiplications. Implemented for all integer vector types. We only use
18601   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18602   // much faster, even faster than using native popcnt instructions.
18603
18604   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18605     MVT VT = V.getSimpleValueType();
18606     SmallVector<SDValue, 32> Shifters(
18607         VT.getVectorNumElements(),
18608         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18609     return DAG.getNode(OpCode, DL, VT, V,
18610                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18611   };
18612   auto GetMask = [&](SDValue V, APInt Mask) {
18613     MVT VT = V.getSimpleValueType();
18614     SmallVector<SDValue, 32> Masks(
18615         VT.getVectorNumElements(),
18616         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18617     return DAG.getNode(ISD::AND, DL, VT, V,
18618                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18619   };
18620
18621   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18622   // x86, so set the SRL type to have elements at least i16 wide. This is
18623   // correct because all of our SRLs are followed immediately by a mask anyways
18624   // that handles any bits that sneak into the high bits of the byte elements.
18625   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18626
18627   SDValue V = Op;
18628
18629   // v = v - ((v >> 1) & 0x55555555...)
18630   SDValue Srl =
18631       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18632   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18633   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18634
18635   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18636   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18637   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18638   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18639   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18640
18641   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18642   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18643   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18644   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18645
18646   // At this point, V contains the byte-wise population count, and we are
18647   // merely doing a horizontal sum if necessary to get the wider element
18648   // counts.
18649   if (EltVT == MVT::i8)
18650     return V;
18651
18652   return LowerHorizontalByteSum(
18653       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18654       DAG);
18655 }
18656
18657 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18658                                 SelectionDAG &DAG) {
18659   MVT VT = Op.getSimpleValueType();
18660   // FIXME: Need to add AVX-512 support here!
18661   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18662          "Unknown CTPOP type to handle");
18663   SDLoc DL(Op.getNode());
18664   SDValue Op0 = Op.getOperand(0);
18665
18666   if (!Subtarget->hasSSSE3()) {
18667     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18668     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18669     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18670   }
18671
18672   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18673     unsigned NumElems = VT.getVectorNumElements();
18674
18675     // Extract each 128-bit vector, compute pop count and concat the result.
18676     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18677     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18678
18679     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18680                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18681                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18682   }
18683
18684   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18685 }
18686
18687 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18688                           SelectionDAG &DAG) {
18689   assert(Op.getValueType().isVector() &&
18690          "We only do custom lowering for vector population count.");
18691   return LowerVectorCTPOP(Op, Subtarget, DAG);
18692 }
18693
18694 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18695   SDNode *Node = Op.getNode();
18696   SDLoc dl(Node);
18697   EVT T = Node->getValueType(0);
18698   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18699                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18700   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18701                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18702                        Node->getOperand(0),
18703                        Node->getOperand(1), negOp,
18704                        cast<AtomicSDNode>(Node)->getMemOperand(),
18705                        cast<AtomicSDNode>(Node)->getOrdering(),
18706                        cast<AtomicSDNode>(Node)->getSynchScope());
18707 }
18708
18709 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18710   SDNode *Node = Op.getNode();
18711   SDLoc dl(Node);
18712   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18713
18714   // Convert seq_cst store -> xchg
18715   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18716   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18717   //        (The only way to get a 16-byte store is cmpxchg16b)
18718   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18719   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18720       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18721     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18722                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18723                                  Node->getOperand(0),
18724                                  Node->getOperand(1), Node->getOperand(2),
18725                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18726                                  cast<AtomicSDNode>(Node)->getOrdering(),
18727                                  cast<AtomicSDNode>(Node)->getSynchScope());
18728     return Swap.getValue(1);
18729   }
18730   // Other atomic stores have a simple pattern.
18731   return Op;
18732 }
18733
18734 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18735   EVT VT = Op.getNode()->getSimpleValueType(0);
18736
18737   // Let legalize expand this if it isn't a legal type yet.
18738   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18739     return SDValue();
18740
18741   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18742
18743   unsigned Opc;
18744   bool ExtraOp = false;
18745   switch (Op.getOpcode()) {
18746   default: llvm_unreachable("Invalid code");
18747   case ISD::ADDC: Opc = X86ISD::ADD; break;
18748   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18749   case ISD::SUBC: Opc = X86ISD::SUB; break;
18750   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18751   }
18752
18753   if (!ExtraOp)
18754     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18755                        Op.getOperand(1));
18756   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18757                      Op.getOperand(1), Op.getOperand(2));
18758 }
18759
18760 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18761                             SelectionDAG &DAG) {
18762   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18763
18764   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18765   // which returns the values as { float, float } (in XMM0) or
18766   // { double, double } (which is returned in XMM0, XMM1).
18767   SDLoc dl(Op);
18768   SDValue Arg = Op.getOperand(0);
18769   EVT ArgVT = Arg.getValueType();
18770   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18771
18772   TargetLowering::ArgListTy Args;
18773   TargetLowering::ArgListEntry Entry;
18774
18775   Entry.Node = Arg;
18776   Entry.Ty = ArgTy;
18777   Entry.isSExt = false;
18778   Entry.isZExt = false;
18779   Args.push_back(Entry);
18780
18781   bool isF64 = ArgVT == MVT::f64;
18782   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18783   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18784   // the results are returned via SRet in memory.
18785   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18786   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18787   SDValue Callee =
18788       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18789
18790   Type *RetTy = isF64
18791     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18792     : (Type*)VectorType::get(ArgTy, 4);
18793
18794   TargetLowering::CallLoweringInfo CLI(DAG);
18795   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18796     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18797
18798   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18799
18800   if (isF64)
18801     // Returned in xmm0 and xmm1.
18802     return CallResult.first;
18803
18804   // Returned in bits 0:31 and 32:64 xmm0.
18805   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18806                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18807   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18808                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18809   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18810   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18811 }
18812
18813 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18814                              SelectionDAG &DAG) {
18815   assert(Subtarget->hasAVX512() &&
18816          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18817
18818   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18819   EVT VT = N->getValue().getValueType();
18820   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18821   SDLoc dl(Op);
18822
18823   // X86 scatter kills mask register, so its type should be added to
18824   // the list of return values
18825   if (N->getNumValues() == 1) {
18826     SDValue Index = N->getIndex();
18827     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18828         !Index.getValueType().is512BitVector())
18829       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18830
18831     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18832     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18833                       N->getOperand(3), Index };
18834
18835     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18836     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18837     return SDValue(NewScatter.getNode(), 0);
18838   }
18839   return Op;
18840 }
18841
18842 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18843                             SelectionDAG &DAG) {
18844   assert(Subtarget->hasAVX512() &&
18845          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18846
18847   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18848   EVT VT = Op.getValueType();
18849   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18850   SDLoc dl(Op);
18851
18852   SDValue Index = N->getIndex();
18853   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18854       !Index.getValueType().is512BitVector()) {
18855     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18856     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18857                       N->getOperand(3), Index };
18858     DAG.UpdateNodeOperands(N, Ops);
18859   }
18860   return Op;
18861 }
18862
18863 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18864                                                     SelectionDAG &DAG) const {
18865   // TODO: Eventually, the lowering of these nodes should be informed by or
18866   // deferred to the GC strategy for the function in which they appear. For
18867   // now, however, they must be lowered to something. Since they are logically
18868   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18869   // require special handling for these nodes), lower them as literal NOOPs for
18870   // the time being.
18871   SmallVector<SDValue, 2> Ops;
18872
18873   Ops.push_back(Op.getOperand(0));
18874   if (Op->getGluedNode())
18875     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18876
18877   SDLoc OpDL(Op);
18878   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18879   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18880
18881   return NOOP;
18882 }
18883
18884 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18885                                                   SelectionDAG &DAG) const {
18886   // TODO: Eventually, the lowering of these nodes should be informed by or
18887   // deferred to the GC strategy for the function in which they appear. For
18888   // now, however, they must be lowered to something. Since they are logically
18889   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18890   // require special handling for these nodes), lower them as literal NOOPs for
18891   // the time being.
18892   SmallVector<SDValue, 2> Ops;
18893
18894   Ops.push_back(Op.getOperand(0));
18895   if (Op->getGluedNode())
18896     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18897
18898   SDLoc OpDL(Op);
18899   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18900   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18901
18902   return NOOP;
18903 }
18904
18905 /// LowerOperation - Provide custom lowering hooks for some operations.
18906 ///
18907 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18908   switch (Op.getOpcode()) {
18909   default: llvm_unreachable("Should not custom lower this!");
18910   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18911   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18912     return LowerCMP_SWAP(Op, Subtarget, DAG);
18913   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18914   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18915   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18916   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18917   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18918   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18919   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18920   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18921   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18922   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18923   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18924   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18925   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18926   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18927   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18928   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18929   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18930   case ISD::SHL_PARTS:
18931   case ISD::SRA_PARTS:
18932   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18933   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18934   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18935   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18936   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18937   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18938   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18939   case ISD::SIGN_EXTEND_VECTOR_INREG:
18940     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18941   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18942   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18943   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18944   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18945   case ISD::FABS:
18946   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18947   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18948   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18949   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18950   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18951   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18952   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18953   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18954   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18955   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18956   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18957   case ISD::INTRINSIC_VOID:
18958   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18959   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18960   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18961   case ISD::FRAME_TO_ARGS_OFFSET:
18962                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18963   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18964   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18965   case ISD::CATCHRET:           return LowerCATCHRET(Op, DAG);
18966   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18967   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18968   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18969   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18970   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18971   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18972   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18973   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18974   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18975   case ISD::UMUL_LOHI:
18976   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18977   case ISD::SRA:
18978   case ISD::SRL:
18979   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18980   case ISD::SADDO:
18981   case ISD::UADDO:
18982   case ISD::SSUBO:
18983   case ISD::USUBO:
18984   case ISD::SMULO:
18985   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18986   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18987   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18988   case ISD::ADDC:
18989   case ISD::ADDE:
18990   case ISD::SUBC:
18991   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18992   case ISD::ADD:                return LowerADD(Op, DAG);
18993   case ISD::SUB:                return LowerSUB(Op, DAG);
18994   case ISD::SMAX:
18995   case ISD::SMIN:
18996   case ISD::UMAX:
18997   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
18998   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18999   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
19000   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
19001   case ISD::GC_TRANSITION_START:
19002                                 return LowerGC_TRANSITION_START(Op, DAG);
19003   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
19004   }
19005 }
19006
19007 /// ReplaceNodeResults - Replace a node with an illegal result type
19008 /// with a new node built out of custom code.
19009 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19010                                            SmallVectorImpl<SDValue>&Results,
19011                                            SelectionDAG &DAG) const {
19012   SDLoc dl(N);
19013   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19014   switch (N->getOpcode()) {
19015   default:
19016     llvm_unreachable("Do not know how to custom type legalize this operation!");
19017   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19018   case X86ISD::FMINC:
19019   case X86ISD::FMIN:
19020   case X86ISD::FMAXC:
19021   case X86ISD::FMAX: {
19022     EVT VT = N->getValueType(0);
19023     if (VT != MVT::v2f32)
19024       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19025     SDValue UNDEF = DAG.getUNDEF(VT);
19026     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19027                               N->getOperand(0), UNDEF);
19028     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19029                               N->getOperand(1), UNDEF);
19030     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19031     return;
19032   }
19033   case ISD::SIGN_EXTEND_INREG:
19034   case ISD::ADDC:
19035   case ISD::ADDE:
19036   case ISD::SUBC:
19037   case ISD::SUBE:
19038     // We don't want to expand or promote these.
19039     return;
19040   case ISD::SDIV:
19041   case ISD::UDIV:
19042   case ISD::SREM:
19043   case ISD::UREM:
19044   case ISD::SDIVREM:
19045   case ISD::UDIVREM: {
19046     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19047     Results.push_back(V);
19048     return;
19049   }
19050   case ISD::FP_TO_SINT:
19051   case ISD::FP_TO_UINT: {
19052     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19053
19054     std::pair<SDValue,SDValue> Vals =
19055         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19056     SDValue FIST = Vals.first, StackSlot = Vals.second;
19057     if (FIST.getNode()) {
19058       EVT VT = N->getValueType(0);
19059       // Return a load from the stack slot.
19060       if (StackSlot.getNode())
19061         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19062                                       MachinePointerInfo(),
19063                                       false, false, false, 0));
19064       else
19065         Results.push_back(FIST);
19066     }
19067     return;
19068   }
19069   case ISD::UINT_TO_FP: {
19070     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19071     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19072         N->getValueType(0) != MVT::v2f32)
19073       return;
19074     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19075                                  N->getOperand(0));
19076     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19077                                      MVT::f64);
19078     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19079     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19080                              DAG.getBitcast(MVT::v2i64, VBias));
19081     Or = DAG.getBitcast(MVT::v2f64, Or);
19082     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19083     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19084     return;
19085   }
19086   case ISD::FP_ROUND: {
19087     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19088         return;
19089     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19090     Results.push_back(V);
19091     return;
19092   }
19093   case ISD::FP_EXTEND: {
19094     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19095     // No other ValueType for FP_EXTEND should reach this point.
19096     assert(N->getValueType(0) == MVT::v2f32 &&
19097            "Do not know how to legalize this Node");
19098     return;
19099   }
19100   case ISD::INTRINSIC_W_CHAIN: {
19101     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19102     switch (IntNo) {
19103     default : llvm_unreachable("Do not know how to custom type "
19104                                "legalize this intrinsic operation!");
19105     case Intrinsic::x86_rdtsc:
19106       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19107                                      Results);
19108     case Intrinsic::x86_rdtscp:
19109       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19110                                      Results);
19111     case Intrinsic::x86_rdpmc:
19112       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19113     }
19114   }
19115   case ISD::READCYCLECOUNTER: {
19116     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19117                                    Results);
19118   }
19119   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19120     EVT T = N->getValueType(0);
19121     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19122     bool Regs64bit = T == MVT::i128;
19123     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19124     SDValue cpInL, cpInH;
19125     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19126                         DAG.getConstant(0, dl, HalfT));
19127     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19128                         DAG.getConstant(1, dl, HalfT));
19129     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19130                              Regs64bit ? X86::RAX : X86::EAX,
19131                              cpInL, SDValue());
19132     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19133                              Regs64bit ? X86::RDX : X86::EDX,
19134                              cpInH, cpInL.getValue(1));
19135     SDValue swapInL, swapInH;
19136     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19137                           DAG.getConstant(0, dl, HalfT));
19138     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19139                           DAG.getConstant(1, dl, HalfT));
19140     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19141                                Regs64bit ? X86::RBX : X86::EBX,
19142                                swapInL, cpInH.getValue(1));
19143     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19144                                Regs64bit ? X86::RCX : X86::ECX,
19145                                swapInH, swapInL.getValue(1));
19146     SDValue Ops[] = { swapInH.getValue(0),
19147                       N->getOperand(1),
19148                       swapInH.getValue(1) };
19149     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19150     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19151     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19152                                   X86ISD::LCMPXCHG8_DAG;
19153     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19154     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19155                                         Regs64bit ? X86::RAX : X86::EAX,
19156                                         HalfT, Result.getValue(1));
19157     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19158                                         Regs64bit ? X86::RDX : X86::EDX,
19159                                         HalfT, cpOutL.getValue(2));
19160     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19161
19162     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19163                                         MVT::i32, cpOutH.getValue(2));
19164     SDValue Success =
19165         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19166                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19167     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19168
19169     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19170     Results.push_back(Success);
19171     Results.push_back(EFLAGS.getValue(1));
19172     return;
19173   }
19174   case ISD::ATOMIC_SWAP:
19175   case ISD::ATOMIC_LOAD_ADD:
19176   case ISD::ATOMIC_LOAD_SUB:
19177   case ISD::ATOMIC_LOAD_AND:
19178   case ISD::ATOMIC_LOAD_OR:
19179   case ISD::ATOMIC_LOAD_XOR:
19180   case ISD::ATOMIC_LOAD_NAND:
19181   case ISD::ATOMIC_LOAD_MIN:
19182   case ISD::ATOMIC_LOAD_MAX:
19183   case ISD::ATOMIC_LOAD_UMIN:
19184   case ISD::ATOMIC_LOAD_UMAX:
19185   case ISD::ATOMIC_LOAD: {
19186     // Delegate to generic TypeLegalization. Situations we can really handle
19187     // should have already been dealt with by AtomicExpandPass.cpp.
19188     break;
19189   }
19190   case ISD::BITCAST: {
19191     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19192     EVT DstVT = N->getValueType(0);
19193     EVT SrcVT = N->getOperand(0)->getValueType(0);
19194
19195     if (SrcVT != MVT::f64 ||
19196         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19197       return;
19198
19199     unsigned NumElts = DstVT.getVectorNumElements();
19200     EVT SVT = DstVT.getVectorElementType();
19201     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19202     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19203                                    MVT::v2f64, N->getOperand(0));
19204     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19205
19206     if (ExperimentalVectorWideningLegalization) {
19207       // If we are legalizing vectors by widening, we already have the desired
19208       // legal vector type, just return it.
19209       Results.push_back(ToVecInt);
19210       return;
19211     }
19212
19213     SmallVector<SDValue, 8> Elts;
19214     for (unsigned i = 0, e = NumElts; i != e; ++i)
19215       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19216                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19217
19218     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19219   }
19220   }
19221 }
19222
19223 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19224   switch ((X86ISD::NodeType)Opcode) {
19225   case X86ISD::FIRST_NUMBER:       break;
19226   case X86ISD::BSF:                return "X86ISD::BSF";
19227   case X86ISD::BSR:                return "X86ISD::BSR";
19228   case X86ISD::SHLD:               return "X86ISD::SHLD";
19229   case X86ISD::SHRD:               return "X86ISD::SHRD";
19230   case X86ISD::FAND:               return "X86ISD::FAND";
19231   case X86ISD::FANDN:              return "X86ISD::FANDN";
19232   case X86ISD::FOR:                return "X86ISD::FOR";
19233   case X86ISD::FXOR:               return "X86ISD::FXOR";
19234   case X86ISD::FILD:               return "X86ISD::FILD";
19235   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19236   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19237   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19238   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19239   case X86ISD::FLD:                return "X86ISD::FLD";
19240   case X86ISD::FST:                return "X86ISD::FST";
19241   case X86ISD::CALL:               return "X86ISD::CALL";
19242   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19243   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19244   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19245   case X86ISD::BT:                 return "X86ISD::BT";
19246   case X86ISD::CMP:                return "X86ISD::CMP";
19247   case X86ISD::COMI:               return "X86ISD::COMI";
19248   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19249   case X86ISD::CMPM:               return "X86ISD::CMPM";
19250   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19251   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19252   case X86ISD::SETCC:              return "X86ISD::SETCC";
19253   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19254   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19255   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19256   case X86ISD::CMOV:               return "X86ISD::CMOV";
19257   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19258   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19259   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19260   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19261   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19262   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19263   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19264   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19265   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19266   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19267   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19268   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19269   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19270   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19271   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19272   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19273   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19274   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19275   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19276   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19277   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19278   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19279   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19280   case X86ISD::HADD:               return "X86ISD::HADD";
19281   case X86ISD::HSUB:               return "X86ISD::HSUB";
19282   case X86ISD::FHADD:              return "X86ISD::FHADD";
19283   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19284   case X86ISD::ABS:                return "X86ISD::ABS";
19285   case X86ISD::FMAX:               return "X86ISD::FMAX";
19286   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19287   case X86ISD::FMIN:               return "X86ISD::FMIN";
19288   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19289   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19290   case X86ISD::FMINC:              return "X86ISD::FMINC";
19291   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19292   case X86ISD::FRCP:               return "X86ISD::FRCP";
19293   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19294   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19295   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19296   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19297   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19298   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19299   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19300   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19301   case X86ISD::CATCHRET:           return "X86ISD::CATCHRET";
19302   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19303   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19304   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19305   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19306   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19307   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19308   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19309   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19310   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19311   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19312   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19313   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19314   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19315   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19316   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19317   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19318   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19319   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19320   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19321   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19322   case X86ISD::VSHL:               return "X86ISD::VSHL";
19323   case X86ISD::VSRL:               return "X86ISD::VSRL";
19324   case X86ISD::VSRA:               return "X86ISD::VSRA";
19325   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19326   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19327   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19328   case X86ISD::CMPP:               return "X86ISD::CMPP";
19329   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19330   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19331   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19332   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19333   case X86ISD::ADD:                return "X86ISD::ADD";
19334   case X86ISD::SUB:                return "X86ISD::SUB";
19335   case X86ISD::ADC:                return "X86ISD::ADC";
19336   case X86ISD::SBB:                return "X86ISD::SBB";
19337   case X86ISD::SMUL:               return "X86ISD::SMUL";
19338   case X86ISD::UMUL:               return "X86ISD::UMUL";
19339   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19340   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19341   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19342   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19343   case X86ISD::INC:                return "X86ISD::INC";
19344   case X86ISD::DEC:                return "X86ISD::DEC";
19345   case X86ISD::OR:                 return "X86ISD::OR";
19346   case X86ISD::XOR:                return "X86ISD::XOR";
19347   case X86ISD::AND:                return "X86ISD::AND";
19348   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19349   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19350   case X86ISD::PTEST:              return "X86ISD::PTEST";
19351   case X86ISD::TESTP:              return "X86ISD::TESTP";
19352   case X86ISD::TESTM:              return "X86ISD::TESTM";
19353   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19354   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19355   case X86ISD::KTEST:              return "X86ISD::KTEST";
19356   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19357   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19358   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19359   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19360   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19361   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19362   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19363   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19364   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19365   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19366   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19367   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19368   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19369   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19370   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19371   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19372   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19373   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19374   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19375   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19376   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19377   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19378   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19379   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19380   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19381   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19382   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19383   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19384   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19385   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19386   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19387   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19388   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19389   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19390   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19391   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19392   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
19393   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19394   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19395   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19396   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19397   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19398   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19399   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19400   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19401   case X86ISD::SAHF:               return "X86ISD::SAHF";
19402   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19403   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19404   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19405   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19406   case X86ISD::FMADD:              return "X86ISD::FMADD";
19407   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19408   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19409   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19410   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19411   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19412   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19413   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19414   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19415   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19416   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19417   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19418   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19419   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19420   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
19421   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19422   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19423   case X86ISD::XTEST:              return "X86ISD::XTEST";
19424   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19425   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19426   case X86ISD::SELECT:             return "X86ISD::SELECT";
19427   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19428   case X86ISD::RCP28:              return "X86ISD::RCP28";
19429   case X86ISD::EXP2:               return "X86ISD::EXP2";
19430   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19431   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19432   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19433   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19434   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19435   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19436   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19437   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19438   case X86ISD::ADDS:               return "X86ISD::ADDS";
19439   case X86ISD::SUBS:               return "X86ISD::SUBS";
19440   case X86ISD::AVG:                return "X86ISD::AVG";
19441   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19442   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19443   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19444   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19445   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19446   }
19447   return nullptr;
19448 }
19449
19450 // isLegalAddressingMode - Return true if the addressing mode represented
19451 // by AM is legal for this target, for a load/store of the specified type.
19452 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19453                                               const AddrMode &AM, Type *Ty,
19454                                               unsigned AS) const {
19455   // X86 supports extremely general addressing modes.
19456   CodeModel::Model M = getTargetMachine().getCodeModel();
19457   Reloc::Model R = getTargetMachine().getRelocationModel();
19458
19459   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19460   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19461     return false;
19462
19463   if (AM.BaseGV) {
19464     unsigned GVFlags =
19465       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19466
19467     // If a reference to this global requires an extra load, we can't fold it.
19468     if (isGlobalStubReference(GVFlags))
19469       return false;
19470
19471     // If BaseGV requires a register for the PIC base, we cannot also have a
19472     // BaseReg specified.
19473     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19474       return false;
19475
19476     // If lower 4G is not available, then we must use rip-relative addressing.
19477     if ((M != CodeModel::Small || R != Reloc::Static) &&
19478         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19479       return false;
19480   }
19481
19482   switch (AM.Scale) {
19483   case 0:
19484   case 1:
19485   case 2:
19486   case 4:
19487   case 8:
19488     // These scales always work.
19489     break;
19490   case 3:
19491   case 5:
19492   case 9:
19493     // These scales are formed with basereg+scalereg.  Only accept if there is
19494     // no basereg yet.
19495     if (AM.HasBaseReg)
19496       return false;
19497     break;
19498   default:  // Other stuff never works.
19499     return false;
19500   }
19501
19502   return true;
19503 }
19504
19505 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19506   unsigned Bits = Ty->getScalarSizeInBits();
19507
19508   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19509   // particularly cheaper than those without.
19510   if (Bits == 8)
19511     return false;
19512
19513   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19514   // variable shifts just as cheap as scalar ones.
19515   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19516     return false;
19517
19518   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19519   // fully general vector.
19520   return true;
19521 }
19522
19523 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19524   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19525     return false;
19526   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19527   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19528   return NumBits1 > NumBits2;
19529 }
19530
19531 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19532   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19533     return false;
19534
19535   if (!isTypeLegal(EVT::getEVT(Ty1)))
19536     return false;
19537
19538   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19539
19540   // Assuming the caller doesn't have a zeroext or signext return parameter,
19541   // truncation all the way down to i1 is valid.
19542   return true;
19543 }
19544
19545 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19546   return isInt<32>(Imm);
19547 }
19548
19549 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19550   // Can also use sub to handle negated immediates.
19551   return isInt<32>(Imm);
19552 }
19553
19554 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19555   if (!VT1.isInteger() || !VT2.isInteger())
19556     return false;
19557   unsigned NumBits1 = VT1.getSizeInBits();
19558   unsigned NumBits2 = VT2.getSizeInBits();
19559   return NumBits1 > NumBits2;
19560 }
19561
19562 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19563   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19564   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19565 }
19566
19567 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19568   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19569   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19570 }
19571
19572 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19573   EVT VT1 = Val.getValueType();
19574   if (isZExtFree(VT1, VT2))
19575     return true;
19576
19577   if (Val.getOpcode() != ISD::LOAD)
19578     return false;
19579
19580   if (!VT1.isSimple() || !VT1.isInteger() ||
19581       !VT2.isSimple() || !VT2.isInteger())
19582     return false;
19583
19584   switch (VT1.getSimpleVT().SimpleTy) {
19585   default: break;
19586   case MVT::i8:
19587   case MVT::i16:
19588   case MVT::i32:
19589     // X86 has 8, 16, and 32-bit zero-extending loads.
19590     return true;
19591   }
19592
19593   return false;
19594 }
19595
19596 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19597
19598 bool
19599 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19600   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19601     return false;
19602
19603   VT = VT.getScalarType();
19604
19605   if (!VT.isSimple())
19606     return false;
19607
19608   switch (VT.getSimpleVT().SimpleTy) {
19609   case MVT::f32:
19610   case MVT::f64:
19611     return true;
19612   default:
19613     break;
19614   }
19615
19616   return false;
19617 }
19618
19619 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19620   // i16 instructions are longer (0x66 prefix) and potentially slower.
19621   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19622 }
19623
19624 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19625 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19626 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19627 /// are assumed to be legal.
19628 bool
19629 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19630                                       EVT VT) const {
19631   if (!VT.isSimple())
19632     return false;
19633
19634   // Not for i1 vectors
19635   if (VT.getScalarType() == MVT::i1)
19636     return false;
19637
19638   // Very little shuffling can be done for 64-bit vectors right now.
19639   if (VT.getSizeInBits() == 64)
19640     return false;
19641
19642   // We only care that the types being shuffled are legal. The lowering can
19643   // handle any possible shuffle mask that results.
19644   return isTypeLegal(VT.getSimpleVT());
19645 }
19646
19647 bool
19648 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19649                                           EVT VT) const {
19650   // Just delegate to the generic legality, clear masks aren't special.
19651   return isShuffleMaskLegal(Mask, VT);
19652 }
19653
19654 //===----------------------------------------------------------------------===//
19655 //                           X86 Scheduler Hooks
19656 //===----------------------------------------------------------------------===//
19657
19658 /// Utility function to emit xbegin specifying the start of an RTM region.
19659 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19660                                      const TargetInstrInfo *TII) {
19661   DebugLoc DL = MI->getDebugLoc();
19662
19663   const BasicBlock *BB = MBB->getBasicBlock();
19664   MachineFunction::iterator I = MBB;
19665   ++I;
19666
19667   // For the v = xbegin(), we generate
19668   //
19669   // thisMBB:
19670   //  xbegin sinkMBB
19671   //
19672   // mainMBB:
19673   //  eax = -1
19674   //
19675   // sinkMBB:
19676   //  v = eax
19677
19678   MachineBasicBlock *thisMBB = MBB;
19679   MachineFunction *MF = MBB->getParent();
19680   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19681   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19682   MF->insert(I, mainMBB);
19683   MF->insert(I, sinkMBB);
19684
19685   // Transfer the remainder of BB and its successor edges to sinkMBB.
19686   sinkMBB->splice(sinkMBB->begin(), MBB,
19687                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19688   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19689
19690   // thisMBB:
19691   //  xbegin sinkMBB
19692   //  # fallthrough to mainMBB
19693   //  # abortion to sinkMBB
19694   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19695   thisMBB->addSuccessor(mainMBB);
19696   thisMBB->addSuccessor(sinkMBB);
19697
19698   // mainMBB:
19699   //  EAX = -1
19700   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19701   mainMBB->addSuccessor(sinkMBB);
19702
19703   // sinkMBB:
19704   // EAX is live into the sinkMBB
19705   sinkMBB->addLiveIn(X86::EAX);
19706   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19707           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19708     .addReg(X86::EAX);
19709
19710   MI->eraseFromParent();
19711   return sinkMBB;
19712 }
19713
19714 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19715 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19716 // in the .td file.
19717 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19718                                        const TargetInstrInfo *TII) {
19719   unsigned Opc;
19720   switch (MI->getOpcode()) {
19721   default: llvm_unreachable("illegal opcode!");
19722   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19723   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19724   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19725   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19726   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19727   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19728   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19729   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19730   }
19731
19732   DebugLoc dl = MI->getDebugLoc();
19733   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19734
19735   unsigned NumArgs = MI->getNumOperands();
19736   for (unsigned i = 1; i < NumArgs; ++i) {
19737     MachineOperand &Op = MI->getOperand(i);
19738     if (!(Op.isReg() && Op.isImplicit()))
19739       MIB.addOperand(Op);
19740   }
19741   if (MI->hasOneMemOperand())
19742     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19743
19744   BuildMI(*BB, MI, dl,
19745     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19746     .addReg(X86::XMM0);
19747
19748   MI->eraseFromParent();
19749   return BB;
19750 }
19751
19752 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19753 // defs in an instruction pattern
19754 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19755                                        const TargetInstrInfo *TII) {
19756   unsigned Opc;
19757   switch (MI->getOpcode()) {
19758   default: llvm_unreachable("illegal opcode!");
19759   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19760   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19761   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19762   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19763   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19764   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19765   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19766   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19767   }
19768
19769   DebugLoc dl = MI->getDebugLoc();
19770   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19771
19772   unsigned NumArgs = MI->getNumOperands(); // remove the results
19773   for (unsigned i = 1; i < NumArgs; ++i) {
19774     MachineOperand &Op = MI->getOperand(i);
19775     if (!(Op.isReg() && Op.isImplicit()))
19776       MIB.addOperand(Op);
19777   }
19778   if (MI->hasOneMemOperand())
19779     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19780
19781   BuildMI(*BB, MI, dl,
19782     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19783     .addReg(X86::ECX);
19784
19785   MI->eraseFromParent();
19786   return BB;
19787 }
19788
19789 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19790                                       const X86Subtarget *Subtarget) {
19791   DebugLoc dl = MI->getDebugLoc();
19792   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19793   // Address into RAX/EAX, other two args into ECX, EDX.
19794   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19795   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19796   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19797   for (int i = 0; i < X86::AddrNumOperands; ++i)
19798     MIB.addOperand(MI->getOperand(i));
19799
19800   unsigned ValOps = X86::AddrNumOperands;
19801   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19802     .addReg(MI->getOperand(ValOps).getReg());
19803   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19804     .addReg(MI->getOperand(ValOps+1).getReg());
19805
19806   // The instruction doesn't actually take any operands though.
19807   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19808
19809   MI->eraseFromParent(); // The pseudo is gone now.
19810   return BB;
19811 }
19812
19813 MachineBasicBlock *
19814 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19815                                                  MachineBasicBlock *MBB) const {
19816   // Emit va_arg instruction on X86-64.
19817
19818   // Operands to this pseudo-instruction:
19819   // 0  ) Output        : destination address (reg)
19820   // 1-5) Input         : va_list address (addr, i64mem)
19821   // 6  ) ArgSize       : Size (in bytes) of vararg type
19822   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19823   // 8  ) Align         : Alignment of type
19824   // 9  ) EFLAGS (implicit-def)
19825
19826   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19827   static_assert(X86::AddrNumOperands == 5,
19828                 "VAARG_64 assumes 5 address operands");
19829
19830   unsigned DestReg = MI->getOperand(0).getReg();
19831   MachineOperand &Base = MI->getOperand(1);
19832   MachineOperand &Scale = MI->getOperand(2);
19833   MachineOperand &Index = MI->getOperand(3);
19834   MachineOperand &Disp = MI->getOperand(4);
19835   MachineOperand &Segment = MI->getOperand(5);
19836   unsigned ArgSize = MI->getOperand(6).getImm();
19837   unsigned ArgMode = MI->getOperand(7).getImm();
19838   unsigned Align = MI->getOperand(8).getImm();
19839
19840   // Memory Reference
19841   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19842   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19843   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19844
19845   // Machine Information
19846   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19847   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19848   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19849   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19850   DebugLoc DL = MI->getDebugLoc();
19851
19852   // struct va_list {
19853   //   i32   gp_offset
19854   //   i32   fp_offset
19855   //   i64   overflow_area (address)
19856   //   i64   reg_save_area (address)
19857   // }
19858   // sizeof(va_list) = 24
19859   // alignment(va_list) = 8
19860
19861   unsigned TotalNumIntRegs = 6;
19862   unsigned TotalNumXMMRegs = 8;
19863   bool UseGPOffset = (ArgMode == 1);
19864   bool UseFPOffset = (ArgMode == 2);
19865   unsigned MaxOffset = TotalNumIntRegs * 8 +
19866                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19867
19868   /* Align ArgSize to a multiple of 8 */
19869   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19870   bool NeedsAlign = (Align > 8);
19871
19872   MachineBasicBlock *thisMBB = MBB;
19873   MachineBasicBlock *overflowMBB;
19874   MachineBasicBlock *offsetMBB;
19875   MachineBasicBlock *endMBB;
19876
19877   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19878   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19879   unsigned OffsetReg = 0;
19880
19881   if (!UseGPOffset && !UseFPOffset) {
19882     // If we only pull from the overflow region, we don't create a branch.
19883     // We don't need to alter control flow.
19884     OffsetDestReg = 0; // unused
19885     OverflowDestReg = DestReg;
19886
19887     offsetMBB = nullptr;
19888     overflowMBB = thisMBB;
19889     endMBB = thisMBB;
19890   } else {
19891     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19892     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19893     // If not, pull from overflow_area. (branch to overflowMBB)
19894     //
19895     //       thisMBB
19896     //         |     .
19897     //         |        .
19898     //     offsetMBB   overflowMBB
19899     //         |        .
19900     //         |     .
19901     //        endMBB
19902
19903     // Registers for the PHI in endMBB
19904     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19905     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19906
19907     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19908     MachineFunction *MF = MBB->getParent();
19909     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19910     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19911     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19912
19913     MachineFunction::iterator MBBIter = MBB;
19914     ++MBBIter;
19915
19916     // Insert the new basic blocks
19917     MF->insert(MBBIter, offsetMBB);
19918     MF->insert(MBBIter, overflowMBB);
19919     MF->insert(MBBIter, endMBB);
19920
19921     // Transfer the remainder of MBB and its successor edges to endMBB.
19922     endMBB->splice(endMBB->begin(), thisMBB,
19923                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19924     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19925
19926     // Make offsetMBB and overflowMBB successors of thisMBB
19927     thisMBB->addSuccessor(offsetMBB);
19928     thisMBB->addSuccessor(overflowMBB);
19929
19930     // endMBB is a successor of both offsetMBB and overflowMBB
19931     offsetMBB->addSuccessor(endMBB);
19932     overflowMBB->addSuccessor(endMBB);
19933
19934     // Load the offset value into a register
19935     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19936     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19937       .addOperand(Base)
19938       .addOperand(Scale)
19939       .addOperand(Index)
19940       .addDisp(Disp, UseFPOffset ? 4 : 0)
19941       .addOperand(Segment)
19942       .setMemRefs(MMOBegin, MMOEnd);
19943
19944     // Check if there is enough room left to pull this argument.
19945     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19946       .addReg(OffsetReg)
19947       .addImm(MaxOffset + 8 - ArgSizeA8);
19948
19949     // Branch to "overflowMBB" if offset >= max
19950     // Fall through to "offsetMBB" otherwise
19951     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19952       .addMBB(overflowMBB);
19953   }
19954
19955   // In offsetMBB, emit code to use the reg_save_area.
19956   if (offsetMBB) {
19957     assert(OffsetReg != 0);
19958
19959     // Read the reg_save_area address.
19960     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19961     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19962       .addOperand(Base)
19963       .addOperand(Scale)
19964       .addOperand(Index)
19965       .addDisp(Disp, 16)
19966       .addOperand(Segment)
19967       .setMemRefs(MMOBegin, MMOEnd);
19968
19969     // Zero-extend the offset
19970     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19971       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19972         .addImm(0)
19973         .addReg(OffsetReg)
19974         .addImm(X86::sub_32bit);
19975
19976     // Add the offset to the reg_save_area to get the final address.
19977     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19978       .addReg(OffsetReg64)
19979       .addReg(RegSaveReg);
19980
19981     // Compute the offset for the next argument
19982     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19983     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19984       .addReg(OffsetReg)
19985       .addImm(UseFPOffset ? 16 : 8);
19986
19987     // Store it back into the va_list.
19988     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19989       .addOperand(Base)
19990       .addOperand(Scale)
19991       .addOperand(Index)
19992       .addDisp(Disp, UseFPOffset ? 4 : 0)
19993       .addOperand(Segment)
19994       .addReg(NextOffsetReg)
19995       .setMemRefs(MMOBegin, MMOEnd);
19996
19997     // Jump to endMBB
19998     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19999       .addMBB(endMBB);
20000   }
20001
20002   //
20003   // Emit code to use overflow area
20004   //
20005
20006   // Load the overflow_area address into a register.
20007   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20008   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20009     .addOperand(Base)
20010     .addOperand(Scale)
20011     .addOperand(Index)
20012     .addDisp(Disp, 8)
20013     .addOperand(Segment)
20014     .setMemRefs(MMOBegin, MMOEnd);
20015
20016   // If we need to align it, do so. Otherwise, just copy the address
20017   // to OverflowDestReg.
20018   if (NeedsAlign) {
20019     // Align the overflow address
20020     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20021     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20022
20023     // aligned_addr = (addr + (align-1)) & ~(align-1)
20024     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20025       .addReg(OverflowAddrReg)
20026       .addImm(Align-1);
20027
20028     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20029       .addReg(TmpReg)
20030       .addImm(~(uint64_t)(Align-1));
20031   } else {
20032     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20033       .addReg(OverflowAddrReg);
20034   }
20035
20036   // Compute the next overflow address after this argument.
20037   // (the overflow address should be kept 8-byte aligned)
20038   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20039   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20040     .addReg(OverflowDestReg)
20041     .addImm(ArgSizeA8);
20042
20043   // Store the new overflow address.
20044   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20045     .addOperand(Base)
20046     .addOperand(Scale)
20047     .addOperand(Index)
20048     .addDisp(Disp, 8)
20049     .addOperand(Segment)
20050     .addReg(NextAddrReg)
20051     .setMemRefs(MMOBegin, MMOEnd);
20052
20053   // If we branched, emit the PHI to the front of endMBB.
20054   if (offsetMBB) {
20055     BuildMI(*endMBB, endMBB->begin(), DL,
20056             TII->get(X86::PHI), DestReg)
20057       .addReg(OffsetDestReg).addMBB(offsetMBB)
20058       .addReg(OverflowDestReg).addMBB(overflowMBB);
20059   }
20060
20061   // Erase the pseudo instruction
20062   MI->eraseFromParent();
20063
20064   return endMBB;
20065 }
20066
20067 MachineBasicBlock *
20068 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20069                                                  MachineInstr *MI,
20070                                                  MachineBasicBlock *MBB) const {
20071   // Emit code to save XMM registers to the stack. The ABI says that the
20072   // number of registers to save is given in %al, so it's theoretically
20073   // possible to do an indirect jump trick to avoid saving all of them,
20074   // however this code takes a simpler approach and just executes all
20075   // of the stores if %al is non-zero. It's less code, and it's probably
20076   // easier on the hardware branch predictor, and stores aren't all that
20077   // expensive anyway.
20078
20079   // Create the new basic blocks. One block contains all the XMM stores,
20080   // and one block is the final destination regardless of whether any
20081   // stores were performed.
20082   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20083   MachineFunction *F = MBB->getParent();
20084   MachineFunction::iterator MBBIter = MBB;
20085   ++MBBIter;
20086   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20087   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20088   F->insert(MBBIter, XMMSaveMBB);
20089   F->insert(MBBIter, EndMBB);
20090
20091   // Transfer the remainder of MBB and its successor edges to EndMBB.
20092   EndMBB->splice(EndMBB->begin(), MBB,
20093                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20094   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20095
20096   // The original block will now fall through to the XMM save block.
20097   MBB->addSuccessor(XMMSaveMBB);
20098   // The XMMSaveMBB will fall through to the end block.
20099   XMMSaveMBB->addSuccessor(EndMBB);
20100
20101   // Now add the instructions.
20102   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20103   DebugLoc DL = MI->getDebugLoc();
20104
20105   unsigned CountReg = MI->getOperand(0).getReg();
20106   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20107   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20108
20109   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20110     // If %al is 0, branch around the XMM save block.
20111     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20112     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20113     MBB->addSuccessor(EndMBB);
20114   }
20115
20116   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20117   // that was just emitted, but clearly shouldn't be "saved".
20118   assert((MI->getNumOperands() <= 3 ||
20119           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20120           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20121          && "Expected last argument to be EFLAGS");
20122   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20123   // In the XMM save block, save all the XMM argument registers.
20124   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20125     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20126     MachineMemOperand *MMO = F->getMachineMemOperand(
20127         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20128         MachineMemOperand::MOStore,
20129         /*Size=*/16, /*Align=*/16);
20130     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20131       .addFrameIndex(RegSaveFrameIndex)
20132       .addImm(/*Scale=*/1)
20133       .addReg(/*IndexReg=*/0)
20134       .addImm(/*Disp=*/Offset)
20135       .addReg(/*Segment=*/0)
20136       .addReg(MI->getOperand(i).getReg())
20137       .addMemOperand(MMO);
20138   }
20139
20140   MI->eraseFromParent();   // The pseudo instruction is gone now.
20141
20142   return EndMBB;
20143 }
20144
20145 // The EFLAGS operand of SelectItr might be missing a kill marker
20146 // because there were multiple uses of EFLAGS, and ISel didn't know
20147 // which to mark. Figure out whether SelectItr should have had a
20148 // kill marker, and set it if it should. Returns the correct kill
20149 // marker value.
20150 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20151                                      MachineBasicBlock* BB,
20152                                      const TargetRegisterInfo* TRI) {
20153   // Scan forward through BB for a use/def of EFLAGS.
20154   MachineBasicBlock::iterator miI(std::next(SelectItr));
20155   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20156     const MachineInstr& mi = *miI;
20157     if (mi.readsRegister(X86::EFLAGS))
20158       return false;
20159     if (mi.definesRegister(X86::EFLAGS))
20160       break; // Should have kill-flag - update below.
20161   }
20162
20163   // If we hit the end of the block, check whether EFLAGS is live into a
20164   // successor.
20165   if (miI == BB->end()) {
20166     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20167                                           sEnd = BB->succ_end();
20168          sItr != sEnd; ++sItr) {
20169       MachineBasicBlock* succ = *sItr;
20170       if (succ->isLiveIn(X86::EFLAGS))
20171         return false;
20172     }
20173   }
20174
20175   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20176   // out. SelectMI should have a kill flag on EFLAGS.
20177   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20178   return true;
20179 }
20180
20181 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20182 // together with other CMOV pseudo-opcodes into a single basic-block with
20183 // conditional jump around it.
20184 static bool isCMOVPseudo(MachineInstr *MI) {
20185   switch (MI->getOpcode()) {
20186   case X86::CMOV_FR32:
20187   case X86::CMOV_FR64:
20188   case X86::CMOV_GR8:
20189   case X86::CMOV_GR16:
20190   case X86::CMOV_GR32:
20191   case X86::CMOV_RFP32:
20192   case X86::CMOV_RFP64:
20193   case X86::CMOV_RFP80:
20194   case X86::CMOV_V2F64:
20195   case X86::CMOV_V2I64:
20196   case X86::CMOV_V4F32:
20197   case X86::CMOV_V4F64:
20198   case X86::CMOV_V4I64:
20199   case X86::CMOV_V16F32:
20200   case X86::CMOV_V8F32:
20201   case X86::CMOV_V8F64:
20202   case X86::CMOV_V8I64:
20203   case X86::CMOV_V8I1:
20204   case X86::CMOV_V16I1:
20205   case X86::CMOV_V32I1:
20206   case X86::CMOV_V64I1:
20207     return true;
20208
20209   default:
20210     return false;
20211   }
20212 }
20213
20214 MachineBasicBlock *
20215 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20216                                      MachineBasicBlock *BB) const {
20217   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20218   DebugLoc DL = MI->getDebugLoc();
20219
20220   // To "insert" a SELECT_CC instruction, we actually have to insert the
20221   // diamond control-flow pattern.  The incoming instruction knows the
20222   // destination vreg to set, the condition code register to branch on, the
20223   // true/false values to select between, and a branch opcode to use.
20224   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20225   MachineFunction::iterator It = BB;
20226   ++It;
20227
20228   //  thisMBB:
20229   //  ...
20230   //   TrueVal = ...
20231   //   cmpTY ccX, r1, r2
20232   //   bCC copy1MBB
20233   //   fallthrough --> copy0MBB
20234   MachineBasicBlock *thisMBB = BB;
20235   MachineFunction *F = BB->getParent();
20236
20237   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20238   // as described above, by inserting a BB, and then making a PHI at the join
20239   // point to select the true and false operands of the CMOV in the PHI.
20240   //
20241   // The code also handles two different cases of multiple CMOV opcodes
20242   // in a row.
20243   //
20244   // Case 1:
20245   // In this case, there are multiple CMOVs in a row, all which are based on
20246   // the same condition setting (or the exact opposite condition setting).
20247   // In this case we can lower all the CMOVs using a single inserted BB, and
20248   // then make a number of PHIs at the join point to model the CMOVs. The only
20249   // trickiness here, is that in a case like:
20250   //
20251   // t2 = CMOV cond1 t1, f1
20252   // t3 = CMOV cond1 t2, f2
20253   //
20254   // when rewriting this into PHIs, we have to perform some renaming on the
20255   // temps since you cannot have a PHI operand refer to a PHI result earlier
20256   // in the same block.  The "simple" but wrong lowering would be:
20257   //
20258   // t2 = PHI t1(BB1), f1(BB2)
20259   // t3 = PHI t2(BB1), f2(BB2)
20260   //
20261   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20262   // renaming is to note that on the path through BB1, t2 is really just a
20263   // copy of t1, and do that renaming, properly generating:
20264   //
20265   // t2 = PHI t1(BB1), f1(BB2)
20266   // t3 = PHI t1(BB1), f2(BB2)
20267   //
20268   // Case 2, we lower cascaded CMOVs such as
20269   //
20270   //   (CMOV (CMOV F, T, cc1), T, cc2)
20271   //
20272   // to two successives branches.  For that, we look for another CMOV as the
20273   // following instruction.
20274   //
20275   // Without this, we would add a PHI between the two jumps, which ends up
20276   // creating a few copies all around. For instance, for
20277   //
20278   //    (sitofp (zext (fcmp une)))
20279   //
20280   // we would generate:
20281   //
20282   //         ucomiss %xmm1, %xmm0
20283   //         movss  <1.0f>, %xmm0
20284   //         movaps  %xmm0, %xmm1
20285   //         jne     .LBB5_2
20286   //         xorps   %xmm1, %xmm1
20287   // .LBB5_2:
20288   //         jp      .LBB5_4
20289   //         movaps  %xmm1, %xmm0
20290   // .LBB5_4:
20291   //         retq
20292   //
20293   // because this custom-inserter would have generated:
20294   //
20295   //   A
20296   //   | \
20297   //   |  B
20298   //   | /
20299   //   C
20300   //   | \
20301   //   |  D
20302   //   | /
20303   //   E
20304   //
20305   // A: X = ...; Y = ...
20306   // B: empty
20307   // C: Z = PHI [X, A], [Y, B]
20308   // D: empty
20309   // E: PHI [X, C], [Z, D]
20310   //
20311   // If we lower both CMOVs in a single step, we can instead generate:
20312   //
20313   //   A
20314   //   | \
20315   //   |  C
20316   //   | /|
20317   //   |/ |
20318   //   |  |
20319   //   |  D
20320   //   | /
20321   //   E
20322   //
20323   // A: X = ...; Y = ...
20324   // D: empty
20325   // E: PHI [X, A], [X, C], [Y, D]
20326   //
20327   // Which, in our sitofp/fcmp example, gives us something like:
20328   //
20329   //         ucomiss %xmm1, %xmm0
20330   //         movss  <1.0f>, %xmm0
20331   //         jne     .LBB5_4
20332   //         jp      .LBB5_4
20333   //         xorps   %xmm0, %xmm0
20334   // .LBB5_4:
20335   //         retq
20336   //
20337   MachineInstr *CascadedCMOV = nullptr;
20338   MachineInstr *LastCMOV = MI;
20339   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20340   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20341   MachineBasicBlock::iterator NextMIIt =
20342       std::next(MachineBasicBlock::iterator(MI));
20343
20344   // Check for case 1, where there are multiple CMOVs with the same condition
20345   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
20346   // number of jumps the most.
20347
20348   if (isCMOVPseudo(MI)) {
20349     // See if we have a string of CMOVS with the same condition.
20350     while (NextMIIt != BB->end() &&
20351            isCMOVPseudo(NextMIIt) &&
20352            (NextMIIt->getOperand(3).getImm() == CC ||
20353             NextMIIt->getOperand(3).getImm() == OppCC)) {
20354       LastCMOV = &*NextMIIt;
20355       ++NextMIIt;
20356     }
20357   }
20358
20359   // This checks for case 2, but only do this if we didn't already find
20360   // case 1, as indicated by LastCMOV == MI.
20361   if (LastCMOV == MI &&
20362       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20363       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20364       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20365     CascadedCMOV = &*NextMIIt;
20366   }
20367
20368   MachineBasicBlock *jcc1MBB = nullptr;
20369
20370   // If we have a cascaded CMOV, we lower it to two successive branches to
20371   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20372   if (CascadedCMOV) {
20373     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20374     F->insert(It, jcc1MBB);
20375     jcc1MBB->addLiveIn(X86::EFLAGS);
20376   }
20377
20378   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20379   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20380   F->insert(It, copy0MBB);
20381   F->insert(It, sinkMBB);
20382
20383   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20384   // live into the sink and copy blocks.
20385   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20386
20387   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20388   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20389       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20390     copy0MBB->addLiveIn(X86::EFLAGS);
20391     sinkMBB->addLiveIn(X86::EFLAGS);
20392   }
20393
20394   // Transfer the remainder of BB and its successor edges to sinkMBB.
20395   sinkMBB->splice(sinkMBB->begin(), BB,
20396                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20397   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20398
20399   // Add the true and fallthrough blocks as its successors.
20400   if (CascadedCMOV) {
20401     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20402     BB->addSuccessor(jcc1MBB);
20403
20404     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20405     // jump to the sinkMBB.
20406     jcc1MBB->addSuccessor(copy0MBB);
20407     jcc1MBB->addSuccessor(sinkMBB);
20408   } else {
20409     BB->addSuccessor(copy0MBB);
20410   }
20411
20412   // The true block target of the first (or only) branch is always sinkMBB.
20413   BB->addSuccessor(sinkMBB);
20414
20415   // Create the conditional branch instruction.
20416   unsigned Opc = X86::GetCondBranchFromCond(CC);
20417   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20418
20419   if (CascadedCMOV) {
20420     unsigned Opc2 = X86::GetCondBranchFromCond(
20421         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20422     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20423   }
20424
20425   //  copy0MBB:
20426   //   %FalseValue = ...
20427   //   # fallthrough to sinkMBB
20428   copy0MBB->addSuccessor(sinkMBB);
20429
20430   //  sinkMBB:
20431   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20432   //  ...
20433   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20434   MachineBasicBlock::iterator MIItEnd =
20435     std::next(MachineBasicBlock::iterator(LastCMOV));
20436   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20437   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20438   MachineInstrBuilder MIB;
20439
20440   // As we are creating the PHIs, we have to be careful if there is more than
20441   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
20442   // PHIs have to reference the individual true/false inputs from earlier PHIs.
20443   // That also means that PHI construction must work forward from earlier to
20444   // later, and that the code must maintain a mapping from earlier PHI's
20445   // destination registers, and the registers that went into the PHI.
20446
20447   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20448     unsigned DestReg = MIIt->getOperand(0).getReg();
20449     unsigned Op1Reg = MIIt->getOperand(1).getReg();
20450     unsigned Op2Reg = MIIt->getOperand(2).getReg();
20451
20452     // If this CMOV we are generating is the opposite condition from
20453     // the jump we generated, then we have to swap the operands for the
20454     // PHI that is going to be generated.
20455     if (MIIt->getOperand(3).getImm() == OppCC)
20456         std::swap(Op1Reg, Op2Reg);
20457
20458     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20459       Op1Reg = RegRewriteTable[Op1Reg].first;
20460
20461     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20462       Op2Reg = RegRewriteTable[Op2Reg].second;
20463
20464     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20465                   TII->get(X86::PHI), DestReg)
20466           .addReg(Op1Reg).addMBB(copy0MBB)
20467           .addReg(Op2Reg).addMBB(thisMBB);
20468
20469     // Add this PHI to the rewrite table.
20470     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20471   }
20472
20473   // If we have a cascaded CMOV, the second Jcc provides the same incoming
20474   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20475   if (CascadedCMOV) {
20476     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20477     // Copy the PHI result to the register defined by the second CMOV.
20478     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20479             DL, TII->get(TargetOpcode::COPY),
20480             CascadedCMOV->getOperand(0).getReg())
20481         .addReg(MI->getOperand(0).getReg());
20482     CascadedCMOV->eraseFromParent();
20483   }
20484
20485   // Now remove the CMOV(s).
20486   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20487     (MIIt++)->eraseFromParent();
20488
20489   return sinkMBB;
20490 }
20491
20492 MachineBasicBlock *
20493 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20494                                        MachineBasicBlock *BB) const {
20495   // Combine the following atomic floating-point modification pattern:
20496   //   a.store(reg OP a.load(acquire), release)
20497   // Transform them into:
20498   //   OPss (%gpr), %xmm
20499   //   movss %xmm, (%gpr)
20500   // Or sd equivalent for 64-bit operations.
20501   unsigned MOp, FOp;
20502   switch (MI->getOpcode()) {
20503   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20504   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20505   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20506   }
20507   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20508   DebugLoc DL = MI->getDebugLoc();
20509   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20510   unsigned MSrc = MI->getOperand(0).getReg();
20511   unsigned VSrc = MI->getOperand(5).getReg();
20512   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20513                                 .addReg(/*Base=*/MSrc)
20514                                 .addImm(/*Scale=*/1)
20515                                 .addReg(/*Index=*/0)
20516                                 .addImm(0)
20517                                 .addReg(0);
20518   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20519                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20520                           .addReg(VSrc)
20521                           .addReg(/*Base=*/MSrc)
20522                           .addImm(/*Scale=*/1)
20523                           .addReg(/*Index=*/0)
20524                           .addImm(/*Disp=*/0)
20525                           .addReg(/*Segment=*/0);
20526   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20527   MI->eraseFromParent(); // The pseudo instruction is gone now.
20528   return BB;
20529 }
20530
20531 MachineBasicBlock *
20532 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20533                                         MachineBasicBlock *BB) const {
20534   MachineFunction *MF = BB->getParent();
20535   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20536   DebugLoc DL = MI->getDebugLoc();
20537   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20538
20539   assert(MF->shouldSplitStack());
20540
20541   const bool Is64Bit = Subtarget->is64Bit();
20542   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20543
20544   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20545   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20546
20547   // BB:
20548   //  ... [Till the alloca]
20549   // If stacklet is not large enough, jump to mallocMBB
20550   //
20551   // bumpMBB:
20552   //  Allocate by subtracting from RSP
20553   //  Jump to continueMBB
20554   //
20555   // mallocMBB:
20556   //  Allocate by call to runtime
20557   //
20558   // continueMBB:
20559   //  ...
20560   //  [rest of original BB]
20561   //
20562
20563   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20564   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20565   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20566
20567   MachineRegisterInfo &MRI = MF->getRegInfo();
20568   const TargetRegisterClass *AddrRegClass =
20569       getRegClassFor(getPointerTy(MF->getDataLayout()));
20570
20571   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20572     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20573     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20574     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20575     sizeVReg = MI->getOperand(1).getReg(),
20576     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20577
20578   MachineFunction::iterator MBBIter = BB;
20579   ++MBBIter;
20580
20581   MF->insert(MBBIter, bumpMBB);
20582   MF->insert(MBBIter, mallocMBB);
20583   MF->insert(MBBIter, continueMBB);
20584
20585   continueMBB->splice(continueMBB->begin(), BB,
20586                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20587   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20588
20589   // Add code to the main basic block to check if the stack limit has been hit,
20590   // and if so, jump to mallocMBB otherwise to bumpMBB.
20591   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20592   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20593     .addReg(tmpSPVReg).addReg(sizeVReg);
20594   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20595     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20596     .addReg(SPLimitVReg);
20597   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20598
20599   // bumpMBB simply decreases the stack pointer, since we know the current
20600   // stacklet has enough space.
20601   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20602     .addReg(SPLimitVReg);
20603   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20604     .addReg(SPLimitVReg);
20605   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20606
20607   // Calls into a routine in libgcc to allocate more space from the heap.
20608   const uint32_t *RegMask =
20609       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20610   if (IsLP64) {
20611     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20612       .addReg(sizeVReg);
20613     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20614       .addExternalSymbol("__morestack_allocate_stack_space")
20615       .addRegMask(RegMask)
20616       .addReg(X86::RDI, RegState::Implicit)
20617       .addReg(X86::RAX, RegState::ImplicitDefine);
20618   } else if (Is64Bit) {
20619     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20620       .addReg(sizeVReg);
20621     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20622       .addExternalSymbol("__morestack_allocate_stack_space")
20623       .addRegMask(RegMask)
20624       .addReg(X86::EDI, RegState::Implicit)
20625       .addReg(X86::EAX, RegState::ImplicitDefine);
20626   } else {
20627     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20628       .addImm(12);
20629     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20630     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20631       .addExternalSymbol("__morestack_allocate_stack_space")
20632       .addRegMask(RegMask)
20633       .addReg(X86::EAX, RegState::ImplicitDefine);
20634   }
20635
20636   if (!Is64Bit)
20637     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20638       .addImm(16);
20639
20640   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20641     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20642   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20643
20644   // Set up the CFG correctly.
20645   BB->addSuccessor(bumpMBB);
20646   BB->addSuccessor(mallocMBB);
20647   mallocMBB->addSuccessor(continueMBB);
20648   bumpMBB->addSuccessor(continueMBB);
20649
20650   // Take care of the PHI nodes.
20651   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20652           MI->getOperand(0).getReg())
20653     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20654     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20655
20656   // Delete the original pseudo instruction.
20657   MI->eraseFromParent();
20658
20659   // And we're done.
20660   return continueMBB;
20661 }
20662
20663 MachineBasicBlock *
20664 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20665                                         MachineBasicBlock *BB) const {
20666   DebugLoc DL = MI->getDebugLoc();
20667
20668   assert(!Subtarget->isTargetMachO());
20669
20670   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20671                                                     DL);
20672
20673   MI->eraseFromParent();   // The pseudo instruction is gone now.
20674   return BB;
20675 }
20676
20677 MachineBasicBlock *
20678 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20679                                       MachineBasicBlock *BB) const {
20680   // This is pretty easy.  We're taking the value that we received from
20681   // our load from the relocation, sticking it in either RDI (x86-64)
20682   // or EAX and doing an indirect call.  The return value will then
20683   // be in the normal return register.
20684   MachineFunction *F = BB->getParent();
20685   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20686   DebugLoc DL = MI->getDebugLoc();
20687
20688   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20689   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20690
20691   // Get a register mask for the lowered call.
20692   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20693   // proper register mask.
20694   const uint32_t *RegMask =
20695       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20696   if (Subtarget->is64Bit()) {
20697     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20698                                       TII->get(X86::MOV64rm), X86::RDI)
20699     .addReg(X86::RIP)
20700     .addImm(0).addReg(0)
20701     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20702                       MI->getOperand(3).getTargetFlags())
20703     .addReg(0);
20704     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20705     addDirectMem(MIB, X86::RDI);
20706     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20707   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20708     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20709                                       TII->get(X86::MOV32rm), X86::EAX)
20710     .addReg(0)
20711     .addImm(0).addReg(0)
20712     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20713                       MI->getOperand(3).getTargetFlags())
20714     .addReg(0);
20715     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20716     addDirectMem(MIB, X86::EAX);
20717     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20718   } else {
20719     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20720                                       TII->get(X86::MOV32rm), X86::EAX)
20721     .addReg(TII->getGlobalBaseReg(F))
20722     .addImm(0).addReg(0)
20723     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20724                       MI->getOperand(3).getTargetFlags())
20725     .addReg(0);
20726     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20727     addDirectMem(MIB, X86::EAX);
20728     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20729   }
20730
20731   MI->eraseFromParent(); // The pseudo instruction is gone now.
20732   return BB;
20733 }
20734
20735 MachineBasicBlock *
20736 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20737                                     MachineBasicBlock *MBB) const {
20738   DebugLoc DL = MI->getDebugLoc();
20739   MachineFunction *MF = MBB->getParent();
20740   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20741   MachineRegisterInfo &MRI = MF->getRegInfo();
20742
20743   const BasicBlock *BB = MBB->getBasicBlock();
20744   MachineFunction::iterator I = MBB;
20745   ++I;
20746
20747   // Memory Reference
20748   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20749   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20750
20751   unsigned DstReg;
20752   unsigned MemOpndSlot = 0;
20753
20754   unsigned CurOp = 0;
20755
20756   DstReg = MI->getOperand(CurOp++).getReg();
20757   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20758   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20759   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20760   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20761
20762   MemOpndSlot = CurOp;
20763
20764   MVT PVT = getPointerTy(MF->getDataLayout());
20765   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20766          "Invalid Pointer Size!");
20767
20768   // For v = setjmp(buf), we generate
20769   //
20770   // thisMBB:
20771   //  buf[LabelOffset] = restoreMBB
20772   //  SjLjSetup restoreMBB
20773   //
20774   // mainMBB:
20775   //  v_main = 0
20776   //
20777   // sinkMBB:
20778   //  v = phi(main, restore)
20779   //
20780   // restoreMBB:
20781   //  if base pointer being used, load it from frame
20782   //  v_restore = 1
20783
20784   MachineBasicBlock *thisMBB = MBB;
20785   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20786   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20787   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20788   MF->insert(I, mainMBB);
20789   MF->insert(I, sinkMBB);
20790   MF->push_back(restoreMBB);
20791
20792   MachineInstrBuilder MIB;
20793
20794   // Transfer the remainder of BB and its successor edges to sinkMBB.
20795   sinkMBB->splice(sinkMBB->begin(), MBB,
20796                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20797   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20798
20799   // thisMBB:
20800   unsigned PtrStoreOpc = 0;
20801   unsigned LabelReg = 0;
20802   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20803   Reloc::Model RM = MF->getTarget().getRelocationModel();
20804   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20805                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20806
20807   // Prepare IP either in reg or imm.
20808   if (!UseImmLabel) {
20809     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20810     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20811     LabelReg = MRI.createVirtualRegister(PtrRC);
20812     if (Subtarget->is64Bit()) {
20813       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20814               .addReg(X86::RIP)
20815               .addImm(0)
20816               .addReg(0)
20817               .addMBB(restoreMBB)
20818               .addReg(0);
20819     } else {
20820       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20821       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20822               .addReg(XII->getGlobalBaseReg(MF))
20823               .addImm(0)
20824               .addReg(0)
20825               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20826               .addReg(0);
20827     }
20828   } else
20829     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20830   // Store IP
20831   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20832   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20833     if (i == X86::AddrDisp)
20834       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20835     else
20836       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20837   }
20838   if (!UseImmLabel)
20839     MIB.addReg(LabelReg);
20840   else
20841     MIB.addMBB(restoreMBB);
20842   MIB.setMemRefs(MMOBegin, MMOEnd);
20843   // Setup
20844   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20845           .addMBB(restoreMBB);
20846
20847   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20848   MIB.addRegMask(RegInfo->getNoPreservedMask());
20849   thisMBB->addSuccessor(mainMBB);
20850   thisMBB->addSuccessor(restoreMBB);
20851
20852   // mainMBB:
20853   //  EAX = 0
20854   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20855   mainMBB->addSuccessor(sinkMBB);
20856
20857   // sinkMBB:
20858   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20859           TII->get(X86::PHI), DstReg)
20860     .addReg(mainDstReg).addMBB(mainMBB)
20861     .addReg(restoreDstReg).addMBB(restoreMBB);
20862
20863   // restoreMBB:
20864   if (RegInfo->hasBasePointer(*MF)) {
20865     const bool Uses64BitFramePtr =
20866         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20867     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20868     X86FI->setRestoreBasePointer(MF);
20869     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20870     unsigned BasePtr = RegInfo->getBaseRegister();
20871     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20872     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20873                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20874       .setMIFlag(MachineInstr::FrameSetup);
20875   }
20876   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20877   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20878   restoreMBB->addSuccessor(sinkMBB);
20879
20880   MI->eraseFromParent();
20881   return sinkMBB;
20882 }
20883
20884 MachineBasicBlock *
20885 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20886                                      MachineBasicBlock *MBB) const {
20887   DebugLoc DL = MI->getDebugLoc();
20888   MachineFunction *MF = MBB->getParent();
20889   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20890   MachineRegisterInfo &MRI = MF->getRegInfo();
20891
20892   // Memory Reference
20893   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20894   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20895
20896   MVT PVT = getPointerTy(MF->getDataLayout());
20897   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20898          "Invalid Pointer Size!");
20899
20900   const TargetRegisterClass *RC =
20901     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20902   unsigned Tmp = MRI.createVirtualRegister(RC);
20903   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20904   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20905   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20906   unsigned SP = RegInfo->getStackRegister();
20907
20908   MachineInstrBuilder MIB;
20909
20910   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20911   const int64_t SPOffset = 2 * PVT.getStoreSize();
20912
20913   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20914   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20915
20916   // Reload FP
20917   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20918   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20919     MIB.addOperand(MI->getOperand(i));
20920   MIB.setMemRefs(MMOBegin, MMOEnd);
20921   // Reload IP
20922   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20923   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20924     if (i == X86::AddrDisp)
20925       MIB.addDisp(MI->getOperand(i), LabelOffset);
20926     else
20927       MIB.addOperand(MI->getOperand(i));
20928   }
20929   MIB.setMemRefs(MMOBegin, MMOEnd);
20930   // Reload SP
20931   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20932   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20933     if (i == X86::AddrDisp)
20934       MIB.addDisp(MI->getOperand(i), SPOffset);
20935     else
20936       MIB.addOperand(MI->getOperand(i));
20937   }
20938   MIB.setMemRefs(MMOBegin, MMOEnd);
20939   // Jump
20940   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20941
20942   MI->eraseFromParent();
20943   return MBB;
20944 }
20945
20946 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20947 // accumulator loops. Writing back to the accumulator allows the coalescer
20948 // to remove extra copies in the loop.
20949 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20950 MachineBasicBlock *
20951 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20952                                  MachineBasicBlock *MBB) const {
20953   MachineOperand &AddendOp = MI->getOperand(3);
20954
20955   // Bail out early if the addend isn't a register - we can't switch these.
20956   if (!AddendOp.isReg())
20957     return MBB;
20958
20959   MachineFunction &MF = *MBB->getParent();
20960   MachineRegisterInfo &MRI = MF.getRegInfo();
20961
20962   // Check whether the addend is defined by a PHI:
20963   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20964   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20965   if (!AddendDef.isPHI())
20966     return MBB;
20967
20968   // Look for the following pattern:
20969   // loop:
20970   //   %addend = phi [%entry, 0], [%loop, %result]
20971   //   ...
20972   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20973
20974   // Replace with:
20975   //   loop:
20976   //   %addend = phi [%entry, 0], [%loop, %result]
20977   //   ...
20978   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20979
20980   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20981     assert(AddendDef.getOperand(i).isReg());
20982     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20983     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20984     if (&PHISrcInst == MI) {
20985       // Found a matching instruction.
20986       unsigned NewFMAOpc = 0;
20987       switch (MI->getOpcode()) {
20988         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20989         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20990         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20991         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20992         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20993         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20994         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20995         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20996         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20997         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20998         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20999         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21000         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21001         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21002         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21003         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21004         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21005         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21006         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21007         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21008
21009         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21010         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21011         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21012         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21013         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21014         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21015         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21016         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21017         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21018         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21019         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21020         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21021         default: llvm_unreachable("Unrecognized FMA variant.");
21022       }
21023
21024       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21025       MachineInstrBuilder MIB =
21026         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21027         .addOperand(MI->getOperand(0))
21028         .addOperand(MI->getOperand(3))
21029         .addOperand(MI->getOperand(2))
21030         .addOperand(MI->getOperand(1));
21031       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21032       MI->eraseFromParent();
21033     }
21034   }
21035
21036   return MBB;
21037 }
21038
21039 MachineBasicBlock *
21040 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21041                                                MachineBasicBlock *BB) const {
21042   switch (MI->getOpcode()) {
21043   default: llvm_unreachable("Unexpected instr type to insert");
21044   case X86::TAILJMPd64:
21045   case X86::TAILJMPr64:
21046   case X86::TAILJMPm64:
21047   case X86::TAILJMPd64_REX:
21048   case X86::TAILJMPr64_REX:
21049   case X86::TAILJMPm64_REX:
21050     llvm_unreachable("TAILJMP64 would not be touched here.");
21051   case X86::TCRETURNdi64:
21052   case X86::TCRETURNri64:
21053   case X86::TCRETURNmi64:
21054     return BB;
21055   case X86::WIN_ALLOCA:
21056     return EmitLoweredWinAlloca(MI, BB);
21057   case X86::SEG_ALLOCA_32:
21058   case X86::SEG_ALLOCA_64:
21059     return EmitLoweredSegAlloca(MI, BB);
21060   case X86::TLSCall_32:
21061   case X86::TLSCall_64:
21062     return EmitLoweredTLSCall(MI, BB);
21063   case X86::CMOV_FR32:
21064   case X86::CMOV_FR64:
21065   case X86::CMOV_GR8:
21066   case X86::CMOV_GR16:
21067   case X86::CMOV_GR32:
21068   case X86::CMOV_RFP32:
21069   case X86::CMOV_RFP64:
21070   case X86::CMOV_RFP80:
21071   case X86::CMOV_V2F64:
21072   case X86::CMOV_V2I64:
21073   case X86::CMOV_V4F32:
21074   case X86::CMOV_V4F64:
21075   case X86::CMOV_V4I64:
21076   case X86::CMOV_V16F32:
21077   case X86::CMOV_V8F32:
21078   case X86::CMOV_V8F64:
21079   case X86::CMOV_V8I64:
21080   case X86::CMOV_V8I1:
21081   case X86::CMOV_V16I1:
21082   case X86::CMOV_V32I1:
21083   case X86::CMOV_V64I1:
21084     return EmitLoweredSelect(MI, BB);
21085
21086   case X86::RELEASE_FADD32mr:
21087   case X86::RELEASE_FADD64mr:
21088     return EmitLoweredAtomicFP(MI, BB);
21089
21090   case X86::FP32_TO_INT16_IN_MEM:
21091   case X86::FP32_TO_INT32_IN_MEM:
21092   case X86::FP32_TO_INT64_IN_MEM:
21093   case X86::FP64_TO_INT16_IN_MEM:
21094   case X86::FP64_TO_INT32_IN_MEM:
21095   case X86::FP64_TO_INT64_IN_MEM:
21096   case X86::FP80_TO_INT16_IN_MEM:
21097   case X86::FP80_TO_INT32_IN_MEM:
21098   case X86::FP80_TO_INT64_IN_MEM: {
21099     MachineFunction *F = BB->getParent();
21100     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21101     DebugLoc DL = MI->getDebugLoc();
21102
21103     // Change the floating point control register to use "round towards zero"
21104     // mode when truncating to an integer value.
21105     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21106     addFrameReference(BuildMI(*BB, MI, DL,
21107                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21108
21109     // Load the old value of the high byte of the control word...
21110     unsigned OldCW =
21111       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21112     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21113                       CWFrameIdx);
21114
21115     // Set the high part to be round to zero...
21116     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21117       .addImm(0xC7F);
21118
21119     // Reload the modified control word now...
21120     addFrameReference(BuildMI(*BB, MI, DL,
21121                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21122
21123     // Restore the memory image of control word to original value
21124     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21125       .addReg(OldCW);
21126
21127     // Get the X86 opcode to use.
21128     unsigned Opc;
21129     switch (MI->getOpcode()) {
21130     default: llvm_unreachable("illegal opcode!");
21131     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21132     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21133     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21134     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21135     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21136     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21137     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21138     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21139     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21140     }
21141
21142     X86AddressMode AM;
21143     MachineOperand &Op = MI->getOperand(0);
21144     if (Op.isReg()) {
21145       AM.BaseType = X86AddressMode::RegBase;
21146       AM.Base.Reg = Op.getReg();
21147     } else {
21148       AM.BaseType = X86AddressMode::FrameIndexBase;
21149       AM.Base.FrameIndex = Op.getIndex();
21150     }
21151     Op = MI->getOperand(1);
21152     if (Op.isImm())
21153       AM.Scale = Op.getImm();
21154     Op = MI->getOperand(2);
21155     if (Op.isImm())
21156       AM.IndexReg = Op.getImm();
21157     Op = MI->getOperand(3);
21158     if (Op.isGlobal()) {
21159       AM.GV = Op.getGlobal();
21160     } else {
21161       AM.Disp = Op.getImm();
21162     }
21163     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21164                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21165
21166     // Reload the original control word now.
21167     addFrameReference(BuildMI(*BB, MI, DL,
21168                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21169
21170     MI->eraseFromParent();   // The pseudo instruction is gone now.
21171     return BB;
21172   }
21173     // String/text processing lowering.
21174   case X86::PCMPISTRM128REG:
21175   case X86::VPCMPISTRM128REG:
21176   case X86::PCMPISTRM128MEM:
21177   case X86::VPCMPISTRM128MEM:
21178   case X86::PCMPESTRM128REG:
21179   case X86::VPCMPESTRM128REG:
21180   case X86::PCMPESTRM128MEM:
21181   case X86::VPCMPESTRM128MEM:
21182     assert(Subtarget->hasSSE42() &&
21183            "Target must have SSE4.2 or AVX features enabled");
21184     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21185
21186   // String/text processing lowering.
21187   case X86::PCMPISTRIREG:
21188   case X86::VPCMPISTRIREG:
21189   case X86::PCMPISTRIMEM:
21190   case X86::VPCMPISTRIMEM:
21191   case X86::PCMPESTRIREG:
21192   case X86::VPCMPESTRIREG:
21193   case X86::PCMPESTRIMEM:
21194   case X86::VPCMPESTRIMEM:
21195     assert(Subtarget->hasSSE42() &&
21196            "Target must have SSE4.2 or AVX features enabled");
21197     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21198
21199   // Thread synchronization.
21200   case X86::MONITOR:
21201     return EmitMonitor(MI, BB, Subtarget);
21202
21203   // xbegin
21204   case X86::XBEGIN:
21205     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21206
21207   case X86::VASTART_SAVE_XMM_REGS:
21208     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21209
21210   case X86::VAARG_64:
21211     return EmitVAARG64WithCustomInserter(MI, BB);
21212
21213   case X86::EH_SjLj_SetJmp32:
21214   case X86::EH_SjLj_SetJmp64:
21215     return emitEHSjLjSetJmp(MI, BB);
21216
21217   case X86::EH_SjLj_LongJmp32:
21218   case X86::EH_SjLj_LongJmp64:
21219     return emitEHSjLjLongJmp(MI, BB);
21220
21221   case TargetOpcode::STATEPOINT:
21222     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21223     // this point in the process.  We diverge later.
21224     return emitPatchPoint(MI, BB);
21225
21226   case TargetOpcode::STACKMAP:
21227   case TargetOpcode::PATCHPOINT:
21228     return emitPatchPoint(MI, BB);
21229
21230   case X86::VFMADDPDr213r:
21231   case X86::VFMADDPSr213r:
21232   case X86::VFMADDSDr213r:
21233   case X86::VFMADDSSr213r:
21234   case X86::VFMSUBPDr213r:
21235   case X86::VFMSUBPSr213r:
21236   case X86::VFMSUBSDr213r:
21237   case X86::VFMSUBSSr213r:
21238   case X86::VFNMADDPDr213r:
21239   case X86::VFNMADDPSr213r:
21240   case X86::VFNMADDSDr213r:
21241   case X86::VFNMADDSSr213r:
21242   case X86::VFNMSUBPDr213r:
21243   case X86::VFNMSUBPSr213r:
21244   case X86::VFNMSUBSDr213r:
21245   case X86::VFNMSUBSSr213r:
21246   case X86::VFMADDSUBPDr213r:
21247   case X86::VFMADDSUBPSr213r:
21248   case X86::VFMSUBADDPDr213r:
21249   case X86::VFMSUBADDPSr213r:
21250   case X86::VFMADDPDr213rY:
21251   case X86::VFMADDPSr213rY:
21252   case X86::VFMSUBPDr213rY:
21253   case X86::VFMSUBPSr213rY:
21254   case X86::VFNMADDPDr213rY:
21255   case X86::VFNMADDPSr213rY:
21256   case X86::VFNMSUBPDr213rY:
21257   case X86::VFNMSUBPSr213rY:
21258   case X86::VFMADDSUBPDr213rY:
21259   case X86::VFMADDSUBPSr213rY:
21260   case X86::VFMSUBADDPDr213rY:
21261   case X86::VFMSUBADDPSr213rY:
21262     return emitFMA3Instr(MI, BB);
21263   }
21264 }
21265
21266 //===----------------------------------------------------------------------===//
21267 //                           X86 Optimization Hooks
21268 //===----------------------------------------------------------------------===//
21269
21270 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21271                                                       APInt &KnownZero,
21272                                                       APInt &KnownOne,
21273                                                       const SelectionDAG &DAG,
21274                                                       unsigned Depth) const {
21275   unsigned BitWidth = KnownZero.getBitWidth();
21276   unsigned Opc = Op.getOpcode();
21277   assert((Opc >= ISD::BUILTIN_OP_END ||
21278           Opc == ISD::INTRINSIC_WO_CHAIN ||
21279           Opc == ISD::INTRINSIC_W_CHAIN ||
21280           Opc == ISD::INTRINSIC_VOID) &&
21281          "Should use MaskedValueIsZero if you don't know whether Op"
21282          " is a target node!");
21283
21284   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21285   switch (Opc) {
21286   default: break;
21287   case X86ISD::ADD:
21288   case X86ISD::SUB:
21289   case X86ISD::ADC:
21290   case X86ISD::SBB:
21291   case X86ISD::SMUL:
21292   case X86ISD::UMUL:
21293   case X86ISD::INC:
21294   case X86ISD::DEC:
21295   case X86ISD::OR:
21296   case X86ISD::XOR:
21297   case X86ISD::AND:
21298     // These nodes' second result is a boolean.
21299     if (Op.getResNo() == 0)
21300       break;
21301     // Fallthrough
21302   case X86ISD::SETCC:
21303     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21304     break;
21305   case ISD::INTRINSIC_WO_CHAIN: {
21306     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21307     unsigned NumLoBits = 0;
21308     switch (IntId) {
21309     default: break;
21310     case Intrinsic::x86_sse_movmsk_ps:
21311     case Intrinsic::x86_avx_movmsk_ps_256:
21312     case Intrinsic::x86_sse2_movmsk_pd:
21313     case Intrinsic::x86_avx_movmsk_pd_256:
21314     case Intrinsic::x86_mmx_pmovmskb:
21315     case Intrinsic::x86_sse2_pmovmskb_128:
21316     case Intrinsic::x86_avx2_pmovmskb: {
21317       // High bits of movmskp{s|d}, pmovmskb are known zero.
21318       switch (IntId) {
21319         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21320         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21321         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21322         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21323         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21324         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21325         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21326         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21327       }
21328       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21329       break;
21330     }
21331     }
21332     break;
21333   }
21334   }
21335 }
21336
21337 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21338   SDValue Op,
21339   const SelectionDAG &,
21340   unsigned Depth) const {
21341   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21342   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21343     return Op.getValueType().getScalarType().getSizeInBits();
21344
21345   // Fallback case.
21346   return 1;
21347 }
21348
21349 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21350 /// node is a GlobalAddress + offset.
21351 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21352                                        const GlobalValue* &GA,
21353                                        int64_t &Offset) const {
21354   if (N->getOpcode() == X86ISD::Wrapper) {
21355     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21356       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21357       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21358       return true;
21359     }
21360   }
21361   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21362 }
21363
21364 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21365 /// same as extracting the high 128-bit part of 256-bit vector and then
21366 /// inserting the result into the low part of a new 256-bit vector
21367 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21368   EVT VT = SVOp->getValueType(0);
21369   unsigned NumElems = VT.getVectorNumElements();
21370
21371   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21372   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21373     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21374         SVOp->getMaskElt(j) >= 0)
21375       return false;
21376
21377   return true;
21378 }
21379
21380 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21381 /// same as extracting the low 128-bit part of 256-bit vector and then
21382 /// inserting the result into the high part of a new 256-bit vector
21383 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21384   EVT VT = SVOp->getValueType(0);
21385   unsigned NumElems = VT.getVectorNumElements();
21386
21387   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21388   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21389     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21390         SVOp->getMaskElt(j) >= 0)
21391       return false;
21392
21393   return true;
21394 }
21395
21396 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21397 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21398                                         TargetLowering::DAGCombinerInfo &DCI,
21399                                         const X86Subtarget* Subtarget) {
21400   SDLoc dl(N);
21401   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21402   SDValue V1 = SVOp->getOperand(0);
21403   SDValue V2 = SVOp->getOperand(1);
21404   EVT VT = SVOp->getValueType(0);
21405   unsigned NumElems = VT.getVectorNumElements();
21406
21407   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21408       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21409     //
21410     //                   0,0,0,...
21411     //                      |
21412     //    V      UNDEF    BUILD_VECTOR    UNDEF
21413     //     \      /           \           /
21414     //  CONCAT_VECTOR         CONCAT_VECTOR
21415     //         \                  /
21416     //          \                /
21417     //          RESULT: V + zero extended
21418     //
21419     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21420         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21421         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21422       return SDValue();
21423
21424     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21425       return SDValue();
21426
21427     // To match the shuffle mask, the first half of the mask should
21428     // be exactly the first vector, and all the rest a splat with the
21429     // first element of the second one.
21430     for (unsigned i = 0; i != NumElems/2; ++i)
21431       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21432           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21433         return SDValue();
21434
21435     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21436     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21437       if (Ld->hasNUsesOfValue(1, 0)) {
21438         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21439         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21440         SDValue ResNode =
21441           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21442                                   Ld->getMemoryVT(),
21443                                   Ld->getPointerInfo(),
21444                                   Ld->getAlignment(),
21445                                   false/*isVolatile*/, true/*ReadMem*/,
21446                                   false/*WriteMem*/);
21447
21448         // Make sure the newly-created LOAD is in the same position as Ld in
21449         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21450         // and update uses of Ld's output chain to use the TokenFactor.
21451         if (Ld->hasAnyUseOfValue(1)) {
21452           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21453                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21454           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21455           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21456                                  SDValue(ResNode.getNode(), 1));
21457         }
21458
21459         return DAG.getBitcast(VT, ResNode);
21460       }
21461     }
21462
21463     // Emit a zeroed vector and insert the desired subvector on its
21464     // first half.
21465     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21466     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21467     return DCI.CombineTo(N, InsV);
21468   }
21469
21470   //===--------------------------------------------------------------------===//
21471   // Combine some shuffles into subvector extracts and inserts:
21472   //
21473
21474   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21475   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21476     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21477     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21478     return DCI.CombineTo(N, InsV);
21479   }
21480
21481   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21482   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21483     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21484     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21485     return DCI.CombineTo(N, InsV);
21486   }
21487
21488   return SDValue();
21489 }
21490
21491 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21492 /// possible.
21493 ///
21494 /// This is the leaf of the recursive combinine below. When we have found some
21495 /// chain of single-use x86 shuffle instructions and accumulated the combined
21496 /// shuffle mask represented by them, this will try to pattern match that mask
21497 /// into either a single instruction if there is a special purpose instruction
21498 /// for this operation, or into a PSHUFB instruction which is a fully general
21499 /// instruction but should only be used to replace chains over a certain depth.
21500 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21501                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21502                                    TargetLowering::DAGCombinerInfo &DCI,
21503                                    const X86Subtarget *Subtarget) {
21504   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21505
21506   // Find the operand that enters the chain. Note that multiple uses are OK
21507   // here, we're not going to remove the operand we find.
21508   SDValue Input = Op.getOperand(0);
21509   while (Input.getOpcode() == ISD::BITCAST)
21510     Input = Input.getOperand(0);
21511
21512   MVT VT = Input.getSimpleValueType();
21513   MVT RootVT = Root.getSimpleValueType();
21514   SDLoc DL(Root);
21515
21516   // Just remove no-op shuffle masks.
21517   if (Mask.size() == 1) {
21518     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21519                   /*AddTo*/ true);
21520     return true;
21521   }
21522
21523   // Use the float domain if the operand type is a floating point type.
21524   bool FloatDomain = VT.isFloatingPoint();
21525
21526   // For floating point shuffles, we don't have free copies in the shuffle
21527   // instructions or the ability to load as part of the instruction, so
21528   // canonicalize their shuffles to UNPCK or MOV variants.
21529   //
21530   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21531   // vectors because it can have a load folded into it that UNPCK cannot. This
21532   // doesn't preclude something switching to the shorter encoding post-RA.
21533   //
21534   // FIXME: Should teach these routines about AVX vector widths.
21535   if (FloatDomain && VT.getSizeInBits() == 128) {
21536     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21537       bool Lo = Mask.equals({0, 0});
21538       unsigned Shuffle;
21539       MVT ShuffleVT;
21540       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21541       // is no slower than UNPCKLPD but has the option to fold the input operand
21542       // into even an unaligned memory load.
21543       if (Lo && Subtarget->hasSSE3()) {
21544         Shuffle = X86ISD::MOVDDUP;
21545         ShuffleVT = MVT::v2f64;
21546       } else {
21547         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21548         // than the UNPCK variants.
21549         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21550         ShuffleVT = MVT::v4f32;
21551       }
21552       if (Depth == 1 && Root->getOpcode() == Shuffle)
21553         return false; // Nothing to do!
21554       Op = DAG.getBitcast(ShuffleVT, Input);
21555       DCI.AddToWorklist(Op.getNode());
21556       if (Shuffle == X86ISD::MOVDDUP)
21557         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21558       else
21559         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21560       DCI.AddToWorklist(Op.getNode());
21561       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21562                     /*AddTo*/ true);
21563       return true;
21564     }
21565     if (Subtarget->hasSSE3() &&
21566         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21567       bool Lo = Mask.equals({0, 0, 2, 2});
21568       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21569       MVT ShuffleVT = MVT::v4f32;
21570       if (Depth == 1 && Root->getOpcode() == Shuffle)
21571         return false; // Nothing to do!
21572       Op = DAG.getBitcast(ShuffleVT, Input);
21573       DCI.AddToWorklist(Op.getNode());
21574       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21575       DCI.AddToWorklist(Op.getNode());
21576       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21577                     /*AddTo*/ true);
21578       return true;
21579     }
21580     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21581       bool Lo = Mask.equals({0, 0, 1, 1});
21582       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21583       MVT ShuffleVT = MVT::v4f32;
21584       if (Depth == 1 && Root->getOpcode() == Shuffle)
21585         return false; // Nothing to do!
21586       Op = DAG.getBitcast(ShuffleVT, Input);
21587       DCI.AddToWorklist(Op.getNode());
21588       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21589       DCI.AddToWorklist(Op.getNode());
21590       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21591                     /*AddTo*/ true);
21592       return true;
21593     }
21594   }
21595
21596   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21597   // variants as none of these have single-instruction variants that are
21598   // superior to the UNPCK formulation.
21599   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21600       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21601        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21602        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21603        Mask.equals(
21604            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21605     bool Lo = Mask[0] == 0;
21606     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21607     if (Depth == 1 && Root->getOpcode() == Shuffle)
21608       return false; // Nothing to do!
21609     MVT ShuffleVT;
21610     switch (Mask.size()) {
21611     case 8:
21612       ShuffleVT = MVT::v8i16;
21613       break;
21614     case 16:
21615       ShuffleVT = MVT::v16i8;
21616       break;
21617     default:
21618       llvm_unreachable("Impossible mask size!");
21619     };
21620     Op = DAG.getBitcast(ShuffleVT, Input);
21621     DCI.AddToWorklist(Op.getNode());
21622     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21623     DCI.AddToWorklist(Op.getNode());
21624     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21625                   /*AddTo*/ true);
21626     return true;
21627   }
21628
21629   // Don't try to re-form single instruction chains under any circumstances now
21630   // that we've done encoding canonicalization for them.
21631   if (Depth < 2)
21632     return false;
21633
21634   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21635   // can replace them with a single PSHUFB instruction profitably. Intel's
21636   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21637   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21638   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21639     SmallVector<SDValue, 16> PSHUFBMask;
21640     int NumBytes = VT.getSizeInBits() / 8;
21641     int Ratio = NumBytes / Mask.size();
21642     for (int i = 0; i < NumBytes; ++i) {
21643       if (Mask[i / Ratio] == SM_SentinelUndef) {
21644         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21645         continue;
21646       }
21647       int M = Mask[i / Ratio] != SM_SentinelZero
21648                   ? Ratio * Mask[i / Ratio] + i % Ratio
21649                   : 255;
21650       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21651     }
21652     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21653     Op = DAG.getBitcast(ByteVT, Input);
21654     DCI.AddToWorklist(Op.getNode());
21655     SDValue PSHUFBMaskOp =
21656         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21657     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21658     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21659     DCI.AddToWorklist(Op.getNode());
21660     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21661                   /*AddTo*/ true);
21662     return true;
21663   }
21664
21665   // Failed to find any combines.
21666   return false;
21667 }
21668
21669 /// \brief Fully generic combining of x86 shuffle instructions.
21670 ///
21671 /// This should be the last combine run over the x86 shuffle instructions. Once
21672 /// they have been fully optimized, this will recursively consider all chains
21673 /// of single-use shuffle instructions, build a generic model of the cumulative
21674 /// shuffle operation, and check for simpler instructions which implement this
21675 /// operation. We use this primarily for two purposes:
21676 ///
21677 /// 1) Collapse generic shuffles to specialized single instructions when
21678 ///    equivalent. In most cases, this is just an encoding size win, but
21679 ///    sometimes we will collapse multiple generic shuffles into a single
21680 ///    special-purpose shuffle.
21681 /// 2) Look for sequences of shuffle instructions with 3 or more total
21682 ///    instructions, and replace them with the slightly more expensive SSSE3
21683 ///    PSHUFB instruction if available. We do this as the last combining step
21684 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21685 ///    a suitable short sequence of other instructions. The PHUFB will either
21686 ///    use a register or have to read from memory and so is slightly (but only
21687 ///    slightly) more expensive than the other shuffle instructions.
21688 ///
21689 /// Because this is inherently a quadratic operation (for each shuffle in
21690 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21691 /// This should never be an issue in practice as the shuffle lowering doesn't
21692 /// produce sequences of more than 8 instructions.
21693 ///
21694 /// FIXME: We will currently miss some cases where the redundant shuffling
21695 /// would simplify under the threshold for PSHUFB formation because of
21696 /// combine-ordering. To fix this, we should do the redundant instruction
21697 /// combining in this recursive walk.
21698 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21699                                           ArrayRef<int> RootMask,
21700                                           int Depth, bool HasPSHUFB,
21701                                           SelectionDAG &DAG,
21702                                           TargetLowering::DAGCombinerInfo &DCI,
21703                                           const X86Subtarget *Subtarget) {
21704   // Bound the depth of our recursive combine because this is ultimately
21705   // quadratic in nature.
21706   if (Depth > 8)
21707     return false;
21708
21709   // Directly rip through bitcasts to find the underlying operand.
21710   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21711     Op = Op.getOperand(0);
21712
21713   MVT VT = Op.getSimpleValueType();
21714   if (!VT.isVector())
21715     return false; // Bail if we hit a non-vector.
21716
21717   assert(Root.getSimpleValueType().isVector() &&
21718          "Shuffles operate on vector types!");
21719   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21720          "Can only combine shuffles of the same vector register size.");
21721
21722   if (!isTargetShuffle(Op.getOpcode()))
21723     return false;
21724   SmallVector<int, 16> OpMask;
21725   bool IsUnary;
21726   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21727   // We only can combine unary shuffles which we can decode the mask for.
21728   if (!HaveMask || !IsUnary)
21729     return false;
21730
21731   assert(VT.getVectorNumElements() == OpMask.size() &&
21732          "Different mask size from vector size!");
21733   assert(((RootMask.size() > OpMask.size() &&
21734            RootMask.size() % OpMask.size() == 0) ||
21735           (OpMask.size() > RootMask.size() &&
21736            OpMask.size() % RootMask.size() == 0) ||
21737           OpMask.size() == RootMask.size()) &&
21738          "The smaller number of elements must divide the larger.");
21739   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21740   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21741   assert(((RootRatio == 1 && OpRatio == 1) ||
21742           (RootRatio == 1) != (OpRatio == 1)) &&
21743          "Must not have a ratio for both incoming and op masks!");
21744
21745   SmallVector<int, 16> Mask;
21746   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21747
21748   // Merge this shuffle operation's mask into our accumulated mask. Note that
21749   // this shuffle's mask will be the first applied to the input, followed by the
21750   // root mask to get us all the way to the root value arrangement. The reason
21751   // for this order is that we are recursing up the operation chain.
21752   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21753     int RootIdx = i / RootRatio;
21754     if (RootMask[RootIdx] < 0) {
21755       // This is a zero or undef lane, we're done.
21756       Mask.push_back(RootMask[RootIdx]);
21757       continue;
21758     }
21759
21760     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21761     int OpIdx = RootMaskedIdx / OpRatio;
21762     if (OpMask[OpIdx] < 0) {
21763       // The incoming lanes are zero or undef, it doesn't matter which ones we
21764       // are using.
21765       Mask.push_back(OpMask[OpIdx]);
21766       continue;
21767     }
21768
21769     // Ok, we have non-zero lanes, map them through.
21770     Mask.push_back(OpMask[OpIdx] * OpRatio +
21771                    RootMaskedIdx % OpRatio);
21772   }
21773
21774   // See if we can recurse into the operand to combine more things.
21775   switch (Op.getOpcode()) {
21776     case X86ISD::PSHUFB:
21777       HasPSHUFB = true;
21778     case X86ISD::PSHUFD:
21779     case X86ISD::PSHUFHW:
21780     case X86ISD::PSHUFLW:
21781       if (Op.getOperand(0).hasOneUse() &&
21782           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21783                                         HasPSHUFB, DAG, DCI, Subtarget))
21784         return true;
21785       break;
21786
21787     case X86ISD::UNPCKL:
21788     case X86ISD::UNPCKH:
21789       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21790       // We can't check for single use, we have to check that this shuffle is the only user.
21791       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21792           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21793                                         HasPSHUFB, DAG, DCI, Subtarget))
21794           return true;
21795       break;
21796   }
21797
21798   // Minor canonicalization of the accumulated shuffle mask to make it easier
21799   // to match below. All this does is detect masks with squential pairs of
21800   // elements, and shrink them to the half-width mask. It does this in a loop
21801   // so it will reduce the size of the mask to the minimal width mask which
21802   // performs an equivalent shuffle.
21803   SmallVector<int, 16> WidenedMask;
21804   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21805     Mask = std::move(WidenedMask);
21806     WidenedMask.clear();
21807   }
21808
21809   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21810                                 Subtarget);
21811 }
21812
21813 /// \brief Get the PSHUF-style mask from PSHUF node.
21814 ///
21815 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21816 /// PSHUF-style masks that can be reused with such instructions.
21817 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21818   MVT VT = N.getSimpleValueType();
21819   SmallVector<int, 4> Mask;
21820   bool IsUnary;
21821   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21822   (void)HaveMask;
21823   assert(HaveMask);
21824
21825   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21826   // matter. Check that the upper masks are repeats and remove them.
21827   if (VT.getSizeInBits() > 128) {
21828     int LaneElts = 128 / VT.getScalarSizeInBits();
21829 #ifndef NDEBUG
21830     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21831       for (int j = 0; j < LaneElts; ++j)
21832         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21833                "Mask doesn't repeat in high 128-bit lanes!");
21834 #endif
21835     Mask.resize(LaneElts);
21836   }
21837
21838   switch (N.getOpcode()) {
21839   case X86ISD::PSHUFD:
21840     return Mask;
21841   case X86ISD::PSHUFLW:
21842     Mask.resize(4);
21843     return Mask;
21844   case X86ISD::PSHUFHW:
21845     Mask.erase(Mask.begin(), Mask.begin() + 4);
21846     for (int &M : Mask)
21847       M -= 4;
21848     return Mask;
21849   default:
21850     llvm_unreachable("No valid shuffle instruction found!");
21851   }
21852 }
21853
21854 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21855 ///
21856 /// We walk up the chain and look for a combinable shuffle, skipping over
21857 /// shuffles that we could hoist this shuffle's transformation past without
21858 /// altering anything.
21859 static SDValue
21860 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21861                              SelectionDAG &DAG,
21862                              TargetLowering::DAGCombinerInfo &DCI) {
21863   assert(N.getOpcode() == X86ISD::PSHUFD &&
21864          "Called with something other than an x86 128-bit half shuffle!");
21865   SDLoc DL(N);
21866
21867   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21868   // of the shuffles in the chain so that we can form a fresh chain to replace
21869   // this one.
21870   SmallVector<SDValue, 8> Chain;
21871   SDValue V = N.getOperand(0);
21872   for (; V.hasOneUse(); V = V.getOperand(0)) {
21873     switch (V.getOpcode()) {
21874     default:
21875       return SDValue(); // Nothing combined!
21876
21877     case ISD::BITCAST:
21878       // Skip bitcasts as we always know the type for the target specific
21879       // instructions.
21880       continue;
21881
21882     case X86ISD::PSHUFD:
21883       // Found another dword shuffle.
21884       break;
21885
21886     case X86ISD::PSHUFLW:
21887       // Check that the low words (being shuffled) are the identity in the
21888       // dword shuffle, and the high words are self-contained.
21889       if (Mask[0] != 0 || Mask[1] != 1 ||
21890           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21891         return SDValue();
21892
21893       Chain.push_back(V);
21894       continue;
21895
21896     case X86ISD::PSHUFHW:
21897       // Check that the high words (being shuffled) are the identity in the
21898       // dword shuffle, and the low words are self-contained.
21899       if (Mask[2] != 2 || Mask[3] != 3 ||
21900           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21901         return SDValue();
21902
21903       Chain.push_back(V);
21904       continue;
21905
21906     case X86ISD::UNPCKL:
21907     case X86ISD::UNPCKH:
21908       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21909       // shuffle into a preceding word shuffle.
21910       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21911           V.getSimpleValueType().getScalarType() != MVT::i16)
21912         return SDValue();
21913
21914       // Search for a half-shuffle which we can combine with.
21915       unsigned CombineOp =
21916           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21917       if (V.getOperand(0) != V.getOperand(1) ||
21918           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21919         return SDValue();
21920       Chain.push_back(V);
21921       V = V.getOperand(0);
21922       do {
21923         switch (V.getOpcode()) {
21924         default:
21925           return SDValue(); // Nothing to combine.
21926
21927         case X86ISD::PSHUFLW:
21928         case X86ISD::PSHUFHW:
21929           if (V.getOpcode() == CombineOp)
21930             break;
21931
21932           Chain.push_back(V);
21933
21934           // Fallthrough!
21935         case ISD::BITCAST:
21936           V = V.getOperand(0);
21937           continue;
21938         }
21939         break;
21940       } while (V.hasOneUse());
21941       break;
21942     }
21943     // Break out of the loop if we break out of the switch.
21944     break;
21945   }
21946
21947   if (!V.hasOneUse())
21948     // We fell out of the loop without finding a viable combining instruction.
21949     return SDValue();
21950
21951   // Merge this node's mask and our incoming mask.
21952   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21953   for (int &M : Mask)
21954     M = VMask[M];
21955   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21956                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21957
21958   // Rebuild the chain around this new shuffle.
21959   while (!Chain.empty()) {
21960     SDValue W = Chain.pop_back_val();
21961
21962     if (V.getValueType() != W.getOperand(0).getValueType())
21963       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21964
21965     switch (W.getOpcode()) {
21966     default:
21967       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21968
21969     case X86ISD::UNPCKL:
21970     case X86ISD::UNPCKH:
21971       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21972       break;
21973
21974     case X86ISD::PSHUFD:
21975     case X86ISD::PSHUFLW:
21976     case X86ISD::PSHUFHW:
21977       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21978       break;
21979     }
21980   }
21981   if (V.getValueType() != N.getValueType())
21982     V = DAG.getBitcast(N.getValueType(), V);
21983
21984   // Return the new chain to replace N.
21985   return V;
21986 }
21987
21988 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21989 ///
21990 /// We walk up the chain, skipping shuffles of the other half and looking
21991 /// through shuffles which switch halves trying to find a shuffle of the same
21992 /// pair of dwords.
21993 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21994                                         SelectionDAG &DAG,
21995                                         TargetLowering::DAGCombinerInfo &DCI) {
21996   assert(
21997       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21998       "Called with something other than an x86 128-bit half shuffle!");
21999   SDLoc DL(N);
22000   unsigned CombineOpcode = N.getOpcode();
22001
22002   // Walk up a single-use chain looking for a combinable shuffle.
22003   SDValue V = N.getOperand(0);
22004   for (; V.hasOneUse(); V = V.getOperand(0)) {
22005     switch (V.getOpcode()) {
22006     default:
22007       return false; // Nothing combined!
22008
22009     case ISD::BITCAST:
22010       // Skip bitcasts as we always know the type for the target specific
22011       // instructions.
22012       continue;
22013
22014     case X86ISD::PSHUFLW:
22015     case X86ISD::PSHUFHW:
22016       if (V.getOpcode() == CombineOpcode)
22017         break;
22018
22019       // Other-half shuffles are no-ops.
22020       continue;
22021     }
22022     // Break out of the loop if we break out of the switch.
22023     break;
22024   }
22025
22026   if (!V.hasOneUse())
22027     // We fell out of the loop without finding a viable combining instruction.
22028     return false;
22029
22030   // Combine away the bottom node as its shuffle will be accumulated into
22031   // a preceding shuffle.
22032   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22033
22034   // Record the old value.
22035   SDValue Old = V;
22036
22037   // Merge this node's mask and our incoming mask (adjusted to account for all
22038   // the pshufd instructions encountered).
22039   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22040   for (int &M : Mask)
22041     M = VMask[M];
22042   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22043                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22044
22045   // Check that the shuffles didn't cancel each other out. If not, we need to
22046   // combine to the new one.
22047   if (Old != V)
22048     // Replace the combinable shuffle with the combined one, updating all users
22049     // so that we re-evaluate the chain here.
22050     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22051
22052   return true;
22053 }
22054
22055 /// \brief Try to combine x86 target specific shuffles.
22056 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22057                                            TargetLowering::DAGCombinerInfo &DCI,
22058                                            const X86Subtarget *Subtarget) {
22059   SDLoc DL(N);
22060   MVT VT = N.getSimpleValueType();
22061   SmallVector<int, 4> Mask;
22062
22063   switch (N.getOpcode()) {
22064   case X86ISD::PSHUFD:
22065   case X86ISD::PSHUFLW:
22066   case X86ISD::PSHUFHW:
22067     Mask = getPSHUFShuffleMask(N);
22068     assert(Mask.size() == 4);
22069     break;
22070   default:
22071     return SDValue();
22072   }
22073
22074   // Nuke no-op shuffles that show up after combining.
22075   if (isNoopShuffleMask(Mask))
22076     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22077
22078   // Look for simplifications involving one or two shuffle instructions.
22079   SDValue V = N.getOperand(0);
22080   switch (N.getOpcode()) {
22081   default:
22082     break;
22083   case X86ISD::PSHUFLW:
22084   case X86ISD::PSHUFHW:
22085     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22086
22087     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22088       return SDValue(); // We combined away this shuffle, so we're done.
22089
22090     // See if this reduces to a PSHUFD which is no more expensive and can
22091     // combine with more operations. Note that it has to at least flip the
22092     // dwords as otherwise it would have been removed as a no-op.
22093     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22094       int DMask[] = {0, 1, 2, 3};
22095       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22096       DMask[DOffset + 0] = DOffset + 1;
22097       DMask[DOffset + 1] = DOffset + 0;
22098       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22099       V = DAG.getBitcast(DVT, V);
22100       DCI.AddToWorklist(V.getNode());
22101       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22102                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22103       DCI.AddToWorklist(V.getNode());
22104       return DAG.getBitcast(VT, V);
22105     }
22106
22107     // Look for shuffle patterns which can be implemented as a single unpack.
22108     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22109     // only works when we have a PSHUFD followed by two half-shuffles.
22110     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22111         (V.getOpcode() == X86ISD::PSHUFLW ||
22112          V.getOpcode() == X86ISD::PSHUFHW) &&
22113         V.getOpcode() != N.getOpcode() &&
22114         V.hasOneUse()) {
22115       SDValue D = V.getOperand(0);
22116       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22117         D = D.getOperand(0);
22118       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22119         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22120         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22121         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22122         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22123         int WordMask[8];
22124         for (int i = 0; i < 4; ++i) {
22125           WordMask[i + NOffset] = Mask[i] + NOffset;
22126           WordMask[i + VOffset] = VMask[i] + VOffset;
22127         }
22128         // Map the word mask through the DWord mask.
22129         int MappedMask[8];
22130         for (int i = 0; i < 8; ++i)
22131           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22132         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22133             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22134           // We can replace all three shuffles with an unpack.
22135           V = DAG.getBitcast(VT, D.getOperand(0));
22136           DCI.AddToWorklist(V.getNode());
22137           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22138                                                 : X86ISD::UNPCKH,
22139                              DL, VT, V, V);
22140         }
22141       }
22142     }
22143
22144     break;
22145
22146   case X86ISD::PSHUFD:
22147     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22148       return NewN;
22149
22150     break;
22151   }
22152
22153   return SDValue();
22154 }
22155
22156 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22157 ///
22158 /// We combine this directly on the abstract vector shuffle nodes so it is
22159 /// easier to generically match. We also insert dummy vector shuffle nodes for
22160 /// the operands which explicitly discard the lanes which are unused by this
22161 /// operation to try to flow through the rest of the combiner the fact that
22162 /// they're unused.
22163 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22164   SDLoc DL(N);
22165   EVT VT = N->getValueType(0);
22166
22167   // We only handle target-independent shuffles.
22168   // FIXME: It would be easy and harmless to use the target shuffle mask
22169   // extraction tool to support more.
22170   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22171     return SDValue();
22172
22173   auto *SVN = cast<ShuffleVectorSDNode>(N);
22174   ArrayRef<int> Mask = SVN->getMask();
22175   SDValue V1 = N->getOperand(0);
22176   SDValue V2 = N->getOperand(1);
22177
22178   // We require the first shuffle operand to be the SUB node, and the second to
22179   // be the ADD node.
22180   // FIXME: We should support the commuted patterns.
22181   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22182     return SDValue();
22183
22184   // If there are other uses of these operations we can't fold them.
22185   if (!V1->hasOneUse() || !V2->hasOneUse())
22186     return SDValue();
22187
22188   // Ensure that both operations have the same operands. Note that we can
22189   // commute the FADD operands.
22190   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22191   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22192       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22193     return SDValue();
22194
22195   // We're looking for blends between FADD and FSUB nodes. We insist on these
22196   // nodes being lined up in a specific expected pattern.
22197   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22198         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22199         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22200     return SDValue();
22201
22202   // Only specific types are legal at this point, assert so we notice if and
22203   // when these change.
22204   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22205           VT == MVT::v4f64) &&
22206          "Unknown vector type encountered!");
22207
22208   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22209 }
22210
22211 /// PerformShuffleCombine - Performs several different shuffle combines.
22212 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22213                                      TargetLowering::DAGCombinerInfo &DCI,
22214                                      const X86Subtarget *Subtarget) {
22215   SDLoc dl(N);
22216   SDValue N0 = N->getOperand(0);
22217   SDValue N1 = N->getOperand(1);
22218   EVT VT = N->getValueType(0);
22219
22220   // Don't create instructions with illegal types after legalize types has run.
22221   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22222   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22223     return SDValue();
22224
22225   // If we have legalized the vector types, look for blends of FADD and FSUB
22226   // nodes that we can fuse into an ADDSUB node.
22227   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22228     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22229       return AddSub;
22230
22231   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22232   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22233       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22234     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22235
22236   // During Type Legalization, when promoting illegal vector types,
22237   // the backend might introduce new shuffle dag nodes and bitcasts.
22238   //
22239   // This code performs the following transformation:
22240   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22241   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22242   //
22243   // We do this only if both the bitcast and the BINOP dag nodes have
22244   // one use. Also, perform this transformation only if the new binary
22245   // operation is legal. This is to avoid introducing dag nodes that
22246   // potentially need to be further expanded (or custom lowered) into a
22247   // less optimal sequence of dag nodes.
22248   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22249       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22250       N0.getOpcode() == ISD::BITCAST) {
22251     SDValue BC0 = N0.getOperand(0);
22252     EVT SVT = BC0.getValueType();
22253     unsigned Opcode = BC0.getOpcode();
22254     unsigned NumElts = VT.getVectorNumElements();
22255
22256     if (BC0.hasOneUse() && SVT.isVector() &&
22257         SVT.getVectorNumElements() * 2 == NumElts &&
22258         TLI.isOperationLegal(Opcode, VT)) {
22259       bool CanFold = false;
22260       switch (Opcode) {
22261       default : break;
22262       case ISD::ADD :
22263       case ISD::FADD :
22264       case ISD::SUB :
22265       case ISD::FSUB :
22266       case ISD::MUL :
22267       case ISD::FMUL :
22268         CanFold = true;
22269       }
22270
22271       unsigned SVTNumElts = SVT.getVectorNumElements();
22272       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22273       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22274         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22275       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22276         CanFold = SVOp->getMaskElt(i) < 0;
22277
22278       if (CanFold) {
22279         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22280         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22281         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22282         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22283       }
22284     }
22285   }
22286
22287   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22288   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22289   // consecutive, non-overlapping, and in the right order.
22290   SmallVector<SDValue, 16> Elts;
22291   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22292     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22293
22294   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22295     return LD;
22296
22297   if (isTargetShuffle(N->getOpcode())) {
22298     SDValue Shuffle =
22299         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22300     if (Shuffle.getNode())
22301       return Shuffle;
22302
22303     // Try recursively combining arbitrary sequences of x86 shuffle
22304     // instructions into higher-order shuffles. We do this after combining
22305     // specific PSHUF instruction sequences into their minimal form so that we
22306     // can evaluate how many specialized shuffle instructions are involved in
22307     // a particular chain.
22308     SmallVector<int, 1> NonceMask; // Just a placeholder.
22309     NonceMask.push_back(0);
22310     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22311                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22312                                       DCI, Subtarget))
22313       return SDValue(); // This routine will use CombineTo to replace N.
22314   }
22315
22316   return SDValue();
22317 }
22318
22319 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22320 /// specific shuffle of a load can be folded into a single element load.
22321 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22322 /// shuffles have been custom lowered so we need to handle those here.
22323 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22324                                          TargetLowering::DAGCombinerInfo &DCI) {
22325   if (DCI.isBeforeLegalizeOps())
22326     return SDValue();
22327
22328   SDValue InVec = N->getOperand(0);
22329   SDValue EltNo = N->getOperand(1);
22330
22331   if (!isa<ConstantSDNode>(EltNo))
22332     return SDValue();
22333
22334   EVT OriginalVT = InVec.getValueType();
22335
22336   if (InVec.getOpcode() == ISD::BITCAST) {
22337     // Don't duplicate a load with other uses.
22338     if (!InVec.hasOneUse())
22339       return SDValue();
22340     EVT BCVT = InVec.getOperand(0).getValueType();
22341     if (!BCVT.isVector() ||
22342         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22343       return SDValue();
22344     InVec = InVec.getOperand(0);
22345   }
22346
22347   EVT CurrentVT = InVec.getValueType();
22348
22349   if (!isTargetShuffle(InVec.getOpcode()))
22350     return SDValue();
22351
22352   // Don't duplicate a load with other uses.
22353   if (!InVec.hasOneUse())
22354     return SDValue();
22355
22356   SmallVector<int, 16> ShuffleMask;
22357   bool UnaryShuffle;
22358   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22359                             ShuffleMask, UnaryShuffle))
22360     return SDValue();
22361
22362   // Select the input vector, guarding against out of range extract vector.
22363   unsigned NumElems = CurrentVT.getVectorNumElements();
22364   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22365   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22366   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22367                                          : InVec.getOperand(1);
22368
22369   // If inputs to shuffle are the same for both ops, then allow 2 uses
22370   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22371                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22372
22373   if (LdNode.getOpcode() == ISD::BITCAST) {
22374     // Don't duplicate a load with other uses.
22375     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22376       return SDValue();
22377
22378     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22379     LdNode = LdNode.getOperand(0);
22380   }
22381
22382   if (!ISD::isNormalLoad(LdNode.getNode()))
22383     return SDValue();
22384
22385   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22386
22387   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22388     return SDValue();
22389
22390   EVT EltVT = N->getValueType(0);
22391   // If there's a bitcast before the shuffle, check if the load type and
22392   // alignment is valid.
22393   unsigned Align = LN0->getAlignment();
22394   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22395   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22396       EltVT.getTypeForEVT(*DAG.getContext()));
22397
22398   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22399     return SDValue();
22400
22401   // All checks match so transform back to vector_shuffle so that DAG combiner
22402   // can finish the job
22403   SDLoc dl(N);
22404
22405   // Create shuffle node taking into account the case that its a unary shuffle
22406   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22407                                    : InVec.getOperand(1);
22408   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22409                                  InVec.getOperand(0), Shuffle,
22410                                  &ShuffleMask[0]);
22411   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22412   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22413                      EltNo);
22414 }
22415
22416 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22417 /// special and don't usually play with other vector types, it's better to
22418 /// handle them early to be sure we emit efficient code by avoiding
22419 /// store-load conversions.
22420 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22421   if (N->getValueType(0) != MVT::x86mmx ||
22422       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22423       N->getOperand(0)->getValueType(0) != MVT::v2i32)
22424     return SDValue();
22425
22426   SDValue V = N->getOperand(0);
22427   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22428   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22429     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22430                        N->getValueType(0), V.getOperand(0));
22431
22432   return SDValue();
22433 }
22434
22435 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22436 /// generation and convert it from being a bunch of shuffles and extracts
22437 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22438 /// storing the value and loading scalars back, while for x64 we should
22439 /// use 64-bit extracts and shifts.
22440 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22441                                          TargetLowering::DAGCombinerInfo &DCI) {
22442   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22443     return NewOp;
22444
22445   SDValue InputVector = N->getOperand(0);
22446   SDLoc dl(InputVector);
22447   // Detect mmx to i32 conversion through a v2i32 elt extract.
22448   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22449       N->getValueType(0) == MVT::i32 &&
22450       InputVector.getValueType() == MVT::v2i32) {
22451
22452     // The bitcast source is a direct mmx result.
22453     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22454     if (MMXSrc.getValueType() == MVT::x86mmx)
22455       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22456                          N->getValueType(0),
22457                          InputVector.getNode()->getOperand(0));
22458
22459     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22460     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22461     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22462         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22463         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22464         MMXSrcOp.getValueType() == MVT::v1i64 &&
22465         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22466       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22467                          N->getValueType(0),
22468                          MMXSrcOp.getOperand(0));
22469   }
22470
22471   EVT VT = N->getValueType(0);
22472
22473   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22474       InputVector.getOpcode() == ISD::BITCAST &&
22475       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22476     uint64_t ExtractedElt =
22477           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22478     uint64_t InputValue =
22479           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22480     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22481     return DAG.getConstant(Res, dl, MVT::i1);
22482   }
22483   // Only operate on vectors of 4 elements, where the alternative shuffling
22484   // gets to be more expensive.
22485   if (InputVector.getValueType() != MVT::v4i32)
22486     return SDValue();
22487
22488   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22489   // single use which is a sign-extend or zero-extend, and all elements are
22490   // used.
22491   SmallVector<SDNode *, 4> Uses;
22492   unsigned ExtractedElements = 0;
22493   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22494        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22495     if (UI.getUse().getResNo() != InputVector.getResNo())
22496       return SDValue();
22497
22498     SDNode *Extract = *UI;
22499     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22500       return SDValue();
22501
22502     if (Extract->getValueType(0) != MVT::i32)
22503       return SDValue();
22504     if (!Extract->hasOneUse())
22505       return SDValue();
22506     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22507         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22508       return SDValue();
22509     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22510       return SDValue();
22511
22512     // Record which element was extracted.
22513     ExtractedElements |=
22514       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22515
22516     Uses.push_back(Extract);
22517   }
22518
22519   // If not all the elements were used, this may not be worthwhile.
22520   if (ExtractedElements != 15)
22521     return SDValue();
22522
22523   // Ok, we've now decided to do the transformation.
22524   // If 64-bit shifts are legal, use the extract-shift sequence,
22525   // otherwise bounce the vector off the cache.
22526   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22527   SDValue Vals[4];
22528
22529   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22530     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22531     auto &DL = DAG.getDataLayout();
22532     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22533     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22534       DAG.getConstant(0, dl, VecIdxTy));
22535     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22536       DAG.getConstant(1, dl, VecIdxTy));
22537
22538     SDValue ShAmt = DAG.getConstant(
22539         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22540     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22541     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22542       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22543     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22544     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22545       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22546   } else {
22547     // Store the value to a temporary stack slot.
22548     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22549     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22550       MachinePointerInfo(), false, false, 0);
22551
22552     EVT ElementType = InputVector.getValueType().getVectorElementType();
22553     unsigned EltSize = ElementType.getSizeInBits() / 8;
22554
22555     // Replace each use (extract) with a load of the appropriate element.
22556     for (unsigned i = 0; i < 4; ++i) {
22557       uint64_t Offset = EltSize * i;
22558       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22559       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22560
22561       SDValue ScalarAddr =
22562           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22563
22564       // Load the scalar.
22565       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22566                             ScalarAddr, MachinePointerInfo(),
22567                             false, false, false, 0);
22568
22569     }
22570   }
22571
22572   // Replace the extracts
22573   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22574     UE = Uses.end(); UI != UE; ++UI) {
22575     SDNode *Extract = *UI;
22576
22577     SDValue Idx = Extract->getOperand(1);
22578     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22579     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22580   }
22581
22582   // The replacement was made in place; don't return anything.
22583   return SDValue();
22584 }
22585
22586 static SDValue
22587 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22588                                       const X86Subtarget *Subtarget) {
22589   SDLoc dl(N);
22590   SDValue Cond = N->getOperand(0);
22591   SDValue LHS = N->getOperand(1);
22592   SDValue RHS = N->getOperand(2);
22593
22594   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22595     SDValue CondSrc = Cond->getOperand(0);
22596     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22597       Cond = CondSrc->getOperand(0);
22598   }
22599
22600   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22601     return SDValue();
22602
22603   // A vselect where all conditions and data are constants can be optimized into
22604   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22605   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22606       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22607     return SDValue();
22608
22609   unsigned MaskValue = 0;
22610   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22611     return SDValue();
22612
22613   MVT VT = N->getSimpleValueType(0);
22614   unsigned NumElems = VT.getVectorNumElements();
22615   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22616   for (unsigned i = 0; i < NumElems; ++i) {
22617     // Be sure we emit undef where we can.
22618     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22619       ShuffleMask[i] = -1;
22620     else
22621       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22622   }
22623
22624   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22625   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22626     return SDValue();
22627   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22628 }
22629
22630 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22631 /// nodes.
22632 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22633                                     TargetLowering::DAGCombinerInfo &DCI,
22634                                     const X86Subtarget *Subtarget) {
22635   SDLoc DL(N);
22636   SDValue Cond = N->getOperand(0);
22637   // Get the LHS/RHS of the select.
22638   SDValue LHS = N->getOperand(1);
22639   SDValue RHS = N->getOperand(2);
22640   EVT VT = LHS.getValueType();
22641   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22642
22643   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22644   // instructions match the semantics of the common C idiom x<y?x:y but not
22645   // x<=y?x:y, because of how they handle negative zero (which can be
22646   // ignored in unsafe-math mode).
22647   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22648   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22649       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22650       (Subtarget->hasSSE2() ||
22651        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22652     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22653
22654     unsigned Opcode = 0;
22655     // Check for x CC y ? x : y.
22656     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22657         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22658       switch (CC) {
22659       default: break;
22660       case ISD::SETULT:
22661         // Converting this to a min would handle NaNs incorrectly, and swapping
22662         // the operands would cause it to handle comparisons between positive
22663         // and negative zero incorrectly.
22664         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22665           if (!DAG.getTarget().Options.UnsafeFPMath &&
22666               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22667             break;
22668           std::swap(LHS, RHS);
22669         }
22670         Opcode = X86ISD::FMIN;
22671         break;
22672       case ISD::SETOLE:
22673         // Converting this to a min would handle comparisons between positive
22674         // and negative zero incorrectly.
22675         if (!DAG.getTarget().Options.UnsafeFPMath &&
22676             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22677           break;
22678         Opcode = X86ISD::FMIN;
22679         break;
22680       case ISD::SETULE:
22681         // Converting this to a min would handle both negative zeros and NaNs
22682         // incorrectly, but we can swap the operands to fix both.
22683         std::swap(LHS, RHS);
22684       case ISD::SETOLT:
22685       case ISD::SETLT:
22686       case ISD::SETLE:
22687         Opcode = X86ISD::FMIN;
22688         break;
22689
22690       case ISD::SETOGE:
22691         // Converting this to a max would handle comparisons between positive
22692         // and negative zero incorrectly.
22693         if (!DAG.getTarget().Options.UnsafeFPMath &&
22694             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22695           break;
22696         Opcode = X86ISD::FMAX;
22697         break;
22698       case ISD::SETUGT:
22699         // Converting this to a max would handle NaNs incorrectly, and swapping
22700         // the operands would cause it to handle comparisons between positive
22701         // and negative zero incorrectly.
22702         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22703           if (!DAG.getTarget().Options.UnsafeFPMath &&
22704               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22705             break;
22706           std::swap(LHS, RHS);
22707         }
22708         Opcode = X86ISD::FMAX;
22709         break;
22710       case ISD::SETUGE:
22711         // Converting this to a max would handle both negative zeros and NaNs
22712         // incorrectly, but we can swap the operands to fix both.
22713         std::swap(LHS, RHS);
22714       case ISD::SETOGT:
22715       case ISD::SETGT:
22716       case ISD::SETGE:
22717         Opcode = X86ISD::FMAX;
22718         break;
22719       }
22720     // Check for x CC y ? y : x -- a min/max with reversed arms.
22721     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22722                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22723       switch (CC) {
22724       default: break;
22725       case ISD::SETOGE:
22726         // Converting this to a min would handle comparisons between positive
22727         // and negative zero incorrectly, and swapping the operands would
22728         // cause it to handle NaNs incorrectly.
22729         if (!DAG.getTarget().Options.UnsafeFPMath &&
22730             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22731           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22732             break;
22733           std::swap(LHS, RHS);
22734         }
22735         Opcode = X86ISD::FMIN;
22736         break;
22737       case ISD::SETUGT:
22738         // Converting this to a min would handle NaNs incorrectly.
22739         if (!DAG.getTarget().Options.UnsafeFPMath &&
22740             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22741           break;
22742         Opcode = X86ISD::FMIN;
22743         break;
22744       case ISD::SETUGE:
22745         // Converting this to a min would handle both negative zeros and NaNs
22746         // incorrectly, but we can swap the operands to fix both.
22747         std::swap(LHS, RHS);
22748       case ISD::SETOGT:
22749       case ISD::SETGT:
22750       case ISD::SETGE:
22751         Opcode = X86ISD::FMIN;
22752         break;
22753
22754       case ISD::SETULT:
22755         // Converting this to a max would handle NaNs incorrectly.
22756         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22757           break;
22758         Opcode = X86ISD::FMAX;
22759         break;
22760       case ISD::SETOLE:
22761         // Converting this to a max would handle comparisons between positive
22762         // and negative zero incorrectly, and swapping the operands would
22763         // cause it to handle NaNs incorrectly.
22764         if (!DAG.getTarget().Options.UnsafeFPMath &&
22765             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22766           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22767             break;
22768           std::swap(LHS, RHS);
22769         }
22770         Opcode = X86ISD::FMAX;
22771         break;
22772       case ISD::SETULE:
22773         // Converting this to a max would handle both negative zeros and NaNs
22774         // incorrectly, but we can swap the operands to fix both.
22775         std::swap(LHS, RHS);
22776       case ISD::SETOLT:
22777       case ISD::SETLT:
22778       case ISD::SETLE:
22779         Opcode = X86ISD::FMAX;
22780         break;
22781       }
22782     }
22783
22784     if (Opcode)
22785       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22786   }
22787
22788   EVT CondVT = Cond.getValueType();
22789   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22790       CondVT.getVectorElementType() == MVT::i1) {
22791     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22792     // lowering on KNL. In this case we convert it to
22793     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22794     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22795     // Since SKX these selects have a proper lowering.
22796     EVT OpVT = LHS.getValueType();
22797     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22798         (OpVT.getVectorElementType() == MVT::i8 ||
22799          OpVT.getVectorElementType() == MVT::i16) &&
22800         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22801       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22802       DCI.AddToWorklist(Cond.getNode());
22803       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22804     }
22805   }
22806   // If this is a select between two integer constants, try to do some
22807   // optimizations.
22808   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22809     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22810       // Don't do this for crazy integer types.
22811       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22812         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22813         // so that TrueC (the true value) is larger than FalseC.
22814         bool NeedsCondInvert = false;
22815
22816         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22817             // Efficiently invertible.
22818             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22819              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22820               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22821           NeedsCondInvert = true;
22822           std::swap(TrueC, FalseC);
22823         }
22824
22825         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22826         if (FalseC->getAPIntValue() == 0 &&
22827             TrueC->getAPIntValue().isPowerOf2()) {
22828           if (NeedsCondInvert) // Invert the condition if needed.
22829             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22830                                DAG.getConstant(1, DL, Cond.getValueType()));
22831
22832           // Zero extend the condition if needed.
22833           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22834
22835           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22836           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22837                              DAG.getConstant(ShAmt, DL, MVT::i8));
22838         }
22839
22840         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22841         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22842           if (NeedsCondInvert) // Invert the condition if needed.
22843             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22844                                DAG.getConstant(1, DL, Cond.getValueType()));
22845
22846           // Zero extend the condition if needed.
22847           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22848                              FalseC->getValueType(0), Cond);
22849           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22850                              SDValue(FalseC, 0));
22851         }
22852
22853         // Optimize cases that will turn into an LEA instruction.  This requires
22854         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22855         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22856           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22857           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22858
22859           bool isFastMultiplier = false;
22860           if (Diff < 10) {
22861             switch ((unsigned char)Diff) {
22862               default: break;
22863               case 1:  // result = add base, cond
22864               case 2:  // result = lea base(    , cond*2)
22865               case 3:  // result = lea base(cond, cond*2)
22866               case 4:  // result = lea base(    , cond*4)
22867               case 5:  // result = lea base(cond, cond*4)
22868               case 8:  // result = lea base(    , cond*8)
22869               case 9:  // result = lea base(cond, cond*8)
22870                 isFastMultiplier = true;
22871                 break;
22872             }
22873           }
22874
22875           if (isFastMultiplier) {
22876             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22877             if (NeedsCondInvert) // Invert the condition if needed.
22878               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22879                                  DAG.getConstant(1, DL, Cond.getValueType()));
22880
22881             // Zero extend the condition if needed.
22882             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22883                                Cond);
22884             // Scale the condition by the difference.
22885             if (Diff != 1)
22886               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22887                                  DAG.getConstant(Diff, DL,
22888                                                  Cond.getValueType()));
22889
22890             // Add the base if non-zero.
22891             if (FalseC->getAPIntValue() != 0)
22892               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22893                                  SDValue(FalseC, 0));
22894             return Cond;
22895           }
22896         }
22897       }
22898   }
22899
22900   // Canonicalize max and min:
22901   // (x > y) ? x : y -> (x >= y) ? x : y
22902   // (x < y) ? x : y -> (x <= y) ? x : y
22903   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22904   // the need for an extra compare
22905   // against zero. e.g.
22906   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22907   // subl   %esi, %edi
22908   // testl  %edi, %edi
22909   // movl   $0, %eax
22910   // cmovgl %edi, %eax
22911   // =>
22912   // xorl   %eax, %eax
22913   // subl   %esi, $edi
22914   // cmovsl %eax, %edi
22915   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22916       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22917       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22918     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22919     switch (CC) {
22920     default: break;
22921     case ISD::SETLT:
22922     case ISD::SETGT: {
22923       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22924       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22925                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22926       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22927     }
22928     }
22929   }
22930
22931   // Early exit check
22932   if (!TLI.isTypeLegal(VT))
22933     return SDValue();
22934
22935   // Match VSELECTs into subs with unsigned saturation.
22936   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22937       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22938       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22939        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22940     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22941
22942     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22943     // left side invert the predicate to simplify logic below.
22944     SDValue Other;
22945     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22946       Other = RHS;
22947       CC = ISD::getSetCCInverse(CC, true);
22948     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22949       Other = LHS;
22950     }
22951
22952     if (Other.getNode() && Other->getNumOperands() == 2 &&
22953         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22954       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22955       SDValue CondRHS = Cond->getOperand(1);
22956
22957       // Look for a general sub with unsigned saturation first.
22958       // x >= y ? x-y : 0 --> subus x, y
22959       // x >  y ? x-y : 0 --> subus x, y
22960       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22961           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22962         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22963
22964       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22965         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22966           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22967             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22968               // If the RHS is a constant we have to reverse the const
22969               // canonicalization.
22970               // x > C-1 ? x+-C : 0 --> subus x, C
22971               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22972                   CondRHSConst->getAPIntValue() ==
22973                       (-OpRHSConst->getAPIntValue() - 1))
22974                 return DAG.getNode(
22975                     X86ISD::SUBUS, DL, VT, OpLHS,
22976                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22977
22978           // Another special case: If C was a sign bit, the sub has been
22979           // canonicalized into a xor.
22980           // FIXME: Would it be better to use computeKnownBits to determine
22981           //        whether it's safe to decanonicalize the xor?
22982           // x s< 0 ? x^C : 0 --> subus x, C
22983           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22984               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22985               OpRHSConst->getAPIntValue().isSignBit())
22986             // Note that we have to rebuild the RHS constant here to ensure we
22987             // don't rely on particular values of undef lanes.
22988             return DAG.getNode(
22989                 X86ISD::SUBUS, DL, VT, OpLHS,
22990                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22991         }
22992     }
22993   }
22994
22995   // Simplify vector selection if condition value type matches vselect
22996   // operand type
22997   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22998     assert(Cond.getValueType().isVector() &&
22999            "vector select expects a vector selector!");
23000
23001     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23002     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23003
23004     // Try invert the condition if true value is not all 1s and false value
23005     // is not all 0s.
23006     if (!TValIsAllOnes && !FValIsAllZeros &&
23007         // Check if the selector will be produced by CMPP*/PCMP*
23008         Cond.getOpcode() == ISD::SETCC &&
23009         // Check if SETCC has already been promoted
23010         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23011             CondVT) {
23012       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23013       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23014
23015       if (TValIsAllZeros || FValIsAllOnes) {
23016         SDValue CC = Cond.getOperand(2);
23017         ISD::CondCode NewCC =
23018           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23019                                Cond.getOperand(0).getValueType().isInteger());
23020         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23021         std::swap(LHS, RHS);
23022         TValIsAllOnes = FValIsAllOnes;
23023         FValIsAllZeros = TValIsAllZeros;
23024       }
23025     }
23026
23027     if (TValIsAllOnes || FValIsAllZeros) {
23028       SDValue Ret;
23029
23030       if (TValIsAllOnes && FValIsAllZeros)
23031         Ret = Cond;
23032       else if (TValIsAllOnes)
23033         Ret =
23034             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23035       else if (FValIsAllZeros)
23036         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23037                           DAG.getBitcast(CondVT, LHS));
23038
23039       return DAG.getBitcast(VT, Ret);
23040     }
23041   }
23042
23043   // We should generate an X86ISD::BLENDI from a vselect if its argument
23044   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23045   // constants. This specific pattern gets generated when we split a
23046   // selector for a 512 bit vector in a machine without AVX512 (but with
23047   // 256-bit vectors), during legalization:
23048   //
23049   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23050   //
23051   // Iff we find this pattern and the build_vectors are built from
23052   // constants, we translate the vselect into a shuffle_vector that we
23053   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23054   if ((N->getOpcode() == ISD::VSELECT ||
23055        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23056       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23057     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23058     if (Shuffle.getNode())
23059       return Shuffle;
23060   }
23061
23062   // If this is a *dynamic* select (non-constant condition) and we can match
23063   // this node with one of the variable blend instructions, restructure the
23064   // condition so that the blends can use the high bit of each element and use
23065   // SimplifyDemandedBits to simplify the condition operand.
23066   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23067       !DCI.isBeforeLegalize() &&
23068       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23069     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23070
23071     // Don't optimize vector selects that map to mask-registers.
23072     if (BitWidth == 1)
23073       return SDValue();
23074
23075     // We can only handle the cases where VSELECT is directly legal on the
23076     // subtarget. We custom lower VSELECT nodes with constant conditions and
23077     // this makes it hard to see whether a dynamic VSELECT will correctly
23078     // lower, so we both check the operation's status and explicitly handle the
23079     // cases where a *dynamic* blend will fail even though a constant-condition
23080     // blend could be custom lowered.
23081     // FIXME: We should find a better way to handle this class of problems.
23082     // Potentially, we should combine constant-condition vselect nodes
23083     // pre-legalization into shuffles and not mark as many types as custom
23084     // lowered.
23085     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23086       return SDValue();
23087     // FIXME: We don't support i16-element blends currently. We could and
23088     // should support them by making *all* the bits in the condition be set
23089     // rather than just the high bit and using an i8-element blend.
23090     if (VT.getScalarType() == MVT::i16)
23091       return SDValue();
23092     // Dynamic blending was only available from SSE4.1 onward.
23093     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23094       return SDValue();
23095     // Byte blends are only available in AVX2
23096     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23097         !Subtarget->hasAVX2())
23098       return SDValue();
23099
23100     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23101     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23102
23103     APInt KnownZero, KnownOne;
23104     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23105                                           DCI.isBeforeLegalizeOps());
23106     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23107         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23108                                  TLO)) {
23109       // If we changed the computation somewhere in the DAG, this change
23110       // will affect all users of Cond.
23111       // Make sure it is fine and update all the nodes so that we do not
23112       // use the generic VSELECT anymore. Otherwise, we may perform
23113       // wrong optimizations as we messed up with the actual expectation
23114       // for the vector boolean values.
23115       if (Cond != TLO.Old) {
23116         // Check all uses of that condition operand to check whether it will be
23117         // consumed by non-BLEND instructions, which may depend on all bits are
23118         // set properly.
23119         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23120              I != E; ++I)
23121           if (I->getOpcode() != ISD::VSELECT)
23122             // TODO: Add other opcodes eventually lowered into BLEND.
23123             return SDValue();
23124
23125         // Update all the users of the condition, before committing the change,
23126         // so that the VSELECT optimizations that expect the correct vector
23127         // boolean value will not be triggered.
23128         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23129              I != E; ++I)
23130           DAG.ReplaceAllUsesOfValueWith(
23131               SDValue(*I, 0),
23132               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23133                           Cond, I->getOperand(1), I->getOperand(2)));
23134         DCI.CommitTargetLoweringOpt(TLO);
23135         return SDValue();
23136       }
23137       // At this point, only Cond is changed. Change the condition
23138       // just for N to keep the opportunity to optimize all other
23139       // users their own way.
23140       DAG.ReplaceAllUsesOfValueWith(
23141           SDValue(N, 0),
23142           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23143                       TLO.New, N->getOperand(1), N->getOperand(2)));
23144       return SDValue();
23145     }
23146   }
23147
23148   return SDValue();
23149 }
23150
23151 // Check whether a boolean test is testing a boolean value generated by
23152 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23153 // code.
23154 //
23155 // Simplify the following patterns:
23156 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23157 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23158 // to (Op EFLAGS Cond)
23159 //
23160 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23161 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23162 // to (Op EFLAGS !Cond)
23163 //
23164 // where Op could be BRCOND or CMOV.
23165 //
23166 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23167   // Quit if not CMP and SUB with its value result used.
23168   if (Cmp.getOpcode() != X86ISD::CMP &&
23169       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23170       return SDValue();
23171
23172   // Quit if not used as a boolean value.
23173   if (CC != X86::COND_E && CC != X86::COND_NE)
23174     return SDValue();
23175
23176   // Check CMP operands. One of them should be 0 or 1 and the other should be
23177   // an SetCC or extended from it.
23178   SDValue Op1 = Cmp.getOperand(0);
23179   SDValue Op2 = Cmp.getOperand(1);
23180
23181   SDValue SetCC;
23182   const ConstantSDNode* C = nullptr;
23183   bool needOppositeCond = (CC == X86::COND_E);
23184   bool checkAgainstTrue = false; // Is it a comparison against 1?
23185
23186   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23187     SetCC = Op2;
23188   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23189     SetCC = Op1;
23190   else // Quit if all operands are not constants.
23191     return SDValue();
23192
23193   if (C->getZExtValue() == 1) {
23194     needOppositeCond = !needOppositeCond;
23195     checkAgainstTrue = true;
23196   } else if (C->getZExtValue() != 0)
23197     // Quit if the constant is neither 0 or 1.
23198     return SDValue();
23199
23200   bool truncatedToBoolWithAnd = false;
23201   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23202   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23203          SetCC.getOpcode() == ISD::TRUNCATE ||
23204          SetCC.getOpcode() == ISD::AND) {
23205     if (SetCC.getOpcode() == ISD::AND) {
23206       int OpIdx = -1;
23207       ConstantSDNode *CS;
23208       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23209           CS->getZExtValue() == 1)
23210         OpIdx = 1;
23211       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23212           CS->getZExtValue() == 1)
23213         OpIdx = 0;
23214       if (OpIdx == -1)
23215         break;
23216       SetCC = SetCC.getOperand(OpIdx);
23217       truncatedToBoolWithAnd = true;
23218     } else
23219       SetCC = SetCC.getOperand(0);
23220   }
23221
23222   switch (SetCC.getOpcode()) {
23223   case X86ISD::SETCC_CARRY:
23224     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23225     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23226     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23227     // truncated to i1 using 'and'.
23228     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23229       break;
23230     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23231            "Invalid use of SETCC_CARRY!");
23232     // FALL THROUGH
23233   case X86ISD::SETCC:
23234     // Set the condition code or opposite one if necessary.
23235     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23236     if (needOppositeCond)
23237       CC = X86::GetOppositeBranchCondition(CC);
23238     return SetCC.getOperand(1);
23239   case X86ISD::CMOV: {
23240     // Check whether false/true value has canonical one, i.e. 0 or 1.
23241     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23242     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23243     // Quit if true value is not a constant.
23244     if (!TVal)
23245       return SDValue();
23246     // Quit if false value is not a constant.
23247     if (!FVal) {
23248       SDValue Op = SetCC.getOperand(0);
23249       // Skip 'zext' or 'trunc' node.
23250       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23251           Op.getOpcode() == ISD::TRUNCATE)
23252         Op = Op.getOperand(0);
23253       // A special case for rdrand/rdseed, where 0 is set if false cond is
23254       // found.
23255       if ((Op.getOpcode() != X86ISD::RDRAND &&
23256            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23257         return SDValue();
23258     }
23259     // Quit if false value is not the constant 0 or 1.
23260     bool FValIsFalse = true;
23261     if (FVal && FVal->getZExtValue() != 0) {
23262       if (FVal->getZExtValue() != 1)
23263         return SDValue();
23264       // If FVal is 1, opposite cond is needed.
23265       needOppositeCond = !needOppositeCond;
23266       FValIsFalse = false;
23267     }
23268     // Quit if TVal is not the constant opposite of FVal.
23269     if (FValIsFalse && TVal->getZExtValue() != 1)
23270       return SDValue();
23271     if (!FValIsFalse && TVal->getZExtValue() != 0)
23272       return SDValue();
23273     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23274     if (needOppositeCond)
23275       CC = X86::GetOppositeBranchCondition(CC);
23276     return SetCC.getOperand(3);
23277   }
23278   }
23279
23280   return SDValue();
23281 }
23282
23283 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23284 /// Match:
23285 ///   (X86or (X86setcc) (X86setcc))
23286 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
23287 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23288                                            X86::CondCode &CC1, SDValue &Flags,
23289                                            bool &isAnd) {
23290   if (Cond->getOpcode() == X86ISD::CMP) {
23291     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23292     if (!CondOp1C || !CondOp1C->isNullValue())
23293       return false;
23294
23295     Cond = Cond->getOperand(0);
23296   }
23297
23298   isAnd = false;
23299
23300   SDValue SetCC0, SetCC1;
23301   switch (Cond->getOpcode()) {
23302   default: return false;
23303   case ISD::AND:
23304   case X86ISD::AND:
23305     isAnd = true;
23306     // fallthru
23307   case ISD::OR:
23308   case X86ISD::OR:
23309     SetCC0 = Cond->getOperand(0);
23310     SetCC1 = Cond->getOperand(1);
23311     break;
23312   };
23313
23314   // Make sure we have SETCC nodes, using the same flags value.
23315   if (SetCC0.getOpcode() != X86ISD::SETCC ||
23316       SetCC1.getOpcode() != X86ISD::SETCC ||
23317       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23318     return false;
23319
23320   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23321   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23322   Flags = SetCC0->getOperand(1);
23323   return true;
23324 }
23325
23326 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23327 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23328                                   TargetLowering::DAGCombinerInfo &DCI,
23329                                   const X86Subtarget *Subtarget) {
23330   SDLoc DL(N);
23331
23332   // If the flag operand isn't dead, don't touch this CMOV.
23333   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23334     return SDValue();
23335
23336   SDValue FalseOp = N->getOperand(0);
23337   SDValue TrueOp = N->getOperand(1);
23338   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23339   SDValue Cond = N->getOperand(3);
23340
23341   if (CC == X86::COND_E || CC == X86::COND_NE) {
23342     switch (Cond.getOpcode()) {
23343     default: break;
23344     case X86ISD::BSR:
23345     case X86ISD::BSF:
23346       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23347       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23348         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23349     }
23350   }
23351
23352   SDValue Flags;
23353
23354   Flags = checkBoolTestSetCCCombine(Cond, CC);
23355   if (Flags.getNode() &&
23356       // Extra check as FCMOV only supports a subset of X86 cond.
23357       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23358     SDValue Ops[] = { FalseOp, TrueOp,
23359                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23360     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23361   }
23362
23363   // If this is a select between two integer constants, try to do some
23364   // optimizations.  Note that the operands are ordered the opposite of SELECT
23365   // operands.
23366   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23367     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23368       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23369       // larger than FalseC (the false value).
23370       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23371         CC = X86::GetOppositeBranchCondition(CC);
23372         std::swap(TrueC, FalseC);
23373         std::swap(TrueOp, FalseOp);
23374       }
23375
23376       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23377       // This is efficient for any integer data type (including i8/i16) and
23378       // shift amount.
23379       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23380         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23381                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23382
23383         // Zero extend the condition if needed.
23384         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23385
23386         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23387         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23388                            DAG.getConstant(ShAmt, DL, MVT::i8));
23389         if (N->getNumValues() == 2)  // Dead flag value?
23390           return DCI.CombineTo(N, Cond, SDValue());
23391         return Cond;
23392       }
23393
23394       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23395       // for any integer data type, including i8/i16.
23396       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23397         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23398                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23399
23400         // Zero extend the condition if needed.
23401         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23402                            FalseC->getValueType(0), Cond);
23403         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23404                            SDValue(FalseC, 0));
23405
23406         if (N->getNumValues() == 2)  // Dead flag value?
23407           return DCI.CombineTo(N, Cond, SDValue());
23408         return Cond;
23409       }
23410
23411       // Optimize cases that will turn into an LEA instruction.  This requires
23412       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23413       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23414         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23415         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23416
23417         bool isFastMultiplier = false;
23418         if (Diff < 10) {
23419           switch ((unsigned char)Diff) {
23420           default: break;
23421           case 1:  // result = add base, cond
23422           case 2:  // result = lea base(    , cond*2)
23423           case 3:  // result = lea base(cond, cond*2)
23424           case 4:  // result = lea base(    , cond*4)
23425           case 5:  // result = lea base(cond, cond*4)
23426           case 8:  // result = lea base(    , cond*8)
23427           case 9:  // result = lea base(cond, cond*8)
23428             isFastMultiplier = true;
23429             break;
23430           }
23431         }
23432
23433         if (isFastMultiplier) {
23434           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23435           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23436                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23437           // Zero extend the condition if needed.
23438           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23439                              Cond);
23440           // Scale the condition by the difference.
23441           if (Diff != 1)
23442             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23443                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23444
23445           // Add the base if non-zero.
23446           if (FalseC->getAPIntValue() != 0)
23447             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23448                                SDValue(FalseC, 0));
23449           if (N->getNumValues() == 2)  // Dead flag value?
23450             return DCI.CombineTo(N, Cond, SDValue());
23451           return Cond;
23452         }
23453       }
23454     }
23455   }
23456
23457   // Handle these cases:
23458   //   (select (x != c), e, c) -> select (x != c), e, x),
23459   //   (select (x == c), c, e) -> select (x == c), x, e)
23460   // where the c is an integer constant, and the "select" is the combination
23461   // of CMOV and CMP.
23462   //
23463   // The rationale for this change is that the conditional-move from a constant
23464   // needs two instructions, however, conditional-move from a register needs
23465   // only one instruction.
23466   //
23467   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23468   //  some instruction-combining opportunities. This opt needs to be
23469   //  postponed as late as possible.
23470   //
23471   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23472     // the DCI.xxxx conditions are provided to postpone the optimization as
23473     // late as possible.
23474
23475     ConstantSDNode *CmpAgainst = nullptr;
23476     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23477         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23478         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23479
23480       if (CC == X86::COND_NE &&
23481           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23482         CC = X86::GetOppositeBranchCondition(CC);
23483         std::swap(TrueOp, FalseOp);
23484       }
23485
23486       if (CC == X86::COND_E &&
23487           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23488         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23489                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23490         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23491       }
23492     }
23493   }
23494
23495   // Fold and/or of setcc's to double CMOV:
23496   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23497   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23498   //
23499   // This combine lets us generate:
23500   //   cmovcc1 (jcc1 if we don't have CMOV)
23501   //   cmovcc2 (same)
23502   // instead of:
23503   //   setcc1
23504   //   setcc2
23505   //   and/or
23506   //   cmovne (jne if we don't have CMOV)
23507   // When we can't use the CMOV instruction, it might increase branch
23508   // mispredicts.
23509   // When we can use CMOV, or when there is no mispredict, this improves
23510   // throughput and reduces register pressure.
23511   //
23512   if (CC == X86::COND_NE) {
23513     SDValue Flags;
23514     X86::CondCode CC0, CC1;
23515     bool isAndSetCC;
23516     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23517       if (isAndSetCC) {
23518         std::swap(FalseOp, TrueOp);
23519         CC0 = X86::GetOppositeBranchCondition(CC0);
23520         CC1 = X86::GetOppositeBranchCondition(CC1);
23521       }
23522
23523       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23524         Flags};
23525       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23526       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23527       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23528       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23529       return CMOV;
23530     }
23531   }
23532
23533   return SDValue();
23534 }
23535
23536 /// PerformMulCombine - Optimize a single multiply with constant into two
23537 /// in order to implement it with two cheaper instructions, e.g.
23538 /// LEA + SHL, LEA + LEA.
23539 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23540                                  TargetLowering::DAGCombinerInfo &DCI) {
23541   // An imul is usually smaller than the alternative sequence.
23542   if (DAG.getMachineFunction().getFunction()->optForMinSize())
23543     return SDValue();
23544
23545   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23546     return SDValue();
23547
23548   EVT VT = N->getValueType(0);
23549   if (VT != MVT::i64 && VT != MVT::i32)
23550     return SDValue();
23551
23552   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23553   if (!C)
23554     return SDValue();
23555   uint64_t MulAmt = C->getZExtValue();
23556   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23557     return SDValue();
23558
23559   uint64_t MulAmt1 = 0;
23560   uint64_t MulAmt2 = 0;
23561   if ((MulAmt % 9) == 0) {
23562     MulAmt1 = 9;
23563     MulAmt2 = MulAmt / 9;
23564   } else if ((MulAmt % 5) == 0) {
23565     MulAmt1 = 5;
23566     MulAmt2 = MulAmt / 5;
23567   } else if ((MulAmt % 3) == 0) {
23568     MulAmt1 = 3;
23569     MulAmt2 = MulAmt / 3;
23570   }
23571   if (MulAmt2 &&
23572       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23573     SDLoc DL(N);
23574
23575     if (isPowerOf2_64(MulAmt2) &&
23576         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23577       // If second multiplifer is pow2, issue it first. We want the multiply by
23578       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23579       // is an add.
23580       std::swap(MulAmt1, MulAmt2);
23581
23582     SDValue NewMul;
23583     if (isPowerOf2_64(MulAmt1))
23584       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23585                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23586     else
23587       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23588                            DAG.getConstant(MulAmt1, DL, VT));
23589
23590     if (isPowerOf2_64(MulAmt2))
23591       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23592                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23593     else
23594       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23595                            DAG.getConstant(MulAmt2, DL, VT));
23596
23597     // Do not add new nodes to DAG combiner worklist.
23598     DCI.CombineTo(N, NewMul, false);
23599   }
23600   return SDValue();
23601 }
23602
23603 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23604   SDValue N0 = N->getOperand(0);
23605   SDValue N1 = N->getOperand(1);
23606   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23607   EVT VT = N0.getValueType();
23608
23609   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23610   // since the result of setcc_c is all zero's or all ones.
23611   if (VT.isInteger() && !VT.isVector() &&
23612       N1C && N0.getOpcode() == ISD::AND &&
23613       N0.getOperand(1).getOpcode() == ISD::Constant) {
23614     SDValue N00 = N0.getOperand(0);
23615     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23616     APInt ShAmt = N1C->getAPIntValue();
23617     Mask = Mask.shl(ShAmt);
23618     bool MaskOK = false;
23619     // We can handle cases concerning bit-widening nodes containing setcc_c if
23620     // we carefully interrogate the mask to make sure we are semantics
23621     // preserving.
23622     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
23623     // of the underlying setcc_c operation if the setcc_c was zero extended.
23624     // Consider the following example:
23625     //   zext(setcc_c)                 -> i32 0x0000FFFF
23626     //   c1                            -> i32 0x0000FFFF
23627     //   c2                            -> i32 0x00000001
23628     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
23629     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
23630     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23631       MaskOK = true;
23632     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
23633                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23634       MaskOK = true;
23635     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
23636                 N00.getOpcode() == ISD::ANY_EXTEND) &&
23637                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23638       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
23639     }
23640     if (MaskOK && Mask != 0) {
23641       SDLoc DL(N);
23642       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
23643     }
23644   }
23645
23646   // Hardware support for vector shifts is sparse which makes us scalarize the
23647   // vector operations in many cases. Also, on sandybridge ADD is faster than
23648   // shl.
23649   // (shl V, 1) -> add V,V
23650   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23651     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23652       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23653       // We shift all of the values by one. In many cases we do not have
23654       // hardware support for this operation. This is better expressed as an ADD
23655       // of two values.
23656       if (N1SplatC->getAPIntValue() == 1)
23657         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23658     }
23659
23660   return SDValue();
23661 }
23662
23663 /// \brief Returns a vector of 0s if the node in input is a vector logical
23664 /// shift by a constant amount which is known to be bigger than or equal
23665 /// to the vector element size in bits.
23666 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23667                                       const X86Subtarget *Subtarget) {
23668   EVT VT = N->getValueType(0);
23669
23670   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23671       (!Subtarget->hasInt256() ||
23672        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23673     return SDValue();
23674
23675   SDValue Amt = N->getOperand(1);
23676   SDLoc DL(N);
23677   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23678     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23679       APInt ShiftAmt = AmtSplat->getAPIntValue();
23680       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23681
23682       // SSE2/AVX2 logical shifts always return a vector of 0s
23683       // if the shift amount is bigger than or equal to
23684       // the element size. The constant shift amount will be
23685       // encoded as a 8-bit immediate.
23686       if (ShiftAmt.trunc(8).uge(MaxAmount))
23687         return getZeroVector(VT, Subtarget, DAG, DL);
23688     }
23689
23690   return SDValue();
23691 }
23692
23693 /// PerformShiftCombine - Combine shifts.
23694 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23695                                    TargetLowering::DAGCombinerInfo &DCI,
23696                                    const X86Subtarget *Subtarget) {
23697   if (N->getOpcode() == ISD::SHL)
23698     if (SDValue V = PerformSHLCombine(N, DAG))
23699       return V;
23700
23701   // Try to fold this logical shift into a zero vector.
23702   if (N->getOpcode() != ISD::SRA)
23703     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23704       return V;
23705
23706   return SDValue();
23707 }
23708
23709 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23710 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23711 // and friends.  Likewise for OR -> CMPNEQSS.
23712 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23713                             TargetLowering::DAGCombinerInfo &DCI,
23714                             const X86Subtarget *Subtarget) {
23715   unsigned opcode;
23716
23717   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23718   // we're requiring SSE2 for both.
23719   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23720     SDValue N0 = N->getOperand(0);
23721     SDValue N1 = N->getOperand(1);
23722     SDValue CMP0 = N0->getOperand(1);
23723     SDValue CMP1 = N1->getOperand(1);
23724     SDLoc DL(N);
23725
23726     // The SETCCs should both refer to the same CMP.
23727     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23728       return SDValue();
23729
23730     SDValue CMP00 = CMP0->getOperand(0);
23731     SDValue CMP01 = CMP0->getOperand(1);
23732     EVT     VT    = CMP00.getValueType();
23733
23734     if (VT == MVT::f32 || VT == MVT::f64) {
23735       bool ExpectingFlags = false;
23736       // Check for any users that want flags:
23737       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23738            !ExpectingFlags && UI != UE; ++UI)
23739         switch (UI->getOpcode()) {
23740         default:
23741         case ISD::BR_CC:
23742         case ISD::BRCOND:
23743         case ISD::SELECT:
23744           ExpectingFlags = true;
23745           break;
23746         case ISD::CopyToReg:
23747         case ISD::SIGN_EXTEND:
23748         case ISD::ZERO_EXTEND:
23749         case ISD::ANY_EXTEND:
23750           break;
23751         }
23752
23753       if (!ExpectingFlags) {
23754         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23755         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23756
23757         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23758           X86::CondCode tmp = cc0;
23759           cc0 = cc1;
23760           cc1 = tmp;
23761         }
23762
23763         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23764             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23765           // FIXME: need symbolic constants for these magic numbers.
23766           // See X86ATTInstPrinter.cpp:printSSECC().
23767           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23768           if (Subtarget->hasAVX512()) {
23769             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23770                                          CMP01,
23771                                          DAG.getConstant(x86cc, DL, MVT::i8));
23772             if (N->getValueType(0) != MVT::i1)
23773               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23774                                  FSetCC);
23775             return FSetCC;
23776           }
23777           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23778                                               CMP00.getValueType(), CMP00, CMP01,
23779                                               DAG.getConstant(x86cc, DL,
23780                                                               MVT::i8));
23781
23782           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23783           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23784
23785           if (is64BitFP && !Subtarget->is64Bit()) {
23786             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23787             // 64-bit integer, since that's not a legal type. Since
23788             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23789             // bits, but can do this little dance to extract the lowest 32 bits
23790             // and work with those going forward.
23791             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23792                                            OnesOrZeroesF);
23793             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23794             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23795                                         Vector32, DAG.getIntPtrConstant(0, DL));
23796             IntVT = MVT::i32;
23797           }
23798
23799           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23800           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23801                                       DAG.getConstant(1, DL, IntVT));
23802           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23803                                               ANDed);
23804           return OneBitOfTruth;
23805         }
23806       }
23807     }
23808   }
23809   return SDValue();
23810 }
23811
23812 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23813 /// so it can be folded inside ANDNP.
23814 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23815   EVT VT = N->getValueType(0);
23816
23817   // Match direct AllOnes for 128 and 256-bit vectors
23818   if (ISD::isBuildVectorAllOnes(N))
23819     return true;
23820
23821   // Look through a bit convert.
23822   if (N->getOpcode() == ISD::BITCAST)
23823     N = N->getOperand(0).getNode();
23824
23825   // Sometimes the operand may come from a insert_subvector building a 256-bit
23826   // allones vector
23827   if (VT.is256BitVector() &&
23828       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23829     SDValue V1 = N->getOperand(0);
23830     SDValue V2 = N->getOperand(1);
23831
23832     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23833         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23834         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23835         ISD::isBuildVectorAllOnes(V2.getNode()))
23836       return true;
23837   }
23838
23839   return false;
23840 }
23841
23842 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23843 // register. In most cases we actually compare or select YMM-sized registers
23844 // and mixing the two types creates horrible code. This method optimizes
23845 // some of the transition sequences.
23846 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23847                                  TargetLowering::DAGCombinerInfo &DCI,
23848                                  const X86Subtarget *Subtarget) {
23849   EVT VT = N->getValueType(0);
23850   if (!VT.is256BitVector())
23851     return SDValue();
23852
23853   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23854           N->getOpcode() == ISD::ZERO_EXTEND ||
23855           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23856
23857   SDValue Narrow = N->getOperand(0);
23858   EVT NarrowVT = Narrow->getValueType(0);
23859   if (!NarrowVT.is128BitVector())
23860     return SDValue();
23861
23862   if (Narrow->getOpcode() != ISD::XOR &&
23863       Narrow->getOpcode() != ISD::AND &&
23864       Narrow->getOpcode() != ISD::OR)
23865     return SDValue();
23866
23867   SDValue N0  = Narrow->getOperand(0);
23868   SDValue N1  = Narrow->getOperand(1);
23869   SDLoc DL(Narrow);
23870
23871   // The Left side has to be a trunc.
23872   if (N0.getOpcode() != ISD::TRUNCATE)
23873     return SDValue();
23874
23875   // The type of the truncated inputs.
23876   EVT WideVT = N0->getOperand(0)->getValueType(0);
23877   if (WideVT != VT)
23878     return SDValue();
23879
23880   // The right side has to be a 'trunc' or a constant vector.
23881   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23882   ConstantSDNode *RHSConstSplat = nullptr;
23883   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23884     RHSConstSplat = RHSBV->getConstantSplatNode();
23885   if (!RHSTrunc && !RHSConstSplat)
23886     return SDValue();
23887
23888   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23889
23890   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23891     return SDValue();
23892
23893   // Set N0 and N1 to hold the inputs to the new wide operation.
23894   N0 = N0->getOperand(0);
23895   if (RHSConstSplat) {
23896     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23897                      SDValue(RHSConstSplat, 0));
23898     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23899     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23900   } else if (RHSTrunc) {
23901     N1 = N1->getOperand(0);
23902   }
23903
23904   // Generate the wide operation.
23905   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23906   unsigned Opcode = N->getOpcode();
23907   switch (Opcode) {
23908   case ISD::ANY_EXTEND:
23909     return Op;
23910   case ISD::ZERO_EXTEND: {
23911     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23912     APInt Mask = APInt::getAllOnesValue(InBits);
23913     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23914     return DAG.getNode(ISD::AND, DL, VT,
23915                        Op, DAG.getConstant(Mask, DL, VT));
23916   }
23917   case ISD::SIGN_EXTEND:
23918     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23919                        Op, DAG.getValueType(NarrowVT));
23920   default:
23921     llvm_unreachable("Unexpected opcode");
23922   }
23923 }
23924
23925 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23926                                  TargetLowering::DAGCombinerInfo &DCI,
23927                                  const X86Subtarget *Subtarget) {
23928   SDValue N0 = N->getOperand(0);
23929   SDValue N1 = N->getOperand(1);
23930   SDLoc DL(N);
23931
23932   // A vector zext_in_reg may be represented as a shuffle,
23933   // feeding into a bitcast (this represents anyext) feeding into
23934   // an and with a mask.
23935   // We'd like to try to combine that into a shuffle with zero
23936   // plus a bitcast, removing the and.
23937   if (N0.getOpcode() != ISD::BITCAST ||
23938       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23939     return SDValue();
23940
23941   // The other side of the AND should be a splat of 2^C, where C
23942   // is the number of bits in the source type.
23943   if (N1.getOpcode() == ISD::BITCAST)
23944     N1 = N1.getOperand(0);
23945   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23946     return SDValue();
23947   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23948
23949   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23950   EVT SrcType = Shuffle->getValueType(0);
23951
23952   // We expect a single-source shuffle
23953   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23954     return SDValue();
23955
23956   unsigned SrcSize = SrcType.getScalarSizeInBits();
23957
23958   APInt SplatValue, SplatUndef;
23959   unsigned SplatBitSize;
23960   bool HasAnyUndefs;
23961   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23962                                 SplatBitSize, HasAnyUndefs))
23963     return SDValue();
23964
23965   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23966   // Make sure the splat matches the mask we expect
23967   if (SplatBitSize > ResSize ||
23968       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23969     return SDValue();
23970
23971   // Make sure the input and output size make sense
23972   if (SrcSize >= ResSize || ResSize % SrcSize)
23973     return SDValue();
23974
23975   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23976   // The number of u's between each two values depends on the ratio between
23977   // the source and dest type.
23978   unsigned ZextRatio = ResSize / SrcSize;
23979   bool IsZext = true;
23980   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23981     if (i % ZextRatio) {
23982       if (Shuffle->getMaskElt(i) > 0) {
23983         // Expected undef
23984         IsZext = false;
23985         break;
23986       }
23987     } else {
23988       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23989         // Expected element number
23990         IsZext = false;
23991         break;
23992       }
23993     }
23994   }
23995
23996   if (!IsZext)
23997     return SDValue();
23998
23999   // Ok, perform the transformation - replace the shuffle with
24000   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24001   // (instead of undef) where the k elements come from the zero vector.
24002   SmallVector<int, 8> Mask;
24003   unsigned NumElems = SrcType.getVectorNumElements();
24004   for (unsigned i = 0; i < NumElems; ++i)
24005     if (i % ZextRatio)
24006       Mask.push_back(NumElems);
24007     else
24008       Mask.push_back(i / ZextRatio);
24009
24010   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24011     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24012   return DAG.getBitcast(N0.getValueType(), NewShuffle);
24013 }
24014
24015 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24016                                  TargetLowering::DAGCombinerInfo &DCI,
24017                                  const X86Subtarget *Subtarget) {
24018   if (DCI.isBeforeLegalizeOps())
24019     return SDValue();
24020
24021   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24022     return Zext;
24023
24024   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24025     return R;
24026
24027   EVT VT = N->getValueType(0);
24028   SDValue N0 = N->getOperand(0);
24029   SDValue N1 = N->getOperand(1);
24030   SDLoc DL(N);
24031
24032   // Create BEXTR instructions
24033   // BEXTR is ((X >> imm) & (2**size-1))
24034   if (VT == MVT::i32 || VT == MVT::i64) {
24035     // Check for BEXTR.
24036     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24037         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24038       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24039       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24040       if (MaskNode && ShiftNode) {
24041         uint64_t Mask = MaskNode->getZExtValue();
24042         uint64_t Shift = ShiftNode->getZExtValue();
24043         if (isMask_64(Mask)) {
24044           uint64_t MaskSize = countPopulation(Mask);
24045           if (Shift + MaskSize <= VT.getSizeInBits())
24046             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24047                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24048                                                VT));
24049         }
24050       }
24051     } // BEXTR
24052
24053     return SDValue();
24054   }
24055
24056   // Want to form ANDNP nodes:
24057   // 1) In the hopes of then easily combining them with OR and AND nodes
24058   //    to form PBLEND/PSIGN.
24059   // 2) To match ANDN packed intrinsics
24060   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24061     return SDValue();
24062
24063   // Check LHS for vnot
24064   if (N0.getOpcode() == ISD::XOR &&
24065       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24066       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24067     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24068
24069   // Check RHS for vnot
24070   if (N1.getOpcode() == ISD::XOR &&
24071       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24072       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24073     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24074
24075   return SDValue();
24076 }
24077
24078 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24079                                 TargetLowering::DAGCombinerInfo &DCI,
24080                                 const X86Subtarget *Subtarget) {
24081   if (DCI.isBeforeLegalizeOps())
24082     return SDValue();
24083
24084   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24085     return R;
24086
24087   SDValue N0 = N->getOperand(0);
24088   SDValue N1 = N->getOperand(1);
24089   EVT VT = N->getValueType(0);
24090
24091   // look for psign/blend
24092   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24093     if (!Subtarget->hasSSSE3() ||
24094         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24095       return SDValue();
24096
24097     // Canonicalize pandn to RHS
24098     if (N0.getOpcode() == X86ISD::ANDNP)
24099       std::swap(N0, N1);
24100     // or (and (m, y), (pandn m, x))
24101     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24102       SDValue Mask = N1.getOperand(0);
24103       SDValue X    = N1.getOperand(1);
24104       SDValue Y;
24105       if (N0.getOperand(0) == Mask)
24106         Y = N0.getOperand(1);
24107       if (N0.getOperand(1) == Mask)
24108         Y = N0.getOperand(0);
24109
24110       // Check to see if the mask appeared in both the AND and ANDNP and
24111       if (!Y.getNode())
24112         return SDValue();
24113
24114       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24115       // Look through mask bitcast.
24116       if (Mask.getOpcode() == ISD::BITCAST)
24117         Mask = Mask.getOperand(0);
24118       if (X.getOpcode() == ISD::BITCAST)
24119         X = X.getOperand(0);
24120       if (Y.getOpcode() == ISD::BITCAST)
24121         Y = Y.getOperand(0);
24122
24123       EVT MaskVT = Mask.getValueType();
24124
24125       // Validate that the Mask operand is a vector sra node.
24126       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24127       // there is no psrai.b
24128       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24129       unsigned SraAmt = ~0;
24130       if (Mask.getOpcode() == ISD::SRA) {
24131         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24132           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24133             SraAmt = AmtConst->getZExtValue();
24134       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24135         SDValue SraC = Mask.getOperand(1);
24136         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24137       }
24138       if ((SraAmt + 1) != EltBits)
24139         return SDValue();
24140
24141       SDLoc DL(N);
24142
24143       // Now we know we at least have a plendvb with the mask val.  See if
24144       // we can form a psignb/w/d.
24145       // psign = x.type == y.type == mask.type && y = sub(0, x);
24146       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24147           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24148           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24149         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24150                "Unsupported VT for PSIGN");
24151         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24152         return DAG.getBitcast(VT, Mask);
24153       }
24154       // PBLENDVB only available on SSE 4.1
24155       if (!Subtarget->hasSSE41())
24156         return SDValue();
24157
24158       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24159
24160       X = DAG.getBitcast(BlendVT, X);
24161       Y = DAG.getBitcast(BlendVT, Y);
24162       Mask = DAG.getBitcast(BlendVT, Mask);
24163       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24164       return DAG.getBitcast(VT, Mask);
24165     }
24166   }
24167
24168   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24169     return SDValue();
24170
24171   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24172   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24173
24174   // SHLD/SHRD instructions have lower register pressure, but on some
24175   // platforms they have higher latency than the equivalent
24176   // series of shifts/or that would otherwise be generated.
24177   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24178   // have higher latencies and we are not optimizing for size.
24179   if (!OptForSize && Subtarget->isSHLDSlow())
24180     return SDValue();
24181
24182   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24183     std::swap(N0, N1);
24184   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24185     return SDValue();
24186   if (!N0.hasOneUse() || !N1.hasOneUse())
24187     return SDValue();
24188
24189   SDValue ShAmt0 = N0.getOperand(1);
24190   if (ShAmt0.getValueType() != MVT::i8)
24191     return SDValue();
24192   SDValue ShAmt1 = N1.getOperand(1);
24193   if (ShAmt1.getValueType() != MVT::i8)
24194     return SDValue();
24195   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24196     ShAmt0 = ShAmt0.getOperand(0);
24197   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24198     ShAmt1 = ShAmt1.getOperand(0);
24199
24200   SDLoc DL(N);
24201   unsigned Opc = X86ISD::SHLD;
24202   SDValue Op0 = N0.getOperand(0);
24203   SDValue Op1 = N1.getOperand(0);
24204   if (ShAmt0.getOpcode() == ISD::SUB) {
24205     Opc = X86ISD::SHRD;
24206     std::swap(Op0, Op1);
24207     std::swap(ShAmt0, ShAmt1);
24208   }
24209
24210   unsigned Bits = VT.getSizeInBits();
24211   if (ShAmt1.getOpcode() == ISD::SUB) {
24212     SDValue Sum = ShAmt1.getOperand(0);
24213     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24214       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24215       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24216         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24217       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24218         return DAG.getNode(Opc, DL, VT,
24219                            Op0, Op1,
24220                            DAG.getNode(ISD::TRUNCATE, DL,
24221                                        MVT::i8, ShAmt0));
24222     }
24223   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24224     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24225     if (ShAmt0C &&
24226         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24227       return DAG.getNode(Opc, DL, VT,
24228                          N0.getOperand(0), N1.getOperand(0),
24229                          DAG.getNode(ISD::TRUNCATE, DL,
24230                                        MVT::i8, ShAmt0));
24231   }
24232
24233   return SDValue();
24234 }
24235
24236 // Generate NEG and CMOV for integer abs.
24237 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24238   EVT VT = N->getValueType(0);
24239
24240   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24241   // 8-bit integer abs to NEG and CMOV.
24242   if (VT.isInteger() && VT.getSizeInBits() == 8)
24243     return SDValue();
24244
24245   SDValue N0 = N->getOperand(0);
24246   SDValue N1 = N->getOperand(1);
24247   SDLoc DL(N);
24248
24249   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24250   // and change it to SUB and CMOV.
24251   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24252       N0.getOpcode() == ISD::ADD &&
24253       N0.getOperand(1) == N1 &&
24254       N1.getOpcode() == ISD::SRA &&
24255       N1.getOperand(0) == N0.getOperand(0))
24256     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24257       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24258         // Generate SUB & CMOV.
24259         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24260                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24261
24262         SDValue Ops[] = { N0.getOperand(0), Neg,
24263                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24264                           SDValue(Neg.getNode(), 1) };
24265         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24266       }
24267   return SDValue();
24268 }
24269
24270 // Try to turn tests against the signbit in the form of:
24271 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24272 // into:
24273 //   SETGT(X, -1)
24274 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24275   // This is only worth doing if the output type is i8.
24276   if (N->getValueType(0) != MVT::i8)
24277     return SDValue();
24278
24279   SDValue N0 = N->getOperand(0);
24280   SDValue N1 = N->getOperand(1);
24281
24282   // We should be performing an xor against a truncated shift.
24283   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24284     return SDValue();
24285
24286   // Make sure we are performing an xor against one.
24287   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24288     return SDValue();
24289
24290   // SetCC on x86 zero extends so only act on this if it's a logical shift.
24291   SDValue Shift = N0.getOperand(0);
24292   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24293     return SDValue();
24294
24295   // Make sure we are truncating from one of i16, i32 or i64.
24296   EVT ShiftTy = Shift.getValueType();
24297   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24298     return SDValue();
24299
24300   // Make sure the shift amount extracts the sign bit.
24301   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24302       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24303     return SDValue();
24304
24305   // Create a greater-than comparison against -1.
24306   // N.B. Using SETGE against 0 works but we want a canonical looking
24307   // comparison, using SETGT matches up with what TranslateX86CC.
24308   SDLoc DL(N);
24309   SDValue ShiftOp = Shift.getOperand(0);
24310   EVT ShiftOpTy = ShiftOp.getValueType();
24311   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24312                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24313   return Cond;
24314 }
24315
24316 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24317                                  TargetLowering::DAGCombinerInfo &DCI,
24318                                  const X86Subtarget *Subtarget) {
24319   if (DCI.isBeforeLegalizeOps())
24320     return SDValue();
24321
24322   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24323     return RV;
24324
24325   if (Subtarget->hasCMov())
24326     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24327       return RV;
24328
24329   return SDValue();
24330 }
24331
24332 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24333 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24334                                   TargetLowering::DAGCombinerInfo &DCI,
24335                                   const X86Subtarget *Subtarget) {
24336   LoadSDNode *Ld = cast<LoadSDNode>(N);
24337   EVT RegVT = Ld->getValueType(0);
24338   EVT MemVT = Ld->getMemoryVT();
24339   SDLoc dl(Ld);
24340   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24341
24342   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24343   // into two 16-byte operations.
24344   ISD::LoadExtType Ext = Ld->getExtensionType();
24345   bool Fast;
24346   unsigned AddressSpace = Ld->getAddressSpace();
24347   unsigned Alignment = Ld->getAlignment();
24348   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24349       Ext == ISD::NON_EXTLOAD &&
24350       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24351                              AddressSpace, Alignment, &Fast) && !Fast) {
24352     unsigned NumElems = RegVT.getVectorNumElements();
24353     if (NumElems < 2)
24354       return SDValue();
24355
24356     SDValue Ptr = Ld->getBasePtr();
24357     SDValue Increment =
24358         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24359
24360     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24361                                   NumElems/2);
24362     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24363                                 Ld->getPointerInfo(), Ld->isVolatile(),
24364                                 Ld->isNonTemporal(), Ld->isInvariant(),
24365                                 Alignment);
24366     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24367     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24368                                 Ld->getPointerInfo(), Ld->isVolatile(),
24369                                 Ld->isNonTemporal(), Ld->isInvariant(),
24370                                 std::min(16U, Alignment));
24371     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24372                              Load1.getValue(1),
24373                              Load2.getValue(1));
24374
24375     SDValue NewVec = DAG.getUNDEF(RegVT);
24376     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24377     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24378     return DCI.CombineTo(N, NewVec, TF, true);
24379   }
24380
24381   return SDValue();
24382 }
24383
24384 /// PerformMLOADCombine - Resolve extending loads
24385 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24386                                    TargetLowering::DAGCombinerInfo &DCI,
24387                                    const X86Subtarget *Subtarget) {
24388   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24389   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24390     return SDValue();
24391
24392   EVT VT = Mld->getValueType(0);
24393   unsigned NumElems = VT.getVectorNumElements();
24394   EVT LdVT = Mld->getMemoryVT();
24395   SDLoc dl(Mld);
24396
24397   assert(LdVT != VT && "Cannot extend to the same type");
24398   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24399   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24400   // From, To sizes and ElemCount must be pow of two
24401   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24402     "Unexpected size for extending masked load");
24403
24404   unsigned SizeRatio  = ToSz / FromSz;
24405   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24406
24407   // Create a type on which we perform the shuffle
24408   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24409           LdVT.getScalarType(), NumElems*SizeRatio);
24410   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24411
24412   // Convert Src0 value
24413   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24414   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24415     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24416     for (unsigned i = 0; i != NumElems; ++i)
24417       ShuffleVec[i] = i * SizeRatio;
24418
24419     // Can't shuffle using an illegal type.
24420     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24421             && "WideVecVT should be legal");
24422     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24423                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24424   }
24425   // Prepare the new mask
24426   SDValue NewMask;
24427   SDValue Mask = Mld->getMask();
24428   if (Mask.getValueType() == VT) {
24429     // Mask and original value have the same type
24430     NewMask = DAG.getBitcast(WideVecVT, Mask);
24431     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24432     for (unsigned i = 0; i != NumElems; ++i)
24433       ShuffleVec[i] = i * SizeRatio;
24434     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24435       ShuffleVec[i] = NumElems*SizeRatio;
24436     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24437                                    DAG.getConstant(0, dl, WideVecVT),
24438                                    &ShuffleVec[0]);
24439   }
24440   else {
24441     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24442     unsigned WidenNumElts = NumElems*SizeRatio;
24443     unsigned MaskNumElts = VT.getVectorNumElements();
24444     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24445                                      WidenNumElts);
24446
24447     unsigned NumConcat = WidenNumElts / MaskNumElts;
24448     SmallVector<SDValue, 16> Ops(NumConcat);
24449     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24450     Ops[0] = Mask;
24451     for (unsigned i = 1; i != NumConcat; ++i)
24452       Ops[i] = ZeroVal;
24453
24454     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24455   }
24456
24457   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24458                                      Mld->getBasePtr(), NewMask, WideSrc0,
24459                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24460                                      ISD::NON_EXTLOAD);
24461   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24462   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24463
24464 }
24465 /// PerformMSTORECombine - Resolve truncating stores
24466 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24467                                     const X86Subtarget *Subtarget) {
24468   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24469   if (!Mst->isTruncatingStore())
24470     return SDValue();
24471
24472   EVT VT = Mst->getValue().getValueType();
24473   unsigned NumElems = VT.getVectorNumElements();
24474   EVT StVT = Mst->getMemoryVT();
24475   SDLoc dl(Mst);
24476
24477   assert(StVT != VT && "Cannot truncate to the same type");
24478   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24479   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24480
24481   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24482
24483   // The truncating store is legal in some cases. For example
24484   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24485   // are designated for truncate store.
24486   // In this case we don't need any further transformations.
24487   if (TLI.isTruncStoreLegal(VT, StVT))
24488     return SDValue();
24489
24490   // From, To sizes and ElemCount must be pow of two
24491   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24492     "Unexpected size for truncating masked store");
24493   // We are going to use the original vector elt for storing.
24494   // Accumulated smaller vector elements must be a multiple of the store size.
24495   assert (((NumElems * FromSz) % ToSz) == 0 &&
24496           "Unexpected ratio for truncating masked store");
24497
24498   unsigned SizeRatio  = FromSz / ToSz;
24499   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24500
24501   // Create a type on which we perform the shuffle
24502   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24503           StVT.getScalarType(), NumElems*SizeRatio);
24504
24505   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24506
24507   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24508   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24509   for (unsigned i = 0; i != NumElems; ++i)
24510     ShuffleVec[i] = i * SizeRatio;
24511
24512   // Can't shuffle using an illegal type.
24513   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24514           && "WideVecVT should be legal");
24515
24516   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24517                                         DAG.getUNDEF(WideVecVT),
24518                                         &ShuffleVec[0]);
24519
24520   SDValue NewMask;
24521   SDValue Mask = Mst->getMask();
24522   if (Mask.getValueType() == VT) {
24523     // Mask and original value have the same type
24524     NewMask = DAG.getBitcast(WideVecVT, Mask);
24525     for (unsigned i = 0; i != NumElems; ++i)
24526       ShuffleVec[i] = i * SizeRatio;
24527     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24528       ShuffleVec[i] = NumElems*SizeRatio;
24529     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24530                                    DAG.getConstant(0, dl, WideVecVT),
24531                                    &ShuffleVec[0]);
24532   }
24533   else {
24534     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24535     unsigned WidenNumElts = NumElems*SizeRatio;
24536     unsigned MaskNumElts = VT.getVectorNumElements();
24537     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24538                                      WidenNumElts);
24539
24540     unsigned NumConcat = WidenNumElts / MaskNumElts;
24541     SmallVector<SDValue, 16> Ops(NumConcat);
24542     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24543     Ops[0] = Mask;
24544     for (unsigned i = 1; i != NumConcat; ++i)
24545       Ops[i] = ZeroVal;
24546
24547     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24548   }
24549
24550   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24551                             NewMask, StVT, Mst->getMemOperand(), false);
24552 }
24553 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24554 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24555                                    const X86Subtarget *Subtarget) {
24556   StoreSDNode *St = cast<StoreSDNode>(N);
24557   EVT VT = St->getValue().getValueType();
24558   EVT StVT = St->getMemoryVT();
24559   SDLoc dl(St);
24560   SDValue StoredVal = St->getOperand(1);
24561   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24562
24563   // If we are saving a concatenation of two XMM registers and 32-byte stores
24564   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24565   bool Fast;
24566   unsigned AddressSpace = St->getAddressSpace();
24567   unsigned Alignment = St->getAlignment();
24568   if (VT.is256BitVector() && StVT == VT &&
24569       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24570                              AddressSpace, Alignment, &Fast) && !Fast) {
24571     unsigned NumElems = VT.getVectorNumElements();
24572     if (NumElems < 2)
24573       return SDValue();
24574
24575     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24576     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24577
24578     SDValue Stride =
24579         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24580     SDValue Ptr0 = St->getBasePtr();
24581     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24582
24583     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24584                                 St->getPointerInfo(), St->isVolatile(),
24585                                 St->isNonTemporal(), Alignment);
24586     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24587                                 St->getPointerInfo(), St->isVolatile(),
24588                                 St->isNonTemporal(),
24589                                 std::min(16U, Alignment));
24590     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24591   }
24592
24593   // Optimize trunc store (of multiple scalars) to shuffle and store.
24594   // First, pack all of the elements in one place. Next, store to memory
24595   // in fewer chunks.
24596   if (St->isTruncatingStore() && VT.isVector()) {
24597     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24598     unsigned NumElems = VT.getVectorNumElements();
24599     assert(StVT != VT && "Cannot truncate to the same type");
24600     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24601     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24602
24603     // The truncating store is legal in some cases. For example
24604     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24605     // are designated for truncate store.
24606     // In this case we don't need any further transformations.
24607     if (TLI.isTruncStoreLegal(VT, StVT))
24608       return SDValue();
24609
24610     // From, To sizes and ElemCount must be pow of two
24611     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24612     // We are going to use the original vector elt for storing.
24613     // Accumulated smaller vector elements must be a multiple of the store size.
24614     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24615
24616     unsigned SizeRatio  = FromSz / ToSz;
24617
24618     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24619
24620     // Create a type on which we perform the shuffle
24621     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24622             StVT.getScalarType(), NumElems*SizeRatio);
24623
24624     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24625
24626     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24627     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24628     for (unsigned i = 0; i != NumElems; ++i)
24629       ShuffleVec[i] = i * SizeRatio;
24630
24631     // Can't shuffle using an illegal type.
24632     if (!TLI.isTypeLegal(WideVecVT))
24633       return SDValue();
24634
24635     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24636                                          DAG.getUNDEF(WideVecVT),
24637                                          &ShuffleVec[0]);
24638     // At this point all of the data is stored at the bottom of the
24639     // register. We now need to save it to mem.
24640
24641     // Find the largest store unit
24642     MVT StoreType = MVT::i8;
24643     for (MVT Tp : MVT::integer_valuetypes()) {
24644       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24645         StoreType = Tp;
24646     }
24647
24648     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24649     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24650         (64 <= NumElems * ToSz))
24651       StoreType = MVT::f64;
24652
24653     // Bitcast the original vector into a vector of store-size units
24654     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24655             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24656     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24657     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24658     SmallVector<SDValue, 8> Chains;
24659     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24660                                         TLI.getPointerTy(DAG.getDataLayout()));
24661     SDValue Ptr = St->getBasePtr();
24662
24663     // Perform one or more big stores into memory.
24664     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24665       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24666                                    StoreType, ShuffWide,
24667                                    DAG.getIntPtrConstant(i, dl));
24668       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24669                                 St->getPointerInfo(), St->isVolatile(),
24670                                 St->isNonTemporal(), St->getAlignment());
24671       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24672       Chains.push_back(Ch);
24673     }
24674
24675     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24676   }
24677
24678   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24679   // the FP state in cases where an emms may be missing.
24680   // A preferable solution to the general problem is to figure out the right
24681   // places to insert EMMS.  This qualifies as a quick hack.
24682
24683   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24684   if (VT.getSizeInBits() != 64)
24685     return SDValue();
24686
24687   const Function *F = DAG.getMachineFunction().getFunction();
24688   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24689   bool F64IsLegal =
24690       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24691   if ((VT.isVector() ||
24692        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24693       isa<LoadSDNode>(St->getValue()) &&
24694       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24695       St->getChain().hasOneUse() && !St->isVolatile()) {
24696     SDNode* LdVal = St->getValue().getNode();
24697     LoadSDNode *Ld = nullptr;
24698     int TokenFactorIndex = -1;
24699     SmallVector<SDValue, 8> Ops;
24700     SDNode* ChainVal = St->getChain().getNode();
24701     // Must be a store of a load.  We currently handle two cases:  the load
24702     // is a direct child, and it's under an intervening TokenFactor.  It is
24703     // possible to dig deeper under nested TokenFactors.
24704     if (ChainVal == LdVal)
24705       Ld = cast<LoadSDNode>(St->getChain());
24706     else if (St->getValue().hasOneUse() &&
24707              ChainVal->getOpcode() == ISD::TokenFactor) {
24708       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24709         if (ChainVal->getOperand(i).getNode() == LdVal) {
24710           TokenFactorIndex = i;
24711           Ld = cast<LoadSDNode>(St->getValue());
24712         } else
24713           Ops.push_back(ChainVal->getOperand(i));
24714       }
24715     }
24716
24717     if (!Ld || !ISD::isNormalLoad(Ld))
24718       return SDValue();
24719
24720     // If this is not the MMX case, i.e. we are just turning i64 load/store
24721     // into f64 load/store, avoid the transformation if there are multiple
24722     // uses of the loaded value.
24723     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24724       return SDValue();
24725
24726     SDLoc LdDL(Ld);
24727     SDLoc StDL(N);
24728     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24729     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24730     // pair instead.
24731     if (Subtarget->is64Bit() || F64IsLegal) {
24732       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24733       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24734                                   Ld->getPointerInfo(), Ld->isVolatile(),
24735                                   Ld->isNonTemporal(), Ld->isInvariant(),
24736                                   Ld->getAlignment());
24737       SDValue NewChain = NewLd.getValue(1);
24738       if (TokenFactorIndex != -1) {
24739         Ops.push_back(NewChain);
24740         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24741       }
24742       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24743                           St->getPointerInfo(),
24744                           St->isVolatile(), St->isNonTemporal(),
24745                           St->getAlignment());
24746     }
24747
24748     // Otherwise, lower to two pairs of 32-bit loads / stores.
24749     SDValue LoAddr = Ld->getBasePtr();
24750     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24751                                  DAG.getConstant(4, LdDL, MVT::i32));
24752
24753     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24754                                Ld->getPointerInfo(),
24755                                Ld->isVolatile(), Ld->isNonTemporal(),
24756                                Ld->isInvariant(), Ld->getAlignment());
24757     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24758                                Ld->getPointerInfo().getWithOffset(4),
24759                                Ld->isVolatile(), Ld->isNonTemporal(),
24760                                Ld->isInvariant(),
24761                                MinAlign(Ld->getAlignment(), 4));
24762
24763     SDValue NewChain = LoLd.getValue(1);
24764     if (TokenFactorIndex != -1) {
24765       Ops.push_back(LoLd);
24766       Ops.push_back(HiLd);
24767       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24768     }
24769
24770     LoAddr = St->getBasePtr();
24771     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24772                          DAG.getConstant(4, StDL, MVT::i32));
24773
24774     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24775                                 St->getPointerInfo(),
24776                                 St->isVolatile(), St->isNonTemporal(),
24777                                 St->getAlignment());
24778     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24779                                 St->getPointerInfo().getWithOffset(4),
24780                                 St->isVolatile(),
24781                                 St->isNonTemporal(),
24782                                 MinAlign(St->getAlignment(), 4));
24783     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24784   }
24785
24786   // This is similar to the above case, but here we handle a scalar 64-bit
24787   // integer store that is extracted from a vector on a 32-bit target.
24788   // If we have SSE2, then we can treat it like a floating-point double
24789   // to get past legalization. The execution dependencies fixup pass will
24790   // choose the optimal machine instruction for the store if this really is
24791   // an integer or v2f32 rather than an f64.
24792   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24793       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24794     SDValue OldExtract = St->getOperand(1);
24795     SDValue ExtOp0 = OldExtract.getOperand(0);
24796     unsigned VecSize = ExtOp0.getValueSizeInBits();
24797     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24798     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24799     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24800                                      BitCast, OldExtract.getOperand(1));
24801     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24802                         St->getPointerInfo(), St->isVolatile(),
24803                         St->isNonTemporal(), St->getAlignment());
24804   }
24805
24806   return SDValue();
24807 }
24808
24809 /// Return 'true' if this vector operation is "horizontal"
24810 /// and return the operands for the horizontal operation in LHS and RHS.  A
24811 /// horizontal operation performs the binary operation on successive elements
24812 /// of its first operand, then on successive elements of its second operand,
24813 /// returning the resulting values in a vector.  For example, if
24814 ///   A = < float a0, float a1, float a2, float a3 >
24815 /// and
24816 ///   B = < float b0, float b1, float b2, float b3 >
24817 /// then the result of doing a horizontal operation on A and B is
24818 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24819 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24820 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24821 /// set to A, RHS to B, and the routine returns 'true'.
24822 /// Note that the binary operation should have the property that if one of the
24823 /// operands is UNDEF then the result is UNDEF.
24824 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24825   // Look for the following pattern: if
24826   //   A = < float a0, float a1, float a2, float a3 >
24827   //   B = < float b0, float b1, float b2, float b3 >
24828   // and
24829   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24830   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24831   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24832   // which is A horizontal-op B.
24833
24834   // At least one of the operands should be a vector shuffle.
24835   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24836       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24837     return false;
24838
24839   MVT VT = LHS.getSimpleValueType();
24840
24841   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24842          "Unsupported vector type for horizontal add/sub");
24843
24844   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24845   // operate independently on 128-bit lanes.
24846   unsigned NumElts = VT.getVectorNumElements();
24847   unsigned NumLanes = VT.getSizeInBits()/128;
24848   unsigned NumLaneElts = NumElts / NumLanes;
24849   assert((NumLaneElts % 2 == 0) &&
24850          "Vector type should have an even number of elements in each lane");
24851   unsigned HalfLaneElts = NumLaneElts/2;
24852
24853   // View LHS in the form
24854   //   LHS = VECTOR_SHUFFLE A, B, LMask
24855   // If LHS is not a shuffle then pretend it is the shuffle
24856   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24857   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24858   // type VT.
24859   SDValue A, B;
24860   SmallVector<int, 16> LMask(NumElts);
24861   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24862     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24863       A = LHS.getOperand(0);
24864     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24865       B = LHS.getOperand(1);
24866     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24867     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24868   } else {
24869     if (LHS.getOpcode() != ISD::UNDEF)
24870       A = LHS;
24871     for (unsigned i = 0; i != NumElts; ++i)
24872       LMask[i] = i;
24873   }
24874
24875   // Likewise, view RHS in the form
24876   //   RHS = VECTOR_SHUFFLE C, D, RMask
24877   SDValue C, D;
24878   SmallVector<int, 16> RMask(NumElts);
24879   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24880     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24881       C = RHS.getOperand(0);
24882     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24883       D = RHS.getOperand(1);
24884     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24885     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24886   } else {
24887     if (RHS.getOpcode() != ISD::UNDEF)
24888       C = RHS;
24889     for (unsigned i = 0; i != NumElts; ++i)
24890       RMask[i] = i;
24891   }
24892
24893   // Check that the shuffles are both shuffling the same vectors.
24894   if (!(A == C && B == D) && !(A == D && B == C))
24895     return false;
24896
24897   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24898   if (!A.getNode() && !B.getNode())
24899     return false;
24900
24901   // If A and B occur in reverse order in RHS, then "swap" them (which means
24902   // rewriting the mask).
24903   if (A != C)
24904     ShuffleVectorSDNode::commuteMask(RMask);
24905
24906   // At this point LHS and RHS are equivalent to
24907   //   LHS = VECTOR_SHUFFLE A, B, LMask
24908   //   RHS = VECTOR_SHUFFLE A, B, RMask
24909   // Check that the masks correspond to performing a horizontal operation.
24910   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24911     for (unsigned i = 0; i != NumLaneElts; ++i) {
24912       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24913
24914       // Ignore any UNDEF components.
24915       if (LIdx < 0 || RIdx < 0 ||
24916           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24917           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24918         continue;
24919
24920       // Check that successive elements are being operated on.  If not, this is
24921       // not a horizontal operation.
24922       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24923       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24924       if (!(LIdx == Index && RIdx == Index + 1) &&
24925           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24926         return false;
24927     }
24928   }
24929
24930   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24931   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24932   return true;
24933 }
24934
24935 /// Do target-specific dag combines on floating point adds.
24936 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24937                                   const X86Subtarget *Subtarget) {
24938   EVT VT = N->getValueType(0);
24939   SDValue LHS = N->getOperand(0);
24940   SDValue RHS = N->getOperand(1);
24941
24942   // Try to synthesize horizontal adds from adds of shuffles.
24943   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24944        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24945       isHorizontalBinOp(LHS, RHS, true))
24946     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24947   return SDValue();
24948 }
24949
24950 /// Do target-specific dag combines on floating point subs.
24951 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24952                                   const X86Subtarget *Subtarget) {
24953   EVT VT = N->getValueType(0);
24954   SDValue LHS = N->getOperand(0);
24955   SDValue RHS = N->getOperand(1);
24956
24957   // Try to synthesize horizontal subs from subs of shuffles.
24958   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24959        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24960       isHorizontalBinOp(LHS, RHS, false))
24961     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24962   return SDValue();
24963 }
24964
24965 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24966 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24967   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24968
24969   // F[X]OR(0.0, x) -> x
24970   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24971     if (C->getValueAPF().isPosZero())
24972       return N->getOperand(1);
24973
24974   // F[X]OR(x, 0.0) -> x
24975   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24976     if (C->getValueAPF().isPosZero())
24977       return N->getOperand(0);
24978   return SDValue();
24979 }
24980
24981 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24982 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24983   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24984
24985   // Only perform optimizations if UnsafeMath is used.
24986   if (!DAG.getTarget().Options.UnsafeFPMath)
24987     return SDValue();
24988
24989   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24990   // into FMINC and FMAXC, which are Commutative operations.
24991   unsigned NewOp = 0;
24992   switch (N->getOpcode()) {
24993     default: llvm_unreachable("unknown opcode");
24994     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24995     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24996   }
24997
24998   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24999                      N->getOperand(0), N->getOperand(1));
25000 }
25001
25002 /// Do target-specific dag combines on X86ISD::FAND nodes.
25003 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25004   // FAND(0.0, x) -> 0.0
25005   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25006     if (C->getValueAPF().isPosZero())
25007       return N->getOperand(0);
25008
25009   // FAND(x, 0.0) -> 0.0
25010   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25011     if (C->getValueAPF().isPosZero())
25012       return N->getOperand(1);
25013
25014   return SDValue();
25015 }
25016
25017 /// Do target-specific dag combines on X86ISD::FANDN nodes
25018 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25019   // FANDN(0.0, x) -> x
25020   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25021     if (C->getValueAPF().isPosZero())
25022       return N->getOperand(1);
25023
25024   // FANDN(x, 0.0) -> 0.0
25025   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25026     if (C->getValueAPF().isPosZero())
25027       return N->getOperand(1);
25028
25029   return SDValue();
25030 }
25031
25032 static SDValue PerformBTCombine(SDNode *N,
25033                                 SelectionDAG &DAG,
25034                                 TargetLowering::DAGCombinerInfo &DCI) {
25035   // BT ignores high bits in the bit index operand.
25036   SDValue Op1 = N->getOperand(1);
25037   if (Op1.hasOneUse()) {
25038     unsigned BitWidth = Op1.getValueSizeInBits();
25039     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25040     APInt KnownZero, KnownOne;
25041     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25042                                           !DCI.isBeforeLegalizeOps());
25043     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25044     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25045         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25046       DCI.CommitTargetLoweringOpt(TLO);
25047   }
25048   return SDValue();
25049 }
25050
25051 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25052   SDValue Op = N->getOperand(0);
25053   if (Op.getOpcode() == ISD::BITCAST)
25054     Op = Op.getOperand(0);
25055   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25056   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25057       VT.getVectorElementType().getSizeInBits() ==
25058       OpVT.getVectorElementType().getSizeInBits()) {
25059     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25060   }
25061   return SDValue();
25062 }
25063
25064 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25065                                                const X86Subtarget *Subtarget) {
25066   EVT VT = N->getValueType(0);
25067   if (!VT.isVector())
25068     return SDValue();
25069
25070   SDValue N0 = N->getOperand(0);
25071   SDValue N1 = N->getOperand(1);
25072   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25073   SDLoc dl(N);
25074
25075   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25076   // both SSE and AVX2 since there is no sign-extended shift right
25077   // operation on a vector with 64-bit elements.
25078   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25079   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25080   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25081       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25082     SDValue N00 = N0.getOperand(0);
25083
25084     // EXTLOAD has a better solution on AVX2,
25085     // it may be replaced with X86ISD::VSEXT node.
25086     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25087       if (!ISD::isNormalLoad(N00.getNode()))
25088         return SDValue();
25089
25090     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25091         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25092                                   N00, N1);
25093       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25094     }
25095   }
25096   return SDValue();
25097 }
25098
25099 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25100                                   TargetLowering::DAGCombinerInfo &DCI,
25101                                   const X86Subtarget *Subtarget) {
25102   SDValue N0 = N->getOperand(0);
25103   EVT VT = N->getValueType(0);
25104   EVT SVT = VT.getScalarType();
25105   EVT InVT = N0.getValueType();
25106   EVT InSVT = InVT.getScalarType();
25107   SDLoc DL(N);
25108
25109   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25110   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25111   // This exposes the sext to the sdivrem lowering, so that it directly extends
25112   // from AH (which we otherwise need to do contortions to access).
25113   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25114       InVT == MVT::i8 && VT == MVT::i32) {
25115     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25116     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25117                             N0.getOperand(0), N0.getOperand(1));
25118     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25119     return R.getValue(1);
25120   }
25121
25122   if (!DCI.isBeforeLegalizeOps()) {
25123     if (InVT == MVT::i1) {
25124       SDValue Zero = DAG.getConstant(0, DL, VT);
25125       SDValue AllOnes =
25126         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25127       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25128     }
25129     return SDValue();
25130   }
25131
25132   if (VT.isVector() && Subtarget->hasSSE2()) {
25133     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25134       EVT InVT = N.getValueType();
25135       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25136                                    Size / InVT.getScalarSizeInBits());
25137       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25138                                     DAG.getUNDEF(InVT));
25139       Opnds[0] = N;
25140       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25141     };
25142
25143     // If target-size is less than 128-bits, extend to a type that would extend
25144     // to 128 bits, extend that and extract the original target vector.
25145     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25146         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25147         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25148       unsigned Scale = 128 / VT.getSizeInBits();
25149       EVT ExVT =
25150           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25151       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25152       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25153       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25154                          DAG.getIntPtrConstant(0, DL));
25155     }
25156
25157     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25158     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25159     if (VT.getSizeInBits() == 128 &&
25160         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25161         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25162       SDValue ExOp = ExtendVecSize(DL, N0, 128);
25163       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25164     }
25165
25166     // On pre-AVX2 targets, split into 128-bit nodes of
25167     // ISD::SIGN_EXTEND_VECTOR_INREG.
25168     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25169         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25170         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25171       unsigned NumVecs = VT.getSizeInBits() / 128;
25172       unsigned NumSubElts = 128 / SVT.getSizeInBits();
25173       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25174       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25175
25176       SmallVector<SDValue, 8> Opnds;
25177       for (unsigned i = 0, Offset = 0; i != NumVecs;
25178            ++i, Offset += NumSubElts) {
25179         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25180                                      DAG.getIntPtrConstant(Offset, DL));
25181         SrcVec = ExtendVecSize(DL, SrcVec, 128);
25182         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25183         Opnds.push_back(SrcVec);
25184       }
25185       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25186     }
25187   }
25188
25189   if (!Subtarget->hasFp256())
25190     return SDValue();
25191
25192   if (VT.isVector() && VT.getSizeInBits() == 256)
25193     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25194       return R;
25195
25196   return SDValue();
25197 }
25198
25199 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25200                                  const X86Subtarget* Subtarget) {
25201   SDLoc dl(N);
25202   EVT VT = N->getValueType(0);
25203
25204   // Let legalize expand this if it isn't a legal type yet.
25205   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25206     return SDValue();
25207
25208   EVT ScalarVT = VT.getScalarType();
25209   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25210       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25211        !Subtarget->hasAVX512()))
25212     return SDValue();
25213
25214   SDValue A = N->getOperand(0);
25215   SDValue B = N->getOperand(1);
25216   SDValue C = N->getOperand(2);
25217
25218   bool NegA = (A.getOpcode() == ISD::FNEG);
25219   bool NegB = (B.getOpcode() == ISD::FNEG);
25220   bool NegC = (C.getOpcode() == ISD::FNEG);
25221
25222   // Negative multiplication when NegA xor NegB
25223   bool NegMul = (NegA != NegB);
25224   if (NegA)
25225     A = A.getOperand(0);
25226   if (NegB)
25227     B = B.getOperand(0);
25228   if (NegC)
25229     C = C.getOperand(0);
25230
25231   unsigned Opcode;
25232   if (!NegMul)
25233     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25234   else
25235     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25236
25237   return DAG.getNode(Opcode, dl, VT, A, B, C);
25238 }
25239
25240 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25241                                   TargetLowering::DAGCombinerInfo &DCI,
25242                                   const X86Subtarget *Subtarget) {
25243   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25244   //           (and (i32 x86isd::setcc_carry), 1)
25245   // This eliminates the zext. This transformation is necessary because
25246   // ISD::SETCC is always legalized to i8.
25247   SDLoc dl(N);
25248   SDValue N0 = N->getOperand(0);
25249   EVT VT = N->getValueType(0);
25250
25251   if (N0.getOpcode() == ISD::AND &&
25252       N0.hasOneUse() &&
25253       N0.getOperand(0).hasOneUse()) {
25254     SDValue N00 = N0.getOperand(0);
25255     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25256       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25257       if (!C || C->getZExtValue() != 1)
25258         return SDValue();
25259       return DAG.getNode(ISD::AND, dl, VT,
25260                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25261                                      N00.getOperand(0), N00.getOperand(1)),
25262                          DAG.getConstant(1, dl, VT));
25263     }
25264   }
25265
25266   if (N0.getOpcode() == ISD::TRUNCATE &&
25267       N0.hasOneUse() &&
25268       N0.getOperand(0).hasOneUse()) {
25269     SDValue N00 = N0.getOperand(0);
25270     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25271       return DAG.getNode(ISD::AND, dl, VT,
25272                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25273                                      N00.getOperand(0), N00.getOperand(1)),
25274                          DAG.getConstant(1, dl, VT));
25275     }
25276   }
25277
25278   if (VT.is256BitVector())
25279     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25280       return R;
25281
25282   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25283   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25284   // This exposes the zext to the udivrem lowering, so that it directly extends
25285   // from AH (which we otherwise need to do contortions to access).
25286   if (N0.getOpcode() == ISD::UDIVREM &&
25287       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25288       (VT == MVT::i32 || VT == MVT::i64)) {
25289     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25290     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25291                             N0.getOperand(0), N0.getOperand(1));
25292     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25293     return R.getValue(1);
25294   }
25295
25296   return SDValue();
25297 }
25298
25299 // Optimize x == -y --> x+y == 0
25300 //          x != -y --> x+y != 0
25301 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25302                                       const X86Subtarget* Subtarget) {
25303   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25304   SDValue LHS = N->getOperand(0);
25305   SDValue RHS = N->getOperand(1);
25306   EVT VT = N->getValueType(0);
25307   SDLoc DL(N);
25308
25309   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25310     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25311       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25312         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25313                                    LHS.getOperand(1));
25314         return DAG.getSetCC(DL, N->getValueType(0), addV,
25315                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25316       }
25317   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25318     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25319       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25320         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25321                                    RHS.getOperand(1));
25322         return DAG.getSetCC(DL, N->getValueType(0), addV,
25323                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25324       }
25325
25326   if (VT.getScalarType() == MVT::i1 &&
25327       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25328     bool IsSEXT0 =
25329         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25330         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25331     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25332
25333     if (!IsSEXT0 || !IsVZero1) {
25334       // Swap the operands and update the condition code.
25335       std::swap(LHS, RHS);
25336       CC = ISD::getSetCCSwappedOperands(CC);
25337
25338       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25339                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25340       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25341     }
25342
25343     if (IsSEXT0 && IsVZero1) {
25344       assert(VT == LHS.getOperand(0).getValueType() &&
25345              "Uexpected operand type");
25346       if (CC == ISD::SETGT)
25347         return DAG.getConstant(0, DL, VT);
25348       if (CC == ISD::SETLE)
25349         return DAG.getConstant(1, DL, VT);
25350       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25351         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25352
25353       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25354              "Unexpected condition code!");
25355       return LHS.getOperand(0);
25356     }
25357   }
25358
25359   return SDValue();
25360 }
25361
25362 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25363                                          SelectionDAG &DAG) {
25364   SDLoc dl(Load);
25365   MVT VT = Load->getSimpleValueType(0);
25366   MVT EVT = VT.getVectorElementType();
25367   SDValue Addr = Load->getOperand(1);
25368   SDValue NewAddr = DAG.getNode(
25369       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25370       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25371                       Addr.getSimpleValueType()));
25372
25373   SDValue NewLoad =
25374       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25375                   DAG.getMachineFunction().getMachineMemOperand(
25376                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25377   return NewLoad;
25378 }
25379
25380 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25381                                       const X86Subtarget *Subtarget) {
25382   SDLoc dl(N);
25383   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25384   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25385          "X86insertps is only defined for v4x32");
25386
25387   SDValue Ld = N->getOperand(1);
25388   if (MayFoldLoad(Ld)) {
25389     // Extract the countS bits from the immediate so we can get the proper
25390     // address when narrowing the vector load to a specific element.
25391     // When the second source op is a memory address, insertps doesn't use
25392     // countS and just gets an f32 from that address.
25393     unsigned DestIndex =
25394         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25395
25396     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25397
25398     // Create this as a scalar to vector to match the instruction pattern.
25399     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25400     // countS bits are ignored when loading from memory on insertps, which
25401     // means we don't need to explicitly set them to 0.
25402     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25403                        LoadScalarToVector, N->getOperand(2));
25404   }
25405   return SDValue();
25406 }
25407
25408 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25409   SDValue V0 = N->getOperand(0);
25410   SDValue V1 = N->getOperand(1);
25411   SDLoc DL(N);
25412   EVT VT = N->getValueType(0);
25413
25414   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25415   // operands and changing the mask to 1. This saves us a bunch of
25416   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25417   // x86InstrInfo knows how to commute this back after instruction selection
25418   // if it would help register allocation.
25419
25420   // TODO: If optimizing for size or a processor that doesn't suffer from
25421   // partial register update stalls, this should be transformed into a MOVSD
25422   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25423
25424   if (VT == MVT::v2f64)
25425     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25426       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25427         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25428         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25429       }
25430
25431   return SDValue();
25432 }
25433
25434 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25435 // as "sbb reg,reg", since it can be extended without zext and produces
25436 // an all-ones bit which is more useful than 0/1 in some cases.
25437 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25438                                MVT VT) {
25439   if (VT == MVT::i8)
25440     return DAG.getNode(ISD::AND, DL, VT,
25441                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25442                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25443                                    EFLAGS),
25444                        DAG.getConstant(1, DL, VT));
25445   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25446   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25447                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25448                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25449                                  EFLAGS));
25450 }
25451
25452 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25453 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25454                                    TargetLowering::DAGCombinerInfo &DCI,
25455                                    const X86Subtarget *Subtarget) {
25456   SDLoc DL(N);
25457   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25458   SDValue EFLAGS = N->getOperand(1);
25459
25460   if (CC == X86::COND_A) {
25461     // Try to convert COND_A into COND_B in an attempt to facilitate
25462     // materializing "setb reg".
25463     //
25464     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25465     // cannot take an immediate as its first operand.
25466     //
25467     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25468         EFLAGS.getValueType().isInteger() &&
25469         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25470       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25471                                    EFLAGS.getNode()->getVTList(),
25472                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25473       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25474       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25475     }
25476   }
25477
25478   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25479   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25480   // cases.
25481   if (CC == X86::COND_B)
25482     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25483
25484   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25485     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25486     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25487   }
25488
25489   return SDValue();
25490 }
25491
25492 // Optimize branch condition evaluation.
25493 //
25494 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25495                                     TargetLowering::DAGCombinerInfo &DCI,
25496                                     const X86Subtarget *Subtarget) {
25497   SDLoc DL(N);
25498   SDValue Chain = N->getOperand(0);
25499   SDValue Dest = N->getOperand(1);
25500   SDValue EFLAGS = N->getOperand(3);
25501   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25502
25503   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25504     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25505     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25506                        Flags);
25507   }
25508
25509   return SDValue();
25510 }
25511
25512 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25513                                                          SelectionDAG &DAG) {
25514   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25515   // optimize away operation when it's from a constant.
25516   //
25517   // The general transformation is:
25518   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25519   //       AND(VECTOR_CMP(x,y), constant2)
25520   //    constant2 = UNARYOP(constant)
25521
25522   // Early exit if this isn't a vector operation, the operand of the
25523   // unary operation isn't a bitwise AND, or if the sizes of the operations
25524   // aren't the same.
25525   EVT VT = N->getValueType(0);
25526   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25527       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25528       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25529     return SDValue();
25530
25531   // Now check that the other operand of the AND is a constant. We could
25532   // make the transformation for non-constant splats as well, but it's unclear
25533   // that would be a benefit as it would not eliminate any operations, just
25534   // perform one more step in scalar code before moving to the vector unit.
25535   if (BuildVectorSDNode *BV =
25536           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25537     // Bail out if the vector isn't a constant.
25538     if (!BV->isConstant())
25539       return SDValue();
25540
25541     // Everything checks out. Build up the new and improved node.
25542     SDLoc DL(N);
25543     EVT IntVT = BV->getValueType(0);
25544     // Create a new constant of the appropriate type for the transformed
25545     // DAG.
25546     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25547     // The AND node needs bitcasts to/from an integer vector type around it.
25548     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25549     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25550                                  N->getOperand(0)->getOperand(0), MaskConst);
25551     SDValue Res = DAG.getBitcast(VT, NewAnd);
25552     return Res;
25553   }
25554
25555   return SDValue();
25556 }
25557
25558 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25559                                         const X86Subtarget *Subtarget) {
25560   SDValue Op0 = N->getOperand(0);
25561   EVT VT = N->getValueType(0);
25562   EVT InVT = Op0.getValueType();
25563   EVT InSVT = InVT.getScalarType();
25564   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25565
25566   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25567   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25568   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25569     SDLoc dl(N);
25570     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25571                                  InVT.getVectorNumElements());
25572     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25573
25574     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25575       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25576
25577     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25578   }
25579
25580   return SDValue();
25581 }
25582
25583 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25584                                         const X86Subtarget *Subtarget) {
25585   // First try to optimize away the conversion entirely when it's
25586   // conditionally from a constant. Vectors only.
25587   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25588     return Res;
25589
25590   // Now move on to more general possibilities.
25591   SDValue Op0 = N->getOperand(0);
25592   EVT VT = N->getValueType(0);
25593   EVT InVT = Op0.getValueType();
25594   EVT InSVT = InVT.getScalarType();
25595
25596   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25597   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25598   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25599     SDLoc dl(N);
25600     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25601                                  InVT.getVectorNumElements());
25602     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25603     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25604   }
25605
25606   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25607   // a 32-bit target where SSE doesn't support i64->FP operations.
25608   if (Op0.getOpcode() == ISD::LOAD) {
25609     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25610     EVT LdVT = Ld->getValueType(0);
25611
25612     // This transformation is not supported if the result type is f16
25613     if (VT == MVT::f16)
25614       return SDValue();
25615
25616     if (!Ld->isVolatile() && !VT.isVector() &&
25617         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25618         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25619       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25620           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25621       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25622       return FILDChain;
25623     }
25624   }
25625   return SDValue();
25626 }
25627
25628 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25629 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25630                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25631   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25632   // the result is either zero or one (depending on the input carry bit).
25633   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25634   if (X86::isZeroNode(N->getOperand(0)) &&
25635       X86::isZeroNode(N->getOperand(1)) &&
25636       // We don't have a good way to replace an EFLAGS use, so only do this when
25637       // dead right now.
25638       SDValue(N, 1).use_empty()) {
25639     SDLoc DL(N);
25640     EVT VT = N->getValueType(0);
25641     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25642     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25643                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25644                                            DAG.getConstant(X86::COND_B, DL,
25645                                                            MVT::i8),
25646                                            N->getOperand(2)),
25647                                DAG.getConstant(1, DL, VT));
25648     return DCI.CombineTo(N, Res1, CarryOut);
25649   }
25650
25651   return SDValue();
25652 }
25653
25654 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25655 //      (add Y, (setne X, 0)) -> sbb -1, Y
25656 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25657 //      (sub (setne X, 0), Y) -> adc -1, Y
25658 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25659   SDLoc DL(N);
25660
25661   // Look through ZExts.
25662   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25663   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25664     return SDValue();
25665
25666   SDValue SetCC = Ext.getOperand(0);
25667   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25668     return SDValue();
25669
25670   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25671   if (CC != X86::COND_E && CC != X86::COND_NE)
25672     return SDValue();
25673
25674   SDValue Cmp = SetCC.getOperand(1);
25675   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25676       !X86::isZeroNode(Cmp.getOperand(1)) ||
25677       !Cmp.getOperand(0).getValueType().isInteger())
25678     return SDValue();
25679
25680   SDValue CmpOp0 = Cmp.getOperand(0);
25681   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25682                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25683
25684   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25685   if (CC == X86::COND_NE)
25686     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25687                        DL, OtherVal.getValueType(), OtherVal,
25688                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25689                        NewCmp);
25690   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25691                      DL, OtherVal.getValueType(), OtherVal,
25692                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25693 }
25694
25695 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25696 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25697                                  const X86Subtarget *Subtarget) {
25698   EVT VT = N->getValueType(0);
25699   SDValue Op0 = N->getOperand(0);
25700   SDValue Op1 = N->getOperand(1);
25701
25702   // Try to synthesize horizontal adds from adds of shuffles.
25703   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25704        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25705       isHorizontalBinOp(Op0, Op1, true))
25706     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25707
25708   return OptimizeConditionalInDecrement(N, DAG);
25709 }
25710
25711 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25712                                  const X86Subtarget *Subtarget) {
25713   SDValue Op0 = N->getOperand(0);
25714   SDValue Op1 = N->getOperand(1);
25715
25716   // X86 can't encode an immediate LHS of a sub. See if we can push the
25717   // negation into a preceding instruction.
25718   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25719     // If the RHS of the sub is a XOR with one use and a constant, invert the
25720     // immediate. Then add one to the LHS of the sub so we can turn
25721     // X-Y -> X+~Y+1, saving one register.
25722     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25723         isa<ConstantSDNode>(Op1.getOperand(1))) {
25724       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25725       EVT VT = Op0.getValueType();
25726       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25727                                    Op1.getOperand(0),
25728                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25729       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25730                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25731     }
25732   }
25733
25734   // Try to synthesize horizontal adds from adds of shuffles.
25735   EVT VT = N->getValueType(0);
25736   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25737        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25738       isHorizontalBinOp(Op0, Op1, true))
25739     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25740
25741   return OptimizeConditionalInDecrement(N, DAG);
25742 }
25743
25744 /// performVZEXTCombine - Performs build vector combines
25745 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25746                                    TargetLowering::DAGCombinerInfo &DCI,
25747                                    const X86Subtarget *Subtarget) {
25748   SDLoc DL(N);
25749   MVT VT = N->getSimpleValueType(0);
25750   SDValue Op = N->getOperand(0);
25751   MVT OpVT = Op.getSimpleValueType();
25752   MVT OpEltVT = OpVT.getVectorElementType();
25753   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25754
25755   // (vzext (bitcast (vzext (x)) -> (vzext x)
25756   SDValue V = Op;
25757   while (V.getOpcode() == ISD::BITCAST)
25758     V = V.getOperand(0);
25759
25760   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25761     MVT InnerVT = V.getSimpleValueType();
25762     MVT InnerEltVT = InnerVT.getVectorElementType();
25763
25764     // If the element sizes match exactly, we can just do one larger vzext. This
25765     // is always an exact type match as vzext operates on integer types.
25766     if (OpEltVT == InnerEltVT) {
25767       assert(OpVT == InnerVT && "Types must match for vzext!");
25768       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25769     }
25770
25771     // The only other way we can combine them is if only a single element of the
25772     // inner vzext is used in the input to the outer vzext.
25773     if (InnerEltVT.getSizeInBits() < InputBits)
25774       return SDValue();
25775
25776     // In this case, the inner vzext is completely dead because we're going to
25777     // only look at bits inside of the low element. Just do the outer vzext on
25778     // a bitcast of the input to the inner.
25779     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25780   }
25781
25782   // Check if we can bypass extracting and re-inserting an element of an input
25783   // vector. Essentially:
25784   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25785   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25786       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25787       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25788     SDValue ExtractedV = V.getOperand(0);
25789     SDValue OrigV = ExtractedV.getOperand(0);
25790     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25791       if (ExtractIdx->getZExtValue() == 0) {
25792         MVT OrigVT = OrigV.getSimpleValueType();
25793         // Extract a subvector if necessary...
25794         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25795           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25796           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25797                                     OrigVT.getVectorNumElements() / Ratio);
25798           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25799                               DAG.getIntPtrConstant(0, DL));
25800         }
25801         Op = DAG.getBitcast(OpVT, OrigV);
25802         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25803       }
25804   }
25805
25806   return SDValue();
25807 }
25808
25809 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25810                                              DAGCombinerInfo &DCI) const {
25811   SelectionDAG &DAG = DCI.DAG;
25812   switch (N->getOpcode()) {
25813   default: break;
25814   case ISD::EXTRACT_VECTOR_ELT:
25815     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25816   case ISD::VSELECT:
25817   case ISD::SELECT:
25818   case X86ISD::SHRUNKBLEND:
25819     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25820   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25821   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25822   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25823   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25824   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25825   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25826   case ISD::SHL:
25827   case ISD::SRA:
25828   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25829   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25830   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25831   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25832   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25833   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25834   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25835   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25836   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25837   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25838   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25839   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25840   case X86ISD::FXOR:
25841   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25842   case X86ISD::FMIN:
25843   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25844   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25845   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25846   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25847   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25848   case ISD::ANY_EXTEND:
25849   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25850   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25851   case ISD::SIGN_EXTEND_INREG:
25852     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25853   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25854   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25855   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25856   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25857   case X86ISD::SHUFP:       // Handle all target specific shuffles
25858   case X86ISD::PALIGNR:
25859   case X86ISD::UNPCKH:
25860   case X86ISD::UNPCKL:
25861   case X86ISD::MOVHLPS:
25862   case X86ISD::MOVLHPS:
25863   case X86ISD::PSHUFB:
25864   case X86ISD::PSHUFD:
25865   case X86ISD::PSHUFHW:
25866   case X86ISD::PSHUFLW:
25867   case X86ISD::MOVSS:
25868   case X86ISD::MOVSD:
25869   case X86ISD::VPERMILPI:
25870   case X86ISD::VPERM2X128:
25871   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25872   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25873   case X86ISD::INSERTPS: {
25874     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25875       return PerformINSERTPSCombine(N, DAG, Subtarget);
25876     break;
25877   }
25878   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25879   }
25880
25881   return SDValue();
25882 }
25883
25884 /// isTypeDesirableForOp - Return true if the target has native support for
25885 /// the specified value type and it is 'desirable' to use the type for the
25886 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25887 /// instruction encodings are longer and some i16 instructions are slow.
25888 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25889   if (!isTypeLegal(VT))
25890     return false;
25891   if (VT != MVT::i16)
25892     return true;
25893
25894   switch (Opc) {
25895   default:
25896     return true;
25897   case ISD::LOAD:
25898   case ISD::SIGN_EXTEND:
25899   case ISD::ZERO_EXTEND:
25900   case ISD::ANY_EXTEND:
25901   case ISD::SHL:
25902   case ISD::SRL:
25903   case ISD::SUB:
25904   case ISD::ADD:
25905   case ISD::MUL:
25906   case ISD::AND:
25907   case ISD::OR:
25908   case ISD::XOR:
25909     return false;
25910   }
25911 }
25912
25913 /// IsDesirableToPromoteOp - This method query the target whether it is
25914 /// beneficial for dag combiner to promote the specified node. If true, it
25915 /// should return the desired promotion type by reference.
25916 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25917   EVT VT = Op.getValueType();
25918   if (VT != MVT::i16)
25919     return false;
25920
25921   bool Promote = false;
25922   bool Commute = false;
25923   switch (Op.getOpcode()) {
25924   default: break;
25925   case ISD::LOAD: {
25926     LoadSDNode *LD = cast<LoadSDNode>(Op);
25927     // If the non-extending load has a single use and it's not live out, then it
25928     // might be folded.
25929     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25930                                                      Op.hasOneUse()*/) {
25931       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25932              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25933         // The only case where we'd want to promote LOAD (rather then it being
25934         // promoted as an operand is when it's only use is liveout.
25935         if (UI->getOpcode() != ISD::CopyToReg)
25936           return false;
25937       }
25938     }
25939     Promote = true;
25940     break;
25941   }
25942   case ISD::SIGN_EXTEND:
25943   case ISD::ZERO_EXTEND:
25944   case ISD::ANY_EXTEND:
25945     Promote = true;
25946     break;
25947   case ISD::SHL:
25948   case ISD::SRL: {
25949     SDValue N0 = Op.getOperand(0);
25950     // Look out for (store (shl (load), x)).
25951     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25952       return false;
25953     Promote = true;
25954     break;
25955   }
25956   case ISD::ADD:
25957   case ISD::MUL:
25958   case ISD::AND:
25959   case ISD::OR:
25960   case ISD::XOR:
25961     Commute = true;
25962     // fallthrough
25963   case ISD::SUB: {
25964     SDValue N0 = Op.getOperand(0);
25965     SDValue N1 = Op.getOperand(1);
25966     if (!Commute && MayFoldLoad(N1))
25967       return false;
25968     // Avoid disabling potential load folding opportunities.
25969     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25970       return false;
25971     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25972       return false;
25973     Promote = true;
25974   }
25975   }
25976
25977   PVT = MVT::i32;
25978   return Promote;
25979 }
25980
25981 //===----------------------------------------------------------------------===//
25982 //                           X86 Inline Assembly Support
25983 //===----------------------------------------------------------------------===//
25984
25985 // Helper to match a string separated by whitespace.
25986 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25987   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25988
25989   for (StringRef Piece : Pieces) {
25990     if (!S.startswith(Piece)) // Check if the piece matches.
25991       return false;
25992
25993     S = S.substr(Piece.size());
25994     StringRef::size_type Pos = S.find_first_not_of(" \t");
25995     if (Pos == 0) // We matched a prefix.
25996       return false;
25997
25998     S = S.substr(Pos);
25999   }
26000
26001   return S.empty();
26002 }
26003
26004 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26005
26006   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26007     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26008         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26009         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26010
26011       if (AsmPieces.size() == 3)
26012         return true;
26013       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26014         return true;
26015     }
26016   }
26017   return false;
26018 }
26019
26020 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26021   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26022
26023   std::string AsmStr = IA->getAsmString();
26024
26025   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26026   if (!Ty || Ty->getBitWidth() % 16 != 0)
26027     return false;
26028
26029   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26030   SmallVector<StringRef, 4> AsmPieces;
26031   SplitString(AsmStr, AsmPieces, ";\n");
26032
26033   switch (AsmPieces.size()) {
26034   default: return false;
26035   case 1:
26036     // FIXME: this should verify that we are targeting a 486 or better.  If not,
26037     // we will turn this bswap into something that will be lowered to logical
26038     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26039     // lower so don't worry about this.
26040     // bswap $0
26041     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26042         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26043         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26044         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26045         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26046         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26047       // No need to check constraints, nothing other than the equivalent of
26048       // "=r,0" would be valid here.
26049       return IntrinsicLowering::LowerToByteSwap(CI);
26050     }
26051
26052     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26053     if (CI->getType()->isIntegerTy(16) &&
26054         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26055         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26056          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26057       AsmPieces.clear();
26058       StringRef ConstraintsStr = IA->getConstraintString();
26059       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26060       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26061       if (clobbersFlagRegisters(AsmPieces))
26062         return IntrinsicLowering::LowerToByteSwap(CI);
26063     }
26064     break;
26065   case 3:
26066     if (CI->getType()->isIntegerTy(32) &&
26067         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26068         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26069         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26070         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26071       AsmPieces.clear();
26072       StringRef ConstraintsStr = IA->getConstraintString();
26073       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26074       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26075       if (clobbersFlagRegisters(AsmPieces))
26076         return IntrinsicLowering::LowerToByteSwap(CI);
26077     }
26078
26079     if (CI->getType()->isIntegerTy(64)) {
26080       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26081       if (Constraints.size() >= 2 &&
26082           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26083           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26084         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
26085         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26086             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26087             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26088           return IntrinsicLowering::LowerToByteSwap(CI);
26089       }
26090     }
26091     break;
26092   }
26093   return false;
26094 }
26095
26096 /// getConstraintType - Given a constraint letter, return the type of
26097 /// constraint it is for this target.
26098 X86TargetLowering::ConstraintType
26099 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26100   if (Constraint.size() == 1) {
26101     switch (Constraint[0]) {
26102     case 'R':
26103     case 'q':
26104     case 'Q':
26105     case 'f':
26106     case 't':
26107     case 'u':
26108     case 'y':
26109     case 'x':
26110     case 'Y':
26111     case 'l':
26112       return C_RegisterClass;
26113     case 'a':
26114     case 'b':
26115     case 'c':
26116     case 'd':
26117     case 'S':
26118     case 'D':
26119     case 'A':
26120       return C_Register;
26121     case 'I':
26122     case 'J':
26123     case 'K':
26124     case 'L':
26125     case 'M':
26126     case 'N':
26127     case 'G':
26128     case 'C':
26129     case 'e':
26130     case 'Z':
26131       return C_Other;
26132     default:
26133       break;
26134     }
26135   }
26136   return TargetLowering::getConstraintType(Constraint);
26137 }
26138
26139 /// Examine constraint type and operand type and determine a weight value.
26140 /// This object must already have been set up with the operand type
26141 /// and the current alternative constraint selected.
26142 TargetLowering::ConstraintWeight
26143   X86TargetLowering::getSingleConstraintMatchWeight(
26144     AsmOperandInfo &info, const char *constraint) const {
26145   ConstraintWeight weight = CW_Invalid;
26146   Value *CallOperandVal = info.CallOperandVal;
26147     // If we don't have a value, we can't do a match,
26148     // but allow it at the lowest weight.
26149   if (!CallOperandVal)
26150     return CW_Default;
26151   Type *type = CallOperandVal->getType();
26152   // Look at the constraint type.
26153   switch (*constraint) {
26154   default:
26155     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26156   case 'R':
26157   case 'q':
26158   case 'Q':
26159   case 'a':
26160   case 'b':
26161   case 'c':
26162   case 'd':
26163   case 'S':
26164   case 'D':
26165   case 'A':
26166     if (CallOperandVal->getType()->isIntegerTy())
26167       weight = CW_SpecificReg;
26168     break;
26169   case 'f':
26170   case 't':
26171   case 'u':
26172     if (type->isFloatingPointTy())
26173       weight = CW_SpecificReg;
26174     break;
26175   case 'y':
26176     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26177       weight = CW_SpecificReg;
26178     break;
26179   case 'x':
26180   case 'Y':
26181     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26182         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26183       weight = CW_Register;
26184     break;
26185   case 'I':
26186     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26187       if (C->getZExtValue() <= 31)
26188         weight = CW_Constant;
26189     }
26190     break;
26191   case 'J':
26192     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26193       if (C->getZExtValue() <= 63)
26194         weight = CW_Constant;
26195     }
26196     break;
26197   case 'K':
26198     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26199       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26200         weight = CW_Constant;
26201     }
26202     break;
26203   case 'L':
26204     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26205       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26206         weight = CW_Constant;
26207     }
26208     break;
26209   case 'M':
26210     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26211       if (C->getZExtValue() <= 3)
26212         weight = CW_Constant;
26213     }
26214     break;
26215   case 'N':
26216     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26217       if (C->getZExtValue() <= 0xff)
26218         weight = CW_Constant;
26219     }
26220     break;
26221   case 'G':
26222   case 'C':
26223     if (isa<ConstantFP>(CallOperandVal)) {
26224       weight = CW_Constant;
26225     }
26226     break;
26227   case 'e':
26228     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26229       if ((C->getSExtValue() >= -0x80000000LL) &&
26230           (C->getSExtValue() <= 0x7fffffffLL))
26231         weight = CW_Constant;
26232     }
26233     break;
26234   case 'Z':
26235     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26236       if (C->getZExtValue() <= 0xffffffff)
26237         weight = CW_Constant;
26238     }
26239     break;
26240   }
26241   return weight;
26242 }
26243
26244 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26245 /// with another that has more specific requirements based on the type of the
26246 /// corresponding operand.
26247 const char *X86TargetLowering::
26248 LowerXConstraint(EVT ConstraintVT) const {
26249   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26250   // 'f' like normal targets.
26251   if (ConstraintVT.isFloatingPoint()) {
26252     if (Subtarget->hasSSE2())
26253       return "Y";
26254     if (Subtarget->hasSSE1())
26255       return "x";
26256   }
26257
26258   return TargetLowering::LowerXConstraint(ConstraintVT);
26259 }
26260
26261 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26262 /// vector.  If it is invalid, don't add anything to Ops.
26263 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26264                                                      std::string &Constraint,
26265                                                      std::vector<SDValue>&Ops,
26266                                                      SelectionDAG &DAG) const {
26267   SDValue Result;
26268
26269   // Only support length 1 constraints for now.
26270   if (Constraint.length() > 1) return;
26271
26272   char ConstraintLetter = Constraint[0];
26273   switch (ConstraintLetter) {
26274   default: break;
26275   case 'I':
26276     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26277       if (C->getZExtValue() <= 31) {
26278         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26279                                        Op.getValueType());
26280         break;
26281       }
26282     }
26283     return;
26284   case 'J':
26285     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26286       if (C->getZExtValue() <= 63) {
26287         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26288                                        Op.getValueType());
26289         break;
26290       }
26291     }
26292     return;
26293   case 'K':
26294     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26295       if (isInt<8>(C->getSExtValue())) {
26296         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26297                                        Op.getValueType());
26298         break;
26299       }
26300     }
26301     return;
26302   case 'L':
26303     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26304       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26305           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26306         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26307                                        Op.getValueType());
26308         break;
26309       }
26310     }
26311     return;
26312   case 'M':
26313     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26314       if (C->getZExtValue() <= 3) {
26315         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26316                                        Op.getValueType());
26317         break;
26318       }
26319     }
26320     return;
26321   case 'N':
26322     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26323       if (C->getZExtValue() <= 255) {
26324         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26325                                        Op.getValueType());
26326         break;
26327       }
26328     }
26329     return;
26330   case 'O':
26331     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26332       if (C->getZExtValue() <= 127) {
26333         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26334                                        Op.getValueType());
26335         break;
26336       }
26337     }
26338     return;
26339   case 'e': {
26340     // 32-bit signed value
26341     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26342       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26343                                            C->getSExtValue())) {
26344         // Widen to 64 bits here to get it sign extended.
26345         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26346         break;
26347       }
26348     // FIXME gcc accepts some relocatable values here too, but only in certain
26349     // memory models; it's complicated.
26350     }
26351     return;
26352   }
26353   case 'Z': {
26354     // 32-bit unsigned value
26355     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26356       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26357                                            C->getZExtValue())) {
26358         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26359                                        Op.getValueType());
26360         break;
26361       }
26362     }
26363     // FIXME gcc accepts some relocatable values here too, but only in certain
26364     // memory models; it's complicated.
26365     return;
26366   }
26367   case 'i': {
26368     // Literal immediates are always ok.
26369     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26370       // Widen to 64 bits here to get it sign extended.
26371       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26372       break;
26373     }
26374
26375     // In any sort of PIC mode addresses need to be computed at runtime by
26376     // adding in a register or some sort of table lookup.  These can't
26377     // be used as immediates.
26378     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26379       return;
26380
26381     // If we are in non-pic codegen mode, we allow the address of a global (with
26382     // an optional displacement) to be used with 'i'.
26383     GlobalAddressSDNode *GA = nullptr;
26384     int64_t Offset = 0;
26385
26386     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26387     while (1) {
26388       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26389         Offset += GA->getOffset();
26390         break;
26391       } else if (Op.getOpcode() == ISD::ADD) {
26392         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26393           Offset += C->getZExtValue();
26394           Op = Op.getOperand(0);
26395           continue;
26396         }
26397       } else if (Op.getOpcode() == ISD::SUB) {
26398         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26399           Offset += -C->getZExtValue();
26400           Op = Op.getOperand(0);
26401           continue;
26402         }
26403       }
26404
26405       // Otherwise, this isn't something we can handle, reject it.
26406       return;
26407     }
26408
26409     const GlobalValue *GV = GA->getGlobal();
26410     // If we require an extra load to get this address, as in PIC mode, we
26411     // can't accept it.
26412     if (isGlobalStubReference(
26413             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26414       return;
26415
26416     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26417                                         GA->getValueType(0), Offset);
26418     break;
26419   }
26420   }
26421
26422   if (Result.getNode()) {
26423     Ops.push_back(Result);
26424     return;
26425   }
26426   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26427 }
26428
26429 std::pair<unsigned, const TargetRegisterClass *>
26430 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26431                                                 StringRef Constraint,
26432                                                 MVT VT) const {
26433   // First, see if this is a constraint that directly corresponds to an LLVM
26434   // register class.
26435   if (Constraint.size() == 1) {
26436     // GCC Constraint Letters
26437     switch (Constraint[0]) {
26438     default: break;
26439       // TODO: Slight differences here in allocation order and leaving
26440       // RIP in the class. Do they matter any more here than they do
26441       // in the normal allocation?
26442     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26443       if (Subtarget->is64Bit()) {
26444         if (VT == MVT::i32 || VT == MVT::f32)
26445           return std::make_pair(0U, &X86::GR32RegClass);
26446         if (VT == MVT::i16)
26447           return std::make_pair(0U, &X86::GR16RegClass);
26448         if (VT == MVT::i8 || VT == MVT::i1)
26449           return std::make_pair(0U, &X86::GR8RegClass);
26450         if (VT == MVT::i64 || VT == MVT::f64)
26451           return std::make_pair(0U, &X86::GR64RegClass);
26452         break;
26453       }
26454       // 32-bit fallthrough
26455     case 'Q':   // Q_REGS
26456       if (VT == MVT::i32 || VT == MVT::f32)
26457         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26458       if (VT == MVT::i16)
26459         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26460       if (VT == MVT::i8 || VT == MVT::i1)
26461         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26462       if (VT == MVT::i64)
26463         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26464       break;
26465     case 'r':   // GENERAL_REGS
26466     case 'l':   // INDEX_REGS
26467       if (VT == MVT::i8 || VT == MVT::i1)
26468         return std::make_pair(0U, &X86::GR8RegClass);
26469       if (VT == MVT::i16)
26470         return std::make_pair(0U, &X86::GR16RegClass);
26471       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26472         return std::make_pair(0U, &X86::GR32RegClass);
26473       return std::make_pair(0U, &X86::GR64RegClass);
26474     case 'R':   // LEGACY_REGS
26475       if (VT == MVT::i8 || VT == MVT::i1)
26476         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26477       if (VT == MVT::i16)
26478         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26479       if (VT == MVT::i32 || !Subtarget->is64Bit())
26480         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26481       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26482     case 'f':  // FP Stack registers.
26483       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26484       // value to the correct fpstack register class.
26485       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26486         return std::make_pair(0U, &X86::RFP32RegClass);
26487       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26488         return std::make_pair(0U, &X86::RFP64RegClass);
26489       return std::make_pair(0U, &X86::RFP80RegClass);
26490     case 'y':   // MMX_REGS if MMX allowed.
26491       if (!Subtarget->hasMMX()) break;
26492       return std::make_pair(0U, &X86::VR64RegClass);
26493     case 'Y':   // SSE_REGS if SSE2 allowed
26494       if (!Subtarget->hasSSE2()) break;
26495       // FALL THROUGH.
26496     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26497       if (!Subtarget->hasSSE1()) break;
26498
26499       switch (VT.SimpleTy) {
26500       default: break;
26501       // Scalar SSE types.
26502       case MVT::f32:
26503       case MVT::i32:
26504         return std::make_pair(0U, &X86::FR32RegClass);
26505       case MVT::f64:
26506       case MVT::i64:
26507         return std::make_pair(0U, &X86::FR64RegClass);
26508       // Vector types.
26509       case MVT::v16i8:
26510       case MVT::v8i16:
26511       case MVT::v4i32:
26512       case MVT::v2i64:
26513       case MVT::v4f32:
26514       case MVT::v2f64:
26515         return std::make_pair(0U, &X86::VR128RegClass);
26516       // AVX types.
26517       case MVT::v32i8:
26518       case MVT::v16i16:
26519       case MVT::v8i32:
26520       case MVT::v4i64:
26521       case MVT::v8f32:
26522       case MVT::v4f64:
26523         return std::make_pair(0U, &X86::VR256RegClass);
26524       case MVT::v8f64:
26525       case MVT::v16f32:
26526       case MVT::v16i32:
26527       case MVT::v8i64:
26528         return std::make_pair(0U, &X86::VR512RegClass);
26529       }
26530       break;
26531     }
26532   }
26533
26534   // Use the default implementation in TargetLowering to convert the register
26535   // constraint into a member of a register class.
26536   std::pair<unsigned, const TargetRegisterClass*> Res;
26537   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26538
26539   // Not found as a standard register?
26540   if (!Res.second) {
26541     // Map st(0) -> st(7) -> ST0
26542     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26543         tolower(Constraint[1]) == 's' &&
26544         tolower(Constraint[2]) == 't' &&
26545         Constraint[3] == '(' &&
26546         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26547         Constraint[5] == ')' &&
26548         Constraint[6] == '}') {
26549
26550       Res.first = X86::FP0+Constraint[4]-'0';
26551       Res.second = &X86::RFP80RegClass;
26552       return Res;
26553     }
26554
26555     // GCC allows "st(0)" to be called just plain "st".
26556     if (StringRef("{st}").equals_lower(Constraint)) {
26557       Res.first = X86::FP0;
26558       Res.second = &X86::RFP80RegClass;
26559       return Res;
26560     }
26561
26562     // flags -> EFLAGS
26563     if (StringRef("{flags}").equals_lower(Constraint)) {
26564       Res.first = X86::EFLAGS;
26565       Res.second = &X86::CCRRegClass;
26566       return Res;
26567     }
26568
26569     // 'A' means EAX + EDX.
26570     if (Constraint == "A") {
26571       Res.first = X86::EAX;
26572       Res.second = &X86::GR32_ADRegClass;
26573       return Res;
26574     }
26575     return Res;
26576   }
26577
26578   // Otherwise, check to see if this is a register class of the wrong value
26579   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26580   // turn into {ax},{dx}.
26581   // MVT::Other is used to specify clobber names.
26582   if (Res.second->hasType(VT) || VT == MVT::Other)
26583     return Res;   // Correct type already, nothing to do.
26584
26585   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26586   // return "eax". This should even work for things like getting 64bit integer
26587   // registers when given an f64 type.
26588   const TargetRegisterClass *Class = Res.second;
26589   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26590       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26591     unsigned Size = VT.getSizeInBits();
26592     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26593                                   : Size == 16 ? MVT::i16
26594                                   : Size == 32 ? MVT::i32
26595                                   : Size == 64 ? MVT::i64
26596                                   : MVT::Other;
26597     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26598     if (DestReg > 0) {
26599       Res.first = DestReg;
26600       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26601                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26602                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26603                  : &X86::GR64RegClass;
26604       assert(Res.second->contains(Res.first) && "Register in register class");
26605     } else {
26606       // No register found/type mismatch.
26607       Res.first = 0;
26608       Res.second = nullptr;
26609     }
26610   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26611              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26612              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26613              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26614              Class == &X86::VR512RegClass) {
26615     // Handle references to XMM physical registers that got mapped into the
26616     // wrong class.  This can happen with constraints like {xmm0} where the
26617     // target independent register mapper will just pick the first match it can
26618     // find, ignoring the required type.
26619
26620     if (VT == MVT::f32 || VT == MVT::i32)
26621       Res.second = &X86::FR32RegClass;
26622     else if (VT == MVT::f64 || VT == MVT::i64)
26623       Res.second = &X86::FR64RegClass;
26624     else if (X86::VR128RegClass.hasType(VT))
26625       Res.second = &X86::VR128RegClass;
26626     else if (X86::VR256RegClass.hasType(VT))
26627       Res.second = &X86::VR256RegClass;
26628     else if (X86::VR512RegClass.hasType(VT))
26629       Res.second = &X86::VR512RegClass;
26630     else {
26631       // Type mismatch and not a clobber: Return an error;
26632       Res.first = 0;
26633       Res.second = nullptr;
26634     }
26635   }
26636
26637   return Res;
26638 }
26639
26640 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26641                                             const AddrMode &AM, Type *Ty,
26642                                             unsigned AS) const {
26643   // Scaling factors are not free at all.
26644   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26645   // will take 2 allocations in the out of order engine instead of 1
26646   // for plain addressing mode, i.e. inst (reg1).
26647   // E.g.,
26648   // vaddps (%rsi,%drx), %ymm0, %ymm1
26649   // Requires two allocations (one for the load, one for the computation)
26650   // whereas:
26651   // vaddps (%rsi), %ymm0, %ymm1
26652   // Requires just 1 allocation, i.e., freeing allocations for other operations
26653   // and having less micro operations to execute.
26654   //
26655   // For some X86 architectures, this is even worse because for instance for
26656   // stores, the complex addressing mode forces the instruction to use the
26657   // "load" ports instead of the dedicated "store" port.
26658   // E.g., on Haswell:
26659   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26660   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26661   if (isLegalAddressingMode(DL, AM, Ty, AS))
26662     // Scale represents reg2 * scale, thus account for 1
26663     // as soon as we use a second register.
26664     return AM.Scale != 0;
26665   return -1;
26666 }
26667
26668 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
26669   // Integer division on x86 is expensive. However, when aggressively optimizing
26670   // for code size, we prefer to use a div instruction, as it is usually smaller
26671   // than the alternative sequence.
26672   // The exception to this is vector division. Since x86 doesn't have vector
26673   // integer division, leaving the division as-is is a loss even in terms of
26674   // size, because it will have to be scalarized, while the alternative code
26675   // sequence can be performed in vector form.
26676   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
26677                                    Attribute::MinSize);
26678   return OptSize && !VT.isVector();
26679 }