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 "X86IntrinsicsInfo.h"
21 #include "X86MachineFunctionInfo.h"
22 #include "X86TargetMachine.h"
23 #include "X86TargetObjectFile.h"
24 #include "llvm/ADT/SmallBitVector.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/Analysis/EHPersonalities.h"
30 #include "llvm/CodeGen/IntrinsicLowering.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/TargetLowering.h"
38 #include "llvm/CodeGen/WinEHFuncInfo.h"
39 #include "llvm/IR/CallSite.h"
40 #include "llvm/IR/CallingConv.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/DiagnosticInfo.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/GlobalAlias.h"
46 #include "llvm/IR/GlobalVariable.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/Intrinsics.h"
49 #include "llvm/MC/MCAsmInfo.h"
50 #include "llvm/MC/MCContext.h"
51 #include "llvm/MC/MCExpr.h"
52 #include "llvm/MC/MCSymbol.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/KnownBits.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Target/TargetOptions.h"
59 #include <algorithm>
60 #include <bitset>
61 #include <cctype>
62 #include <numeric>
63 using namespace llvm;
64 
65 #define DEBUG_TYPE "x86-isel"
66 
67 STATISTIC(NumTailCalls, "Number of tail calls");
68 
69 static cl::opt<bool> ExperimentalVectorWideningLegalization(
70     "x86-experimental-vector-widening-legalization", cl::init(false),
71     cl::desc("Enable an experimental vector type legalization through widening "
72              "rather than promotion."),
73     cl::Hidden);
74 
75 static cl::opt<int> ExperimentalPrefLoopAlignment(
76     "x86-experimental-pref-loop-alignment", cl::init(4),
77     cl::desc("Sets the preferable loop alignment for experiments "
78              "(the last x86-experimental-pref-loop-alignment bits"
79              " of the loop header PC will be 0)."),
80     cl::Hidden);
81 
82 static cl::opt<bool> MulConstantOptimization(
83     "mul-constant-optimization", cl::init(true),
84     cl::desc("Replace 'mul x, Const' with more effective instructions like "
85              "SHIFT, LEA, etc."),
86     cl::Hidden);
87 
88 /// Call this when the user attempts to do something unsupported, like
89 /// returning a double without SSE2 enabled on x86_64. This is not fatal, unlike
90 /// report_fatal_error, so calling code should attempt to recover without
91 /// crashing.
errorUnsupported(SelectionDAG & DAG,const SDLoc & dl,const char * Msg)92 static void errorUnsupported(SelectionDAG &DAG, const SDLoc &dl,
93                              const char *Msg) {
94   MachineFunction &MF = DAG.getMachineFunction();
95   DAG.getContext()->diagnose(
96       DiagnosticInfoUnsupported(MF.getFunction(), Msg, dl.getDebugLoc()));
97 }
98 
X86TargetLowering(const X86TargetMachine & TM,const X86Subtarget & STI)99 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
100                                      const X86Subtarget &STI)
101     : TargetLowering(TM), Subtarget(STI) {
102   bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
103   X86ScalarSSEf64 = Subtarget.hasSSE2();
104   X86ScalarSSEf32 = Subtarget.hasSSE1();
105   MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0));
106 
107   // Set up the TargetLowering object.
108 
109   // X86 is weird. It always uses i8 for shift amounts and setcc results.
110   setBooleanContents(ZeroOrOneBooleanContent);
111   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
112   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
113 
114   // For 64-bit, since we have so many registers, use the ILP scheduler.
115   // For 32-bit, use the register pressure specific scheduling.
116   // For Atom, always use ILP scheduling.
117   if (Subtarget.isAtom())
118     setSchedulingPreference(Sched::ILP);
119   else if (Subtarget.is64Bit())
120     setSchedulingPreference(Sched::ILP);
121   else
122     setSchedulingPreference(Sched::RegPressure);
123   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
124   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
125 
126   // Bypass expensive divides and use cheaper ones.
127   if (TM.getOptLevel() >= CodeGenOpt::Default) {
128     if (Subtarget.hasSlowDivide32())
129       addBypassSlowDiv(32, 8);
130     if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
131       addBypassSlowDiv(64, 32);
132   }
133 
134   if (Subtarget.isTargetKnownWindowsMSVC() ||
135       Subtarget.isTargetWindowsItanium()) {
136     // Setup Windows compiler runtime calls.
137     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
138     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
139     setLibcallName(RTLIB::SREM_I64, "_allrem");
140     setLibcallName(RTLIB::UREM_I64, "_aullrem");
141     setLibcallName(RTLIB::MUL_I64, "_allmul");
142     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
143     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
144     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
145     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
146     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
147   }
148 
149   if (Subtarget.isTargetDarwin()) {
150     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
151     setUseUnderscoreSetJmp(false);
152     setUseUnderscoreLongJmp(false);
153   } else if (Subtarget.isTargetWindowsGNU()) {
154     // MS runtime is weird: it exports _setjmp, but longjmp!
155     setUseUnderscoreSetJmp(true);
156     setUseUnderscoreLongJmp(false);
157   } else {
158     setUseUnderscoreSetJmp(true);
159     setUseUnderscoreLongJmp(true);
160   }
161 
162   // Set up the register classes.
163   addRegisterClass(MVT::i8, &X86::GR8RegClass);
164   addRegisterClass(MVT::i16, &X86::GR16RegClass);
165   addRegisterClass(MVT::i32, &X86::GR32RegClass);
166   if (Subtarget.is64Bit())
167     addRegisterClass(MVT::i64, &X86::GR64RegClass);
168 
169   for (MVT VT : MVT::integer_valuetypes())
170     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
171 
172   // We don't accept any truncstore of integer registers.
173   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
174   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
175   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
176   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
177   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
178   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
179 
180   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
181 
182   // SETOEQ and SETUNE require checking two conditions.
183   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
184   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
185   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
186   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
187   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
188   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
189 
190   // Integer absolute.
191   if (Subtarget.hasCMov()) {
192     setOperationAction(ISD::ABS            , MVT::i16  , Custom);
193     setOperationAction(ISD::ABS            , MVT::i32  , Custom);
194     if (Subtarget.is64Bit())
195       setOperationAction(ISD::ABS          , MVT::i64  , Custom);
196   }
197 
198   // Funnel shifts.
199   for (auto ShiftOp : {ISD::FSHL, ISD::FSHR}) {
200     setOperationAction(ShiftOp             , MVT::i16  , Custom);
201     setOperationAction(ShiftOp             , MVT::i32  , Custom);
202     if (Subtarget.is64Bit())
203       setOperationAction(ShiftOp           , MVT::i64  , Custom);
204   }
205 
206   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
207   // operation.
208   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
209   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
210   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
211 
212   if (Subtarget.is64Bit()) {
213     if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512())
214       // f32/f64 are legal, f80 is custom.
215       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
216     else
217       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
218     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
219   } else if (!Subtarget.useSoftFloat()) {
220     // We have an algorithm for SSE2->double, and we turn this into a
221     // 64-bit FILD followed by conditional FADD for other targets.
222     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
223     // We have an algorithm for SSE2, and we turn this into a 64-bit
224     // FILD or VCVTUSI2SS/SD for other targets.
225     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
226   } else {
227     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Expand);
228   }
229 
230   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
231   // this operation.
232   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
233   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
234 
235   if (!Subtarget.useSoftFloat()) {
236     // SSE has no i16 to fp conversion, only i32.
237     if (X86ScalarSSEf32) {
238       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
239       // f32 and f64 cases are Legal, f80 case is not
240       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
241     } else {
242       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
243       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
244     }
245   } else {
246     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
247     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Expand);
248   }
249 
250   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
251   // this operation.
252   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
253   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
254 
255   if (!Subtarget.useSoftFloat()) {
256     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
257     // are Legal, f80 is custom lowered.
258     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
259     setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
260 
261     if (X86ScalarSSEf32) {
262       setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
263       // f32 and f64 cases are Legal, f80 case is not
264       setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
265     } else {
266       setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
267       setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
268     }
269   } else {
270     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
271     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Expand);
272     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Expand);
273   }
274 
275   // Handle FP_TO_UINT by promoting the destination to a larger signed
276   // conversion.
277   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
278   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
279   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
280 
281   if (Subtarget.is64Bit()) {
282     if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
283       // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
284       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
285       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Custom);
286     } else {
287       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
288       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Expand);
289     }
290   } else if (!Subtarget.useSoftFloat()) {
291     // Since AVX is a superset of SSE3, only check for SSE here.
292     if (Subtarget.hasSSE1() && !Subtarget.hasSSE3())
293       // Expand FP_TO_UINT into a select.
294       // FIXME: We would like to use a Custom expander here eventually to do
295       // the optimal thing for SSE vs. the default expansion in the legalizer.
296       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
297     else
298       // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
299       // With SSE3 we can use fisttpll to convert to a signed i64; without
300       // SSE, we're stuck with a fistpll.
301       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
302 
303     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
304   }
305 
306   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
307   if (!X86ScalarSSEf64) {
308     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
309     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
310     if (Subtarget.is64Bit()) {
311       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
312       // Without SSE, i64->f64 goes through memory.
313       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
314     }
315   } else if (!Subtarget.is64Bit())
316     setOperationAction(ISD::BITCAST      , MVT::i64  , Custom);
317 
318   // Scalar integer divide and remainder are lowered to use operations that
319   // produce two results, to match the available instructions. This exposes
320   // the two-result form to trivial CSE, which is able to combine x/y and x%y
321   // into a single instruction.
322   //
323   // Scalar integer multiply-high is also lowered to use two-result
324   // operations, to match the available instructions. However, plain multiply
325   // (low) operations are left as Legal, as there are single-result
326   // instructions for this in x86. Using the two-result multiply instructions
327   // when both high and low results are needed must be arranged by dagcombine.
328   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
329     setOperationAction(ISD::MULHS, VT, Expand);
330     setOperationAction(ISD::MULHU, VT, Expand);
331     setOperationAction(ISD::SDIV, VT, Expand);
332     setOperationAction(ISD::UDIV, VT, Expand);
333     setOperationAction(ISD::SREM, VT, Expand);
334     setOperationAction(ISD::UREM, VT, Expand);
335   }
336 
337   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
338   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
339   for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
340                    MVT::i8,  MVT::i16, MVT::i32, MVT::i64 }) {
341     setOperationAction(ISD::BR_CC,     VT, Expand);
342     setOperationAction(ISD::SELECT_CC, VT, Expand);
343   }
344   if (Subtarget.is64Bit())
345     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
346   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
347   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
348   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
349   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
350 
351   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
352   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
353   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
354   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
355 
356   // Promote the i8 variants and force them on up to i32 which has a shorter
357   // encoding.
358   setOperationPromotedToType(ISD::CTTZ           , MVT::i8   , MVT::i32);
359   setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
360   if (!Subtarget.hasBMI()) {
361     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
362     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
363     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Legal);
364     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Legal);
365     if (Subtarget.is64Bit()) {
366       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
367       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Legal);
368     }
369   }
370 
371   if (Subtarget.hasLZCNT()) {
372     // When promoting the i8 variants, force them to i32 for a shorter
373     // encoding.
374     setOperationPromotedToType(ISD::CTLZ           , MVT::i8   , MVT::i32);
375     setOperationPromotedToType(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
376   } else {
377     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
378     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
379     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
380     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
381     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
382     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
383     if (Subtarget.is64Bit()) {
384       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
385       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
386     }
387   }
388 
389   // Special handling for half-precision floating point conversions.
390   // If we don't have F16C support, then lower half float conversions
391   // into library calls.
392   if (Subtarget.useSoftFloat() || !Subtarget.hasF16C()) {
393     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
394     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
395   }
396 
397   // There's never any support for operations beyond MVT::f32.
398   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
399   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
400   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
401   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
402 
403   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
404   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
405   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
406   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
407   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
408   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
409 
410   if (Subtarget.hasPOPCNT()) {
411     setOperationPromotedToType(ISD::CTPOP, MVT::i8, MVT::i32);
412   } else {
413     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
414     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
415     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
416     if (Subtarget.is64Bit())
417       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
418   }
419 
420   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
421 
422   if (!Subtarget.hasMOVBE())
423     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
424 
425   // These should be promoted to a larger select which is supported.
426   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
427   // X86 wants to expand cmov itself.
428   for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
429     setOperationAction(ISD::SELECT, VT, Custom);
430     setOperationAction(ISD::SETCC, VT, Custom);
431   }
432   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
433     if (VT == MVT::i64 && !Subtarget.is64Bit())
434       continue;
435     setOperationAction(ISD::SELECT, VT, Custom);
436     setOperationAction(ISD::SETCC,  VT, Custom);
437   }
438 
439   // Custom action for SELECT MMX and expand action for SELECT_CC MMX
440   setOperationAction(ISD::SELECT, MVT::x86mmx, Custom);
441   setOperationAction(ISD::SELECT_CC, MVT::x86mmx, Expand);
442 
443   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
444   // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
445   // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
446   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
447   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
448   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
449   if (TM.Options.ExceptionModel == ExceptionHandling::SjLj)
450     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
451 
452   // Darwin ABI issue.
453   for (auto VT : { MVT::i32, MVT::i64 }) {
454     if (VT == MVT::i64 && !Subtarget.is64Bit())
455       continue;
456     setOperationAction(ISD::ConstantPool    , VT, Custom);
457     setOperationAction(ISD::JumpTable       , VT, Custom);
458     setOperationAction(ISD::GlobalAddress   , VT, Custom);
459     setOperationAction(ISD::GlobalTLSAddress, VT, Custom);
460     setOperationAction(ISD::ExternalSymbol  , VT, Custom);
461     setOperationAction(ISD::BlockAddress    , VT, Custom);
462   }
463 
464   // 64-bit shl, sra, srl (iff 32-bit x86)
465   for (auto VT : { MVT::i32, MVT::i64 }) {
466     if (VT == MVT::i64 && !Subtarget.is64Bit())
467       continue;
468     setOperationAction(ISD::SHL_PARTS, VT, Custom);
469     setOperationAction(ISD::SRA_PARTS, VT, Custom);
470     setOperationAction(ISD::SRL_PARTS, VT, Custom);
471   }
472 
473   if (Subtarget.hasSSEPrefetch() || Subtarget.has3DNow())
474     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
475 
476   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
477 
478   // Expand certain atomics
479   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
480     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
481     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
482     setOperationAction(ISD::ATOMIC_LOAD_ADD, VT, Custom);
483     setOperationAction(ISD::ATOMIC_LOAD_OR, VT, Custom);
484     setOperationAction(ISD::ATOMIC_LOAD_XOR, VT, Custom);
485     setOperationAction(ISD::ATOMIC_LOAD_AND, VT, Custom);
486     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
487   }
488 
489   if (Subtarget.hasCmpxchg16b()) {
490     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
491   }
492 
493   // FIXME - use subtarget debug flags
494   if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
495       !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
496       TM.Options.ExceptionModel != ExceptionHandling::SjLj) {
497     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
498   }
499 
500   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
501   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
502 
503   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
504   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
505 
506   setOperationAction(ISD::TRAP, MVT::Other, Legal);
507   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
508 
509   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
510   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
511   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
512   bool Is64Bit = Subtarget.is64Bit();
513   setOperationAction(ISD::VAARG,  MVT::Other, Is64Bit ? Custom : Expand);
514   setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
515 
516   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
517   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
518 
519   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
520 
521   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
522   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
523   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
524 
525   if (!Subtarget.useSoftFloat() && X86ScalarSSEf64) {
526     // f32 and f64 use SSE.
527     // Set up the FP register classes.
528     addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
529                                                      : &X86::FR32RegClass);
530     addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
531                                                      : &X86::FR64RegClass);
532 
533     for (auto VT : { MVT::f32, MVT::f64 }) {
534       // Use ANDPD to simulate FABS.
535       setOperationAction(ISD::FABS, VT, Custom);
536 
537       // Use XORP to simulate FNEG.
538       setOperationAction(ISD::FNEG, VT, Custom);
539 
540       // Use ANDPD and ORPD to simulate FCOPYSIGN.
541       setOperationAction(ISD::FCOPYSIGN, VT, Custom);
542 
543       // These might be better off as horizontal vector ops.
544       setOperationAction(ISD::FADD, VT, Custom);
545       setOperationAction(ISD::FSUB, VT, Custom);
546 
547       // We don't support sin/cos/fmod
548       setOperationAction(ISD::FSIN   , VT, Expand);
549       setOperationAction(ISD::FCOS   , VT, Expand);
550       setOperationAction(ISD::FSINCOS, VT, Expand);
551     }
552 
553     // Lower this to MOVMSK plus an AND.
554     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
555     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
556 
557   } else if (!useSoftFloat() && X86ScalarSSEf32 && (UseX87 || Is64Bit)) {
558     // Use SSE for f32, x87 for f64.
559     // Set up the FP register classes.
560     addRegisterClass(MVT::f32, &X86::FR32RegClass);
561     if (UseX87)
562       addRegisterClass(MVT::f64, &X86::RFP64RegClass);
563 
564     // Use ANDPS to simulate FABS.
565     setOperationAction(ISD::FABS , MVT::f32, Custom);
566 
567     // Use XORP to simulate FNEG.
568     setOperationAction(ISD::FNEG , MVT::f32, Custom);
569 
570     if (UseX87)
571       setOperationAction(ISD::UNDEF, MVT::f64, Expand);
572 
573     // Use ANDPS and ORPS to simulate FCOPYSIGN.
574     if (UseX87)
575       setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
576     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
577 
578     // We don't support sin/cos/fmod
579     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
580     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
581     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
582 
583     if (UseX87) {
584       // Always expand sin/cos functions even though x87 has an instruction.
585       setOperationAction(ISD::FSIN, MVT::f64, Expand);
586       setOperationAction(ISD::FCOS, MVT::f64, Expand);
587       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
588     }
589   } else if (UseX87) {
590     // f32 and f64 in x87.
591     // Set up the FP register classes.
592     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
593     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
594 
595     for (auto VT : { MVT::f32, MVT::f64 }) {
596       setOperationAction(ISD::UNDEF,     VT, Expand);
597       setOperationAction(ISD::FCOPYSIGN, VT, Expand);
598 
599       // Always expand sin/cos functions even though x87 has an instruction.
600       setOperationAction(ISD::FSIN   , VT, Expand);
601       setOperationAction(ISD::FCOS   , VT, Expand);
602       setOperationAction(ISD::FSINCOS, VT, Expand);
603     }
604   }
605 
606   // Expand FP32 immediates into loads from the stack, save special cases.
607   if (isTypeLegal(MVT::f32)) {
608     if (UseX87 && (getRegClassFor(MVT::f32) == &X86::RFP32RegClass)) {
609       addLegalFPImmediate(APFloat(+0.0f)); // FLD0
610       addLegalFPImmediate(APFloat(+1.0f)); // FLD1
611       addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
612       addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
613     } else // SSE immediates.
614       addLegalFPImmediate(APFloat(+0.0f)); // xorps
615   }
616   // Expand FP64 immediates into loads from the stack, save special cases.
617   if (isTypeLegal(MVT::f64)) {
618     if (UseX87 && getRegClassFor(MVT::f64) == &X86::RFP64RegClass) {
619       addLegalFPImmediate(APFloat(+0.0)); // FLD0
620       addLegalFPImmediate(APFloat(+1.0)); // FLD1
621       addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
622       addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
623     } else // SSE immediates.
624       addLegalFPImmediate(APFloat(+0.0)); // xorpd
625   }
626 
627   // We don't support FMA.
628   setOperationAction(ISD::FMA, MVT::f64, Expand);
629   setOperationAction(ISD::FMA, MVT::f32, Expand);
630 
631   // Long double always uses X87, except f128 in MMX.
632   if (UseX87) {
633     if (Subtarget.is64Bit() && Subtarget.hasMMX()) {
634       addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
635                                                      : &X86::VR128RegClass);
636       ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
637       setOperationAction(ISD::FABS , MVT::f128, Custom);
638       setOperationAction(ISD::FNEG , MVT::f128, Custom);
639       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
640     }
641 
642     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
643     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
644     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
645     {
646       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended());
647       addLegalFPImmediate(TmpFlt);  // FLD0
648       TmpFlt.changeSign();
649       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
650 
651       bool ignored;
652       APFloat TmpFlt2(+1.0);
653       TmpFlt2.convert(APFloat::x87DoubleExtended(), APFloat::rmNearestTiesToEven,
654                       &ignored);
655       addLegalFPImmediate(TmpFlt2);  // FLD1
656       TmpFlt2.changeSign();
657       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
658     }
659 
660     // Always expand sin/cos functions even though x87 has an instruction.
661     setOperationAction(ISD::FSIN   , MVT::f80, Expand);
662     setOperationAction(ISD::FCOS   , MVT::f80, Expand);
663     setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
664 
665     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
666     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
667     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
668     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
669     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
670     setOperationAction(ISD::FMA, MVT::f80, Expand);
671   }
672 
673   // Always use a library call for pow.
674   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
675   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
676   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
677 
678   setOperationAction(ISD::FLOG, MVT::f80, Expand);
679   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
680   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
681   setOperationAction(ISD::FEXP, MVT::f80, Expand);
682   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
683   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
684   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
685 
686   // Some FP actions are always expanded for vector types.
687   for (auto VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32,
688                    MVT::v2f64, MVT::v4f64, MVT::v8f64 }) {
689     setOperationAction(ISD::FSIN,      VT, Expand);
690     setOperationAction(ISD::FSINCOS,   VT, Expand);
691     setOperationAction(ISD::FCOS,      VT, Expand);
692     setOperationAction(ISD::FREM,      VT, Expand);
693     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
694     setOperationAction(ISD::FPOW,      VT, Expand);
695     setOperationAction(ISD::FLOG,      VT, Expand);
696     setOperationAction(ISD::FLOG2,     VT, Expand);
697     setOperationAction(ISD::FLOG10,    VT, Expand);
698     setOperationAction(ISD::FEXP,      VT, Expand);
699     setOperationAction(ISD::FEXP2,     VT, Expand);
700   }
701 
702   // First set operation action for all vector types to either promote
703   // (for widening) or expand (for scalarization). Then we will selectively
704   // turn on ones that can be effectively codegen'd.
705   for (MVT VT : MVT::vector_valuetypes()) {
706     setOperationAction(ISD::SDIV, VT, Expand);
707     setOperationAction(ISD::UDIV, VT, Expand);
708     setOperationAction(ISD::SREM, VT, Expand);
709     setOperationAction(ISD::UREM, VT, Expand);
710     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
711     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
712     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
713     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
714     setOperationAction(ISD::FMA,  VT, Expand);
715     setOperationAction(ISD::FFLOOR, VT, Expand);
716     setOperationAction(ISD::FCEIL, VT, Expand);
717     setOperationAction(ISD::FTRUNC, VT, Expand);
718     setOperationAction(ISD::FRINT, VT, Expand);
719     setOperationAction(ISD::FNEARBYINT, VT, Expand);
720     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
721     setOperationAction(ISD::MULHS, VT, Expand);
722     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
723     setOperationAction(ISD::MULHU, VT, Expand);
724     setOperationAction(ISD::SDIVREM, VT, Expand);
725     setOperationAction(ISD::UDIVREM, VT, Expand);
726     setOperationAction(ISD::CTPOP, VT, Expand);
727     setOperationAction(ISD::CTTZ, VT, Expand);
728     setOperationAction(ISD::CTLZ, VT, Expand);
729     setOperationAction(ISD::ROTL, VT, Expand);
730     setOperationAction(ISD::ROTR, VT, Expand);
731     setOperationAction(ISD::BSWAP, VT, Expand);
732     setOperationAction(ISD::SETCC, VT, Expand);
733     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
734     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
735     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
736     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
737     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
738     setOperationAction(ISD::TRUNCATE, VT, Expand);
739     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
740     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
741     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
742     setOperationAction(ISD::SELECT_CC, VT, Expand);
743     for (MVT InnerVT : MVT::vector_valuetypes()) {
744       setTruncStoreAction(InnerVT, VT, Expand);
745 
746       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
747       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
748 
749       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
750       // types, we have to deal with them whether we ask for Expansion or not.
751       // Setting Expand causes its own optimisation problems though, so leave
752       // them legal.
753       if (VT.getVectorElementType() == MVT::i1)
754         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
755 
756       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
757       // split/scalarized right now.
758       if (VT.getVectorElementType() == MVT::f16)
759         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
760     }
761   }
762 
763   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
764   // with -msoft-float, disable use of MMX as well.
765   if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
766     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
767     // No operations on x86mmx supported, everything uses intrinsics.
768   }
769 
770   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
771     addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
772                                                     : &X86::VR128RegClass);
773 
774     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
775     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
776     setOperationAction(ISD::FCOPYSIGN,          MVT::v4f32, Custom);
777     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
778     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
779     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
780     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
781     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
782     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
783   }
784 
785   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
786     addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
787                                                     : &X86::VR128RegClass);
788 
789     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
790     // registers cannot be used even for integer operations.
791     addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
792                                                     : &X86::VR128RegClass);
793     addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
794                                                     : &X86::VR128RegClass);
795     addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
796                                                     : &X86::VR128RegClass);
797     addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
798                                                     : &X86::VR128RegClass);
799 
800     for (auto VT : { MVT::v2i8, MVT::v4i8, MVT::v8i8,
801                      MVT::v2i16, MVT::v4i16, MVT::v2i32 }) {
802       setOperationAction(ISD::SDIV, VT, Custom);
803       setOperationAction(ISD::SREM, VT, Custom);
804       setOperationAction(ISD::UDIV, VT, Custom);
805       setOperationAction(ISD::UREM, VT, Custom);
806     }
807 
808     setOperationAction(ISD::MUL,                MVT::v2i8,  Custom);
809     setOperationAction(ISD::MUL,                MVT::v2i16, Custom);
810     setOperationAction(ISD::MUL,                MVT::v2i32, Custom);
811     setOperationAction(ISD::MUL,                MVT::v4i8,  Custom);
812     setOperationAction(ISD::MUL,                MVT::v4i16, Custom);
813     setOperationAction(ISD::MUL,                MVT::v8i8,  Custom);
814 
815     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
816     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
817     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
818     setOperationAction(ISD::MULHU,              MVT::v4i32, Custom);
819     setOperationAction(ISD::MULHS,              MVT::v4i32, Custom);
820     setOperationAction(ISD::MULHU,              MVT::v16i8, Custom);
821     setOperationAction(ISD::MULHS,              MVT::v16i8, Custom);
822     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
823     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
824     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
825     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
826     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
827     setOperationAction(ISD::FCOPYSIGN,          MVT::v2f64, Custom);
828 
829     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
830       setOperationAction(ISD::SMAX, VT, VT == MVT::v8i16 ? Legal : Custom);
831       setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
832       setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
833       setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
834     }
835 
836     setOperationAction(ISD::UADDSAT,            MVT::v16i8, Legal);
837     setOperationAction(ISD::SADDSAT,            MVT::v16i8, Legal);
838     setOperationAction(ISD::USUBSAT,            MVT::v16i8, Legal);
839     setOperationAction(ISD::SSUBSAT,            MVT::v16i8, Legal);
840     setOperationAction(ISD::UADDSAT,            MVT::v8i16, Legal);
841     setOperationAction(ISD::SADDSAT,            MVT::v8i16, Legal);
842     setOperationAction(ISD::USUBSAT,            MVT::v8i16, Legal);
843     setOperationAction(ISD::SSUBSAT,            MVT::v8i16, Legal);
844 
845     if (!ExperimentalVectorWideningLegalization) {
846       // Use widening instead of promotion.
847       for (auto VT : { MVT::v8i8, MVT::v4i8, MVT::v2i8,
848                        MVT::v4i16, MVT::v2i16 }) {
849         setOperationAction(ISD::UADDSAT, VT, Custom);
850         setOperationAction(ISD::SADDSAT, VT, Custom);
851         setOperationAction(ISD::USUBSAT, VT, Custom);
852         setOperationAction(ISD::SSUBSAT, VT, Custom);
853       }
854     }
855 
856     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
857     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
858     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
859 
860     // Provide custom widening for v2f32 setcc. This is really for VLX when
861     // setcc result type returns v2i1/v4i1 vector for v2f32/v4f32 leading to
862     // type legalization changing the result type to v4i1 during widening.
863     // It works fine for SSE2 and is probably faster so no need to qualify with
864     // VLX support.
865     setOperationAction(ISD::SETCC,               MVT::v2i32, Custom);
866 
867     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
868       setOperationAction(ISD::SETCC,              VT, Custom);
869       setOperationAction(ISD::CTPOP,              VT, Custom);
870       setOperationAction(ISD::ABS,                VT, Custom);
871 
872       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
873       // setcc all the way to isel and prefer SETGT in some isel patterns.
874       setCondCodeAction(ISD::SETLT, VT, Custom);
875       setCondCodeAction(ISD::SETLE, VT, Custom);
876     }
877 
878     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
879       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
880       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
881       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
882       setOperationAction(ISD::VSELECT,            VT, Custom);
883       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
884     }
885 
886     // We support custom legalizing of sext and anyext loads for specific
887     // memory vector types which we can load as a scalar (or sequence of
888     // scalars) and extend in-register to a legal 128-bit vector type. For sext
889     // loads these must work with a single scalar load.
890     for (MVT VT : MVT::integer_vector_valuetypes()) {
891       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
892       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
893       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
894       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
895       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
896       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
897     }
898 
899     for (auto VT : { MVT::v2f64, MVT::v2i64 }) {
900       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
901       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
902       setOperationAction(ISD::VSELECT,            VT, Custom);
903 
904       if (VT == MVT::v2i64 && !Subtarget.is64Bit())
905         continue;
906 
907       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
908       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
909     }
910 
911     // Custom lower v2i64 and v2f64 selects.
912     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
913     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
914     setOperationAction(ISD::SELECT,             MVT::v4i32, Custom);
915     setOperationAction(ISD::SELECT,             MVT::v8i16, Custom);
916     setOperationAction(ISD::SELECT,             MVT::v16i8, Custom);
917 
918     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
919     setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
920     setOperationAction(ISD::FP_TO_SINT,         MVT::v2i16, Custom);
921 
922     // Custom legalize these to avoid over promotion or custom promotion.
923     setOperationAction(ISD::FP_TO_SINT,         MVT::v2i8,  Custom);
924     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i8,  Custom);
925     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i8,  Custom);
926     setOperationAction(ISD::FP_TO_SINT,         MVT::v2i16, Custom);
927     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i16, Custom);
928     setOperationAction(ISD::FP_TO_UINT,         MVT::v2i8,  Custom);
929     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i8,  Custom);
930     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i8,  Custom);
931     setOperationAction(ISD::FP_TO_UINT,         MVT::v2i16, Custom);
932     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i16, Custom);
933 
934     // By marking FP_TO_SINT v8i16 as Custom, will trick type legalization into
935     // promoting v8i8 FP_TO_UINT into FP_TO_SINT. When the v8i16 FP_TO_SINT is
936     // split again based on the input type, this will cause an AssertSExt i16 to
937     // be emitted instead of an AssertZExt. This will allow packssdw followed by
938     // packuswb to be used to truncate to v8i8. This is necessary since packusdw
939     // isn't available until sse4.1.
940     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
941 
942     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
943     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
944 
945     setOperationAction(ISD::UINT_TO_FP,         MVT::v2i32, Custom);
946 
947     // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
948     setOperationAction(ISD::UINT_TO_FP,         MVT::v2f32, Custom);
949 
950     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
951     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
952 
953     for (MVT VT : MVT::fp_vector_valuetypes())
954       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
955 
956     // We want to legalize this to an f64 load rather than an i64 load on
957     // 64-bit targets and two 32-bit loads on a 32-bit target. Similar for
958     // store.
959     setOperationAction(ISD::LOAD,               MVT::v2f32, Custom);
960     setOperationAction(ISD::LOAD,               MVT::v2i32, Custom);
961     setOperationAction(ISD::LOAD,               MVT::v4i16, Custom);
962     setOperationAction(ISD::LOAD,               MVT::v8i8,  Custom);
963     setOperationAction(ISD::STORE,              MVT::v2f32, Custom);
964     setOperationAction(ISD::STORE,              MVT::v2i32, Custom);
965     setOperationAction(ISD::STORE,              MVT::v4i16, Custom);
966     setOperationAction(ISD::STORE,              MVT::v8i8,  Custom);
967 
968     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
969     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
970     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
971     if (!Subtarget.hasAVX512())
972       setOperationAction(ISD::BITCAST, MVT::v16i1, Custom);
973 
974     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
975     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
976     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
977 
978     if (ExperimentalVectorWideningLegalization) {
979       setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
980 
981       setOperationAction(ISD::TRUNCATE,    MVT::v2i8,  Custom);
982       setOperationAction(ISD::TRUNCATE,    MVT::v2i16, Custom);
983       setOperationAction(ISD::TRUNCATE,    MVT::v2i32, Custom);
984       setOperationAction(ISD::TRUNCATE,    MVT::v4i8,  Custom);
985       setOperationAction(ISD::TRUNCATE,    MVT::v4i16, Custom);
986       setOperationAction(ISD::TRUNCATE,    MVT::v8i8,  Custom);
987     } else {
988       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i64, Custom);
989     }
990 
991     // In the customized shift lowering, the legal v4i32/v2i64 cases
992     // in AVX2 will be recognized.
993     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
994       setOperationAction(ISD::SRL,              VT, Custom);
995       setOperationAction(ISD::SHL,              VT, Custom);
996       setOperationAction(ISD::SRA,              VT, Custom);
997     }
998 
999     setOperationAction(ISD::ROTL,               MVT::v4i32, Custom);
1000     setOperationAction(ISD::ROTL,               MVT::v8i16, Custom);
1001 
1002     // With AVX512, expanding (and promoting the shifts) is better.
1003     if (!Subtarget.hasAVX512())
1004       setOperationAction(ISD::ROTL,             MVT::v16i8, Custom);
1005   }
1006 
1007   if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
1008     setOperationAction(ISD::ABS,                MVT::v16i8, Legal);
1009     setOperationAction(ISD::ABS,                MVT::v8i16, Legal);
1010     setOperationAction(ISD::ABS,                MVT::v4i32, Legal);
1011     setOperationAction(ISD::BITREVERSE,         MVT::v16i8, Custom);
1012     setOperationAction(ISD::CTLZ,               MVT::v16i8, Custom);
1013     setOperationAction(ISD::CTLZ,               MVT::v8i16, Custom);
1014     setOperationAction(ISD::CTLZ,               MVT::v4i32, Custom);
1015     setOperationAction(ISD::CTLZ,               MVT::v2i64, Custom);
1016 
1017     // These might be better off as horizontal vector ops.
1018     setOperationAction(ISD::ADD,                MVT::i16, Custom);
1019     setOperationAction(ISD::ADD,                MVT::i32, Custom);
1020     setOperationAction(ISD::SUB,                MVT::i16, Custom);
1021     setOperationAction(ISD::SUB,                MVT::i32, Custom);
1022   }
1023 
1024   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
1025     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1026       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
1027       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
1028       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
1029       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
1030       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
1031     }
1032 
1033     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
1034     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
1035     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
1036     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
1037     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
1038     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
1039     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
1040     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
1041 
1042     // FIXME: Do we need to handle scalar-to-vector here?
1043     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1044 
1045     // We directly match byte blends in the backend as they match the VSELECT
1046     // condition form.
1047     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1048 
1049     // SSE41 brings specific instructions for doing vector sign extend even in
1050     // cases where we don't have SRA.
1051     for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1052       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Legal);
1053       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Legal);
1054     }
1055 
1056     if (!ExperimentalVectorWideningLegalization) {
1057       // Avoid narrow result types when widening. The legal types are listed
1058       // in the next loop.
1059       for (MVT VT : MVT::integer_vector_valuetypes()) {
1060         setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
1061         setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
1062         setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
1063       }
1064     }
1065 
1066     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1067     for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1068       setLoadExtAction(LoadExtOp, MVT::v8i16, MVT::v8i8,  Legal);
1069       setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i8,  Legal);
1070       if (!ExperimentalVectorWideningLegalization)
1071         setLoadExtAction(LoadExtOp, MVT::v2i32, MVT::v2i8,  Legal);
1072       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i8,  Legal);
1073       setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i16, Legal);
1074       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i16, Legal);
1075       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i32, Legal);
1076     }
1077 
1078     // i8 vectors are custom because the source register and source
1079     // source memory operand types are not the same width.
1080     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1081   }
1082 
1083   if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
1084     for (auto VT : { MVT::v16i8, MVT::v8i16,  MVT::v4i32, MVT::v2i64,
1085                      MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
1086       setOperationAction(ISD::ROTL, VT, Custom);
1087 
1088     // XOP can efficiently perform BITREVERSE with VPPERM.
1089     for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
1090       setOperationAction(ISD::BITREVERSE, VT, Custom);
1091 
1092     for (auto VT : { MVT::v16i8, MVT::v8i16,  MVT::v4i32, MVT::v2i64,
1093                      MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
1094       setOperationAction(ISD::BITREVERSE, VT, Custom);
1095   }
1096 
1097   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
1098     bool HasInt256 = Subtarget.hasInt256();
1099 
1100     addRegisterClass(MVT::v32i8,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1101                                                      : &X86::VR256RegClass);
1102     addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1103                                                      : &X86::VR256RegClass);
1104     addRegisterClass(MVT::v8i32,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1105                                                      : &X86::VR256RegClass);
1106     addRegisterClass(MVT::v8f32,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1107                                                      : &X86::VR256RegClass);
1108     addRegisterClass(MVT::v4i64,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1109                                                      : &X86::VR256RegClass);
1110     addRegisterClass(MVT::v4f64,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1111                                                      : &X86::VR256RegClass);
1112 
1113     for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1114       setOperationAction(ISD::FFLOOR,     VT, Legal);
1115       setOperationAction(ISD::FCEIL,      VT, Legal);
1116       setOperationAction(ISD::FTRUNC,     VT, Legal);
1117       setOperationAction(ISD::FRINT,      VT, Legal);
1118       setOperationAction(ISD::FNEARBYINT, VT, Legal);
1119       setOperationAction(ISD::FNEG,       VT, Custom);
1120       setOperationAction(ISD::FABS,       VT, Custom);
1121       setOperationAction(ISD::FCOPYSIGN,  VT, Custom);
1122     }
1123 
1124     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1125     // even though v8i16 is a legal type.
1126     setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1127     setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1128     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1129 
1130     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1131     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1132 
1133     if (!Subtarget.hasAVX512())
1134       setOperationAction(ISD::BITCAST, MVT::v32i1, Custom);
1135 
1136     for (MVT VT : MVT::fp_vector_valuetypes())
1137       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1138 
1139     // In the customized shift lowering, the legal v8i32/v4i64 cases
1140     // in AVX2 will be recognized.
1141     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1142       setOperationAction(ISD::SRL, VT, Custom);
1143       setOperationAction(ISD::SHL, VT, Custom);
1144       setOperationAction(ISD::SRA, VT, Custom);
1145     }
1146 
1147     if (ExperimentalVectorWideningLegalization) {
1148       // These types need custom splitting if their input is a 128-bit vector.
1149       setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i64,  Custom);
1150       setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i32, Custom);
1151       setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i64,  Custom);
1152       setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i32, Custom);
1153     }
1154 
1155     setOperationAction(ISD::ROTL,              MVT::v8i32,  Custom);
1156     setOperationAction(ISD::ROTL,              MVT::v16i16, Custom);
1157 
1158     // With BWI, expanding (and promoting the shifts) is the better.
1159     if (!Subtarget.hasBWI())
1160       setOperationAction(ISD::ROTL,            MVT::v32i8,  Custom);
1161 
1162     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1163     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1164     setOperationAction(ISD::SELECT,            MVT::v8i32, Custom);
1165     setOperationAction(ISD::SELECT,            MVT::v16i16, Custom);
1166     setOperationAction(ISD::SELECT,            MVT::v32i8, Custom);
1167     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1168 
1169     for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1170       setOperationAction(ISD::SIGN_EXTEND,     VT, Custom);
1171       setOperationAction(ISD::ZERO_EXTEND,     VT, Custom);
1172       setOperationAction(ISD::ANY_EXTEND,      VT, Custom);
1173     }
1174 
1175     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1176     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1177     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1178     setOperationAction(ISD::BITREVERSE,        MVT::v32i8, Custom);
1179 
1180     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1181       setOperationAction(ISD::SETCC,           VT, Custom);
1182       setOperationAction(ISD::CTPOP,           VT, Custom);
1183       setOperationAction(ISD::CTLZ,            VT, Custom);
1184 
1185       // TODO - remove this once 256-bit X86ISD::ANDNP correctly split.
1186       setOperationAction(ISD::CTTZ,  VT, HasInt256 ? Expand : Custom);
1187 
1188       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1189       // setcc all the way to isel and prefer SETGT in some isel patterns.
1190       setCondCodeAction(ISD::SETLT, VT, Custom);
1191       setCondCodeAction(ISD::SETLE, VT, Custom);
1192     }
1193 
1194     if (Subtarget.hasAnyFMA()) {
1195       for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1196                        MVT::v2f64, MVT::v4f64 })
1197         setOperationAction(ISD::FMA, VT, Legal);
1198     }
1199 
1200     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1201       setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1202       setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1203     }
1204 
1205     setOperationAction(ISD::MUL,       MVT::v4i64,  Custom);
1206     setOperationAction(ISD::MUL,       MVT::v8i32,  HasInt256 ? Legal : Custom);
1207     setOperationAction(ISD::MUL,       MVT::v16i16, HasInt256 ? Legal : Custom);
1208     setOperationAction(ISD::MUL,       MVT::v32i8,  Custom);
1209 
1210     setOperationAction(ISD::MULHU,     MVT::v8i32,  Custom);
1211     setOperationAction(ISD::MULHS,     MVT::v8i32,  Custom);
1212     setOperationAction(ISD::MULHU,     MVT::v16i16, HasInt256 ? Legal : Custom);
1213     setOperationAction(ISD::MULHS,     MVT::v16i16, HasInt256 ? Legal : Custom);
1214     setOperationAction(ISD::MULHU,     MVT::v32i8,  Custom);
1215     setOperationAction(ISD::MULHS,     MVT::v32i8,  Custom);
1216 
1217     setOperationAction(ISD::ABS,       MVT::v4i64,  Custom);
1218     setOperationAction(ISD::SMAX,      MVT::v4i64,  Custom);
1219     setOperationAction(ISD::UMAX,      MVT::v4i64,  Custom);
1220     setOperationAction(ISD::SMIN,      MVT::v4i64,  Custom);
1221     setOperationAction(ISD::UMIN,      MVT::v4i64,  Custom);
1222 
1223     setOperationAction(ISD::UADDSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1224     setOperationAction(ISD::SADDSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1225     setOperationAction(ISD::USUBSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1226     setOperationAction(ISD::SSUBSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1227     setOperationAction(ISD::UADDSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1228     setOperationAction(ISD::SADDSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1229     setOperationAction(ISD::USUBSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1230     setOperationAction(ISD::SSUBSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1231 
1232     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1233       setOperationAction(ISD::ABS,  VT, HasInt256 ? Legal : Custom);
1234       setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1235       setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1236       setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1237       setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1238     }
1239 
1240     for (auto VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64}) {
1241       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1242       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1243     }
1244 
1245     if (HasInt256) {
1246       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1247       // when we have a 256bit-wide blend with immediate.
1248       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1249 
1250       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1251       for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1252         setLoadExtAction(LoadExtOp, MVT::v16i16, MVT::v16i8, Legal);
1253         setLoadExtAction(LoadExtOp, MVT::v8i32,  MVT::v8i8,  Legal);
1254         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i8,  Legal);
1255         setLoadExtAction(LoadExtOp, MVT::v8i32,  MVT::v8i16, Legal);
1256         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i16, Legal);
1257         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i32, Legal);
1258       }
1259     }
1260 
1261     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1262                      MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 }) {
1263       setOperationAction(ISD::MLOAD,  VT, Legal);
1264       setOperationAction(ISD::MSTORE, VT, Legal);
1265     }
1266 
1267     // Extract subvector is special because the value type
1268     // (result) is 128-bit but the source is 256-bit wide.
1269     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1270                      MVT::v4f32, MVT::v2f64 }) {
1271       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1272     }
1273 
1274     // Custom lower several nodes for 256-bit types.
1275     for (MVT VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1276                     MVT::v8f32, MVT::v4f64 }) {
1277       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1278       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1279       setOperationAction(ISD::VSELECT,            VT, Custom);
1280       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1281       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1282       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1283       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Legal);
1284       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1285     }
1286 
1287     if (HasInt256)
1288       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1289 
1290     if (HasInt256) {
1291       // Custom legalize 2x32 to get a little better code.
1292       setOperationAction(ISD::MGATHER, MVT::v2f32, Custom);
1293       setOperationAction(ISD::MGATHER, MVT::v2i32, Custom);
1294 
1295       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1296                        MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1297         setOperationAction(ISD::MGATHER,  VT, Custom);
1298     }
1299   }
1300 
1301   // This block controls legalization of the mask vector sizes that are
1302   // available with AVX512. 512-bit vectors are in a separate block controlled
1303   // by useAVX512Regs.
1304   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1305     addRegisterClass(MVT::v1i1,   &X86::VK1RegClass);
1306     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1307     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1308     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1309     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1310 
1311     setOperationAction(ISD::SELECT,             MVT::v1i1, Custom);
1312     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v1i1, Custom);
1313     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i1, Custom);
1314 
1315     setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v8i1,  MVT::v8i32);
1316     setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v8i1,  MVT::v8i32);
1317     setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v4i1,  MVT::v4i32);
1318     setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v4i1,  MVT::v4i32);
1319     setOperationAction(ISD::FP_TO_SINT,         MVT::v2i1,  Custom);
1320     setOperationAction(ISD::FP_TO_UINT,         MVT::v2i1,  Custom);
1321 
1322     // There is no byte sized k-register load or store without AVX512DQ.
1323     if (!Subtarget.hasDQI()) {
1324       setOperationAction(ISD::LOAD, MVT::v1i1, Custom);
1325       setOperationAction(ISD::LOAD, MVT::v2i1, Custom);
1326       setOperationAction(ISD::LOAD, MVT::v4i1, Custom);
1327       setOperationAction(ISD::LOAD, MVT::v8i1, Custom);
1328 
1329       setOperationAction(ISD::STORE, MVT::v1i1, Custom);
1330       setOperationAction(ISD::STORE, MVT::v2i1, Custom);
1331       setOperationAction(ISD::STORE, MVT::v4i1, Custom);
1332       setOperationAction(ISD::STORE, MVT::v8i1, Custom);
1333     }
1334 
1335     // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1336     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1337       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1338       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1339       setOperationAction(ISD::ANY_EXTEND,  VT, Custom);
1340     }
1341 
1342     for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1343       setOperationAction(ISD::ADD,              VT, Custom);
1344       setOperationAction(ISD::SUB,              VT, Custom);
1345       setOperationAction(ISD::MUL,              VT, Custom);
1346       setOperationAction(ISD::SETCC,            VT, Custom);
1347       setOperationAction(ISD::SELECT,           VT, Custom);
1348       setOperationAction(ISD::TRUNCATE,         VT, Custom);
1349       setOperationAction(ISD::UADDSAT,          VT, Custom);
1350       setOperationAction(ISD::SADDSAT,          VT, Custom);
1351       setOperationAction(ISD::USUBSAT,          VT, Custom);
1352       setOperationAction(ISD::SSUBSAT,          VT, Custom);
1353 
1354       setOperationAction(ISD::BUILD_VECTOR,     VT, Custom);
1355       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1356       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1357       setOperationAction(ISD::VECTOR_SHUFFLE,   VT,  Custom);
1358       setOperationAction(ISD::VSELECT,          VT,  Expand);
1359     }
1360 
1361     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Custom);
1362     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,  Custom);
1363     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1,  Custom);
1364     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v2i1,  Custom);
1365     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1,  Custom);
1366     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1,  Custom);
1367     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v16i1, Custom);
1368     for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1369       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1370   }
1371 
1372   // This block controls legalization for 512-bit operations with 32/64 bit
1373   // elements. 512-bits can be disabled based on prefer-vector-width and
1374   // required-vector-width function attributes.
1375   if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1376     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1377     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1378     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1379     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1380 
1381     for (MVT VT : MVT::fp_vector_valuetypes())
1382       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1383 
1384     for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1385       setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i8,  Legal);
1386       setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i16, Legal);
1387       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i8,   Legal);
1388       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i16,  Legal);
1389       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i32,  Legal);
1390     }
1391 
1392     for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1393       setOperationAction(ISD::FNEG,  VT, Custom);
1394       setOperationAction(ISD::FABS,  VT, Custom);
1395       setOperationAction(ISD::FMA,   VT, Legal);
1396       setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1397     }
1398 
1399     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1400     setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v16i16, MVT::v16i32);
1401     setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v16i8, MVT::v16i32);
1402     setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v16i1, MVT::v16i32);
1403     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1404     setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v16i1, MVT::v16i32);
1405     setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v16i8, MVT::v16i32);
1406     setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v16i16, MVT::v16i32);
1407     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1408     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1409 
1410     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1411     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1412     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1413     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1414     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1415 
1416     if (!Subtarget.hasVLX()) {
1417       // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1418       // to 512-bit rather than use the AVX2 instructions so that we can use
1419       // k-masks.
1420       for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1421            MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1422         setOperationAction(ISD::MLOAD,  VT, Custom);
1423         setOperationAction(ISD::MSTORE, VT, Custom);
1424       }
1425     }
1426 
1427     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1429     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1430     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1431     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1432     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1435 
1436     if (ExperimentalVectorWideningLegalization) {
1437       // Need to custom widen this if we don't have AVX512BW.
1438       setOperationAction(ISD::ANY_EXTEND,         MVT::v8i8, Custom);
1439       setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i8, Custom);
1440       setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i8, Custom);
1441     }
1442 
1443     for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1444       setOperationAction(ISD::FFLOOR,           VT, Legal);
1445       setOperationAction(ISD::FCEIL,            VT, Legal);
1446       setOperationAction(ISD::FTRUNC,           VT, Legal);
1447       setOperationAction(ISD::FRINT,            VT, Legal);
1448       setOperationAction(ISD::FNEARBYINT,       VT, Legal);
1449     }
1450 
1451     // Without BWI we need to use custom lowering to handle MVT::v64i8 input.
1452     for (auto VT : {MVT::v16i32, MVT::v8i64, MVT::v64i8}) {
1453       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1454       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1455     }
1456 
1457     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1458     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1459     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1460     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1461 
1462     setOperationAction(ISD::MUL,                MVT::v8i64, Custom);
1463     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1464 
1465     setOperationAction(ISD::MULHU,              MVT::v16i32,  Custom);
1466     setOperationAction(ISD::MULHS,              MVT::v16i32,  Custom);
1467 
1468     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1469     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1470     setOperationAction(ISD::SELECT,             MVT::v16i32, Custom);
1471     setOperationAction(ISD::SELECT,             MVT::v32i16, Custom);
1472     setOperationAction(ISD::SELECT,             MVT::v64i8, Custom);
1473     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1474 
1475     for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1476       setOperationAction(ISD::SMAX,             VT, Legal);
1477       setOperationAction(ISD::UMAX,             VT, Legal);
1478       setOperationAction(ISD::SMIN,             VT, Legal);
1479       setOperationAction(ISD::UMIN,             VT, Legal);
1480       setOperationAction(ISD::ABS,              VT, Legal);
1481       setOperationAction(ISD::SRL,              VT, Custom);
1482       setOperationAction(ISD::SHL,              VT, Custom);
1483       setOperationAction(ISD::SRA,              VT, Custom);
1484       setOperationAction(ISD::CTPOP,            VT, Custom);
1485       setOperationAction(ISD::ROTL,             VT, Custom);
1486       setOperationAction(ISD::ROTR,             VT, Custom);
1487       setOperationAction(ISD::SETCC,            VT, Custom);
1488 
1489       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1490       // setcc all the way to isel and prefer SETGT in some isel patterns.
1491       setCondCodeAction(ISD::SETLT, VT, Custom);
1492       setCondCodeAction(ISD::SETLE, VT, Custom);
1493     }
1494 
1495     if (Subtarget.hasDQI()) {
1496       setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1497       setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1498       setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1499       setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1500 
1501       setOperationAction(ISD::MUL,        MVT::v8i64, Legal);
1502     }
1503 
1504     if (Subtarget.hasCDI()) {
1505       // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1506       for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
1507         setOperationAction(ISD::CTLZ,            VT, Legal);
1508       }
1509     } // Subtarget.hasCDI()
1510 
1511     if (Subtarget.hasVPOPCNTDQ()) {
1512       for (auto VT : { MVT::v16i32, MVT::v8i64 })
1513         setOperationAction(ISD::CTPOP, VT, Legal);
1514     }
1515 
1516     // Extract subvector is special because the value type
1517     // (result) is 256-bit but the source is 512-bit wide.
1518     // 128-bit was made Legal under AVX1.
1519     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1520                      MVT::v8f32, MVT::v4f64 })
1521       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1522 
1523     for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1524       setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1525       setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1526       setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1527       setOperationAction(ISD::VSELECT,             VT, Custom);
1528       setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1529       setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1530       setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Legal);
1531       setOperationAction(ISD::MLOAD,               VT, Legal);
1532       setOperationAction(ISD::MSTORE,              VT, Legal);
1533       setOperationAction(ISD::MGATHER,             VT, Custom);
1534       setOperationAction(ISD::MSCATTER,            VT, Custom);
1535     }
1536     // Need to custom split v32i16/v64i8 bitcasts.
1537     if (!Subtarget.hasBWI()) {
1538       setOperationAction(ISD::BITCAST, MVT::v32i16, Custom);
1539       setOperationAction(ISD::BITCAST, MVT::v64i8,  Custom);
1540     }
1541 
1542     if (Subtarget.hasVBMI2()) {
1543       for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1544         setOperationAction(ISD::FSHL, VT, Custom);
1545         setOperationAction(ISD::FSHR, VT, Custom);
1546       }
1547     }
1548   }// has  AVX-512
1549 
1550   // This block controls legalization for operations that don't have
1551   // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
1552   // narrower widths.
1553   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1554     // These operations are handled on non-VLX by artificially widening in
1555     // isel patterns.
1556     // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1557 
1558     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1559     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1560     setOperationAction(ISD::FP_TO_UINT,         MVT::v2i32, Custom);
1561     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1562     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1563 
1564     for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1565       setOperationAction(ISD::SMAX, VT, Legal);
1566       setOperationAction(ISD::UMAX, VT, Legal);
1567       setOperationAction(ISD::SMIN, VT, Legal);
1568       setOperationAction(ISD::UMIN, VT, Legal);
1569       setOperationAction(ISD::ABS,  VT, Legal);
1570     }
1571 
1572     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1573       setOperationAction(ISD::ROTL,     VT, Custom);
1574       setOperationAction(ISD::ROTR,     VT, Custom);
1575     }
1576 
1577     // Custom legalize 2x32 to get a little better code.
1578     setOperationAction(ISD::MSCATTER, MVT::v2f32, Custom);
1579     setOperationAction(ISD::MSCATTER, MVT::v2i32, Custom);
1580 
1581     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1582                      MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1583       setOperationAction(ISD::MSCATTER, VT, Custom);
1584 
1585     if (Subtarget.hasDQI()) {
1586       for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1587         setOperationAction(ISD::SINT_TO_FP,     VT, Legal);
1588         setOperationAction(ISD::UINT_TO_FP,     VT, Legal);
1589         setOperationAction(ISD::FP_TO_SINT,     VT, Legal);
1590         setOperationAction(ISD::FP_TO_UINT,     VT, Legal);
1591 
1592         setOperationAction(ISD::MUL,            VT, Legal);
1593       }
1594     }
1595 
1596     if (Subtarget.hasCDI()) {
1597       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1598         setOperationAction(ISD::CTLZ,            VT, Legal);
1599       }
1600     } // Subtarget.hasCDI()
1601 
1602     if (Subtarget.hasVPOPCNTDQ()) {
1603       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 })
1604         setOperationAction(ISD::CTPOP, VT, Legal);
1605     }
1606   }
1607 
1608   // This block control legalization of v32i1/v64i1 which are available with
1609   // AVX512BW. 512-bit v32i16 and v64i8 vector legalization is controlled with
1610   // useBWIRegs.
1611   if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1612     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1613     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1614 
1615     for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
1616       setOperationAction(ISD::ADD,                VT, Custom);
1617       setOperationAction(ISD::SUB,                VT, Custom);
1618       setOperationAction(ISD::MUL,                VT, Custom);
1619       setOperationAction(ISD::VSELECT,            VT, Expand);
1620       setOperationAction(ISD::UADDSAT,            VT, Custom);
1621       setOperationAction(ISD::SADDSAT,            VT, Custom);
1622       setOperationAction(ISD::USUBSAT,            VT, Custom);
1623       setOperationAction(ISD::SSUBSAT,            VT, Custom);
1624 
1625       setOperationAction(ISD::TRUNCATE,           VT, Custom);
1626       setOperationAction(ISD::SETCC,              VT, Custom);
1627       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1628       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1629       setOperationAction(ISD::SELECT,             VT, Custom);
1630       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1631       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1632     }
1633 
1634     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1635     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1636     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1637     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1638     for (auto VT : { MVT::v16i1, MVT::v32i1 })
1639       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1640 
1641     // Extends from v32i1 masks to 256-bit vectors.
1642     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1643     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1644     setOperationAction(ISD::ANY_EXTEND,         MVT::v32i8, Custom);
1645   }
1646 
1647   // This block controls legalization for v32i16 and v64i8. 512-bits can be
1648   // disabled based on prefer-vector-width and required-vector-width function
1649   // attributes.
1650   if (!Subtarget.useSoftFloat() && Subtarget.useBWIRegs()) {
1651     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1652     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1653 
1654     // Extends from v64i1 masks to 512-bit vectors.
1655     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1656     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1657     setOperationAction(ISD::ANY_EXTEND,         MVT::v64i8, Custom);
1658 
1659     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1660     setOperationAction(ISD::MUL,                MVT::v64i8, Custom);
1661     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1662     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1663     setOperationAction(ISD::MULHS,              MVT::v64i8, Custom);
1664     setOperationAction(ISD::MULHU,              MVT::v64i8, Custom);
1665     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i16, Custom);
1666     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i8, Custom);
1667     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i16, Legal);
1668     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i8, Legal);
1669     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1670     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1671     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i16, Custom);
1672     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v64i8, Custom);
1673     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1674     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1675     setOperationAction(ISD::ANY_EXTEND,         MVT::v32i16, Custom);
1676     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1677     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i8, Custom);
1678     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i16, Custom);
1679     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i8, Custom);
1680     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1681     setOperationAction(ISD::BITREVERSE,         MVT::v64i8, Custom);
1682 
1683     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v32i16, Custom);
1684     setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, MVT::v32i16, Custom);
1685 
1686     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1687 
1688     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1689       setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1690       setOperationAction(ISD::VSELECT,      VT, Custom);
1691       setOperationAction(ISD::ABS,          VT, Legal);
1692       setOperationAction(ISD::SRL,          VT, Custom);
1693       setOperationAction(ISD::SHL,          VT, Custom);
1694       setOperationAction(ISD::SRA,          VT, Custom);
1695       setOperationAction(ISD::MLOAD,        VT, Legal);
1696       setOperationAction(ISD::MSTORE,       VT, Legal);
1697       setOperationAction(ISD::CTPOP,        VT, Custom);
1698       setOperationAction(ISD::CTLZ,         VT, Custom);
1699       setOperationAction(ISD::SMAX,         VT, Legal);
1700       setOperationAction(ISD::UMAX,         VT, Legal);
1701       setOperationAction(ISD::SMIN,         VT, Legal);
1702       setOperationAction(ISD::UMIN,         VT, Legal);
1703       setOperationAction(ISD::SETCC,        VT, Custom);
1704       setOperationAction(ISD::UADDSAT,      VT, Legal);
1705       setOperationAction(ISD::SADDSAT,      VT, Legal);
1706       setOperationAction(ISD::USUBSAT,      VT, Legal);
1707       setOperationAction(ISD::SSUBSAT,      VT, Legal);
1708 
1709       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1710       // setcc all the way to isel and prefer SETGT in some isel patterns.
1711       setCondCodeAction(ISD::SETLT, VT, Custom);
1712       setCondCodeAction(ISD::SETLE, VT, Custom);
1713     }
1714 
1715     for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1716       setLoadExtAction(ExtType, MVT::v32i16, MVT::v32i8, Legal);
1717     }
1718 
1719     if (Subtarget.hasBITALG()) {
1720       for (auto VT : { MVT::v64i8, MVT::v32i16 })
1721         setOperationAction(ISD::CTPOP, VT, Legal);
1722     }
1723 
1724     if (Subtarget.hasVBMI2()) {
1725       setOperationAction(ISD::FSHL, MVT::v32i16, Custom);
1726       setOperationAction(ISD::FSHR, MVT::v32i16, Custom);
1727     }
1728   }
1729 
1730   if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1731     for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
1732       setOperationAction(ISD::MLOAD,  VT, Subtarget.hasVLX() ? Legal : Custom);
1733       setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
1734     }
1735 
1736     // These operations are handled on non-VLX by artificially widening in
1737     // isel patterns.
1738     // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1739 
1740     if (Subtarget.hasBITALG()) {
1741       for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
1742         setOperationAction(ISD::CTPOP, VT, Legal);
1743     }
1744   }
1745 
1746   if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
1747     setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1748     setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1749     setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1750     setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1751     setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1752 
1753     setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1754     setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1755     setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1756     setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1757     setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1758 
1759     if (Subtarget.hasDQI()) {
1760       // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
1761       // v2f32 UINT_TO_FP is already custom under SSE2.
1762       setOperationAction(ISD::SINT_TO_FP,    MVT::v2f32, Custom);
1763       assert(isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) &&
1764              "Unexpected operation action!");
1765       // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
1766       setOperationAction(ISD::FP_TO_SINT,    MVT::v2f32, Custom);
1767       setOperationAction(ISD::FP_TO_UINT,    MVT::v2f32, Custom);
1768     }
1769 
1770     if (Subtarget.hasBWI()) {
1771       setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1772       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1773     }
1774 
1775     if (Subtarget.hasVBMI2()) {
1776       // TODO: Make these legal even without VLX?
1777       for (auto VT : { MVT::v8i16,  MVT::v4i32, MVT::v2i64,
1778                        MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1779         setOperationAction(ISD::FSHL, VT, Custom);
1780         setOperationAction(ISD::FSHR, VT, Custom);
1781       }
1782     }
1783   }
1784 
1785   // We want to custom lower some of our intrinsics.
1786   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1787   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1788   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1789   if (!Subtarget.is64Bit()) {
1790     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1791     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1792   }
1793 
1794   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1795   // handle type legalization for these operations here.
1796   //
1797   // FIXME: We really should do custom legalization for addition and
1798   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1799   // than generic legalization for 64-bit multiplication-with-overflow, though.
1800   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1801     if (VT == MVT::i64 && !Subtarget.is64Bit())
1802       continue;
1803     // Add/Sub/Mul with overflow operations are custom lowered.
1804     setOperationAction(ISD::SADDO, VT, Custom);
1805     setOperationAction(ISD::UADDO, VT, Custom);
1806     setOperationAction(ISD::SSUBO, VT, Custom);
1807     setOperationAction(ISD::USUBO, VT, Custom);
1808     setOperationAction(ISD::SMULO, VT, Custom);
1809     setOperationAction(ISD::UMULO, VT, Custom);
1810 
1811     // Support carry in as value rather than glue.
1812     setOperationAction(ISD::ADDCARRY, VT, Custom);
1813     setOperationAction(ISD::SUBCARRY, VT, Custom);
1814     setOperationAction(ISD::SETCCCARRY, VT, Custom);
1815   }
1816 
1817   if (!Subtarget.is64Bit()) {
1818     // These libcalls are not available in 32-bit.
1819     setLibcallName(RTLIB::SHL_I128, nullptr);
1820     setLibcallName(RTLIB::SRL_I128, nullptr);
1821     setLibcallName(RTLIB::SRA_I128, nullptr);
1822     setLibcallName(RTLIB::MUL_I128, nullptr);
1823   }
1824 
1825   // Combine sin / cos into _sincos_stret if it is available.
1826   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1827       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1828     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1829     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1830   }
1831 
1832   if (Subtarget.isTargetWin64()) {
1833     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1834     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1835     setOperationAction(ISD::SREM, MVT::i128, Custom);
1836     setOperationAction(ISD::UREM, MVT::i128, Custom);
1837     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1838     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1839   }
1840 
1841   // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
1842   // is. We should promote the value to 64-bits to solve this.
1843   // This is what the CRT headers do - `fmodf` is an inline header
1844   // function casting to f64 and calling `fmod`.
1845   if (Subtarget.is32Bit() && (Subtarget.isTargetKnownWindowsMSVC() ||
1846                               Subtarget.isTargetWindowsItanium()))
1847     for (ISD::NodeType Op :
1848          {ISD::FCEIL, ISD::FCOS, ISD::FEXP, ISD::FFLOOR, ISD::FREM, ISD::FLOG,
1849           ISD::FLOG10, ISD::FPOW, ISD::FSIN})
1850       if (isOperationExpand(Op, MVT::f32))
1851         setOperationAction(Op, MVT::f32, Promote);
1852 
1853   // We have target-specific dag combine patterns for the following nodes:
1854   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1855   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
1856   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1857   setTargetDAGCombine(ISD::INSERT_SUBVECTOR);
1858   setTargetDAGCombine(ISD::EXTRACT_SUBVECTOR);
1859   setTargetDAGCombine(ISD::BITCAST);
1860   setTargetDAGCombine(ISD::VSELECT);
1861   setTargetDAGCombine(ISD::SELECT);
1862   setTargetDAGCombine(ISD::SHL);
1863   setTargetDAGCombine(ISD::SRA);
1864   setTargetDAGCombine(ISD::SRL);
1865   setTargetDAGCombine(ISD::OR);
1866   setTargetDAGCombine(ISD::AND);
1867   setTargetDAGCombine(ISD::ADD);
1868   setTargetDAGCombine(ISD::FADD);
1869   setTargetDAGCombine(ISD::FSUB);
1870   setTargetDAGCombine(ISD::FNEG);
1871   setTargetDAGCombine(ISD::FMA);
1872   setTargetDAGCombine(ISD::FMINNUM);
1873   setTargetDAGCombine(ISD::FMAXNUM);
1874   setTargetDAGCombine(ISD::SUB);
1875   setTargetDAGCombine(ISD::LOAD);
1876   setTargetDAGCombine(ISD::MLOAD);
1877   setTargetDAGCombine(ISD::STORE);
1878   setTargetDAGCombine(ISD::MSTORE);
1879   setTargetDAGCombine(ISD::TRUNCATE);
1880   setTargetDAGCombine(ISD::ZERO_EXTEND);
1881   setTargetDAGCombine(ISD::ANY_EXTEND);
1882   setTargetDAGCombine(ISD::SIGN_EXTEND);
1883   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1884   setTargetDAGCombine(ISD::SINT_TO_FP);
1885   setTargetDAGCombine(ISD::UINT_TO_FP);
1886   setTargetDAGCombine(ISD::SETCC);
1887   setTargetDAGCombine(ISD::MUL);
1888   setTargetDAGCombine(ISD::XOR);
1889   setTargetDAGCombine(ISD::MSCATTER);
1890   setTargetDAGCombine(ISD::MGATHER);
1891 
1892   computeRegisterProperties(Subtarget.getRegisterInfo());
1893 
1894   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1895   MaxStoresPerMemsetOptSize = 8;
1896   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1897   MaxStoresPerMemcpyOptSize = 4;
1898   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1899   MaxStoresPerMemmoveOptSize = 4;
1900 
1901   // TODO: These control memcmp expansion in CGP and could be raised higher, but
1902   // that needs to benchmarked and balanced with the potential use of vector
1903   // load/store types (PR33329, PR33914).
1904   MaxLoadsPerMemcmp = 2;
1905   MaxLoadsPerMemcmpOptSize = 2;
1906 
1907   // Set loop alignment to 2^ExperimentalPrefLoopAlignment bytes (default: 2^4).
1908   setPrefLoopAlignment(ExperimentalPrefLoopAlignment);
1909 
1910   // An out-of-order CPU can speculatively execute past a predictable branch,
1911   // but a conditional move could be stalled by an expensive earlier operation.
1912   PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
1913   EnableExtLdPromotion = true;
1914   setPrefFunctionAlignment(4); // 2^4 bytes.
1915 
1916   verifyIntrinsicTables();
1917 }
1918 
1919 // This has so far only been implemented for 64-bit MachO.
useLoadStackGuardNode() const1920 bool X86TargetLowering::useLoadStackGuardNode() const {
1921   return Subtarget.isTargetMachO() && Subtarget.is64Bit();
1922 }
1923 
useStackGuardXorFP() const1924 bool X86TargetLowering::useStackGuardXorFP() const {
1925   // Currently only MSVC CRTs XOR the frame pointer into the stack guard value.
1926   return Subtarget.getTargetTriple().isOSMSVCRT();
1927 }
1928 
emitStackGuardXorFP(SelectionDAG & DAG,SDValue Val,const SDLoc & DL) const1929 SDValue X86TargetLowering::emitStackGuardXorFP(SelectionDAG &DAG, SDValue Val,
1930                                                const SDLoc &DL) const {
1931   EVT PtrTy = getPointerTy(DAG.getDataLayout());
1932   unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
1933   MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
1934   return SDValue(Node, 0);
1935 }
1936 
1937 TargetLoweringBase::LegalizeTypeAction
getPreferredVectorAction(MVT VT) const1938 X86TargetLowering::getPreferredVectorAction(MVT VT) const {
1939   if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1940     return TypeSplitVector;
1941 
1942   if (ExperimentalVectorWideningLegalization &&
1943       VT.getVectorNumElements() != 1 &&
1944       VT.getVectorElementType() != MVT::i1)
1945     return TypeWidenVector;
1946 
1947   return TargetLoweringBase::getPreferredVectorAction(VT);
1948 }
1949 
getRegisterTypeForCallingConv(LLVMContext & Context,CallingConv::ID CC,EVT VT) const1950 MVT X86TargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1951                                                      CallingConv::ID CC,
1952                                                      EVT VT) const {
1953   if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1954     return MVT::v32i8;
1955   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1956 }
1957 
getNumRegistersForCallingConv(LLVMContext & Context,CallingConv::ID CC,EVT VT) const1958 unsigned X86TargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1959                                                           CallingConv::ID CC,
1960                                                           EVT VT) const {
1961   if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1962     return 1;
1963   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1964 }
1965 
getSetCCResultType(const DataLayout & DL,LLVMContext & Context,EVT VT) const1966 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL,
1967                                           LLVMContext& Context,
1968                                           EVT VT) const {
1969   if (!VT.isVector())
1970     return MVT::i8;
1971 
1972   if (Subtarget.hasAVX512()) {
1973     const unsigned NumElts = VT.getVectorNumElements();
1974 
1975     // Figure out what this type will be legalized to.
1976     EVT LegalVT = VT;
1977     while (getTypeAction(Context, LegalVT) != TypeLegal)
1978       LegalVT = getTypeToTransformTo(Context, LegalVT);
1979 
1980     // If we got a 512-bit vector then we'll definitely have a vXi1 compare.
1981     if (LegalVT.getSimpleVT().is512BitVector())
1982       return EVT::getVectorVT(Context, MVT::i1, NumElts);
1983 
1984     if (LegalVT.getSimpleVT().isVector() && Subtarget.hasVLX()) {
1985       // If we legalized to less than a 512-bit vector, then we will use a vXi1
1986       // compare for vXi32/vXi64 for sure. If we have BWI we will also support
1987       // vXi16/vXi8.
1988       MVT EltVT = LegalVT.getSimpleVT().getVectorElementType();
1989       if (Subtarget.hasBWI() || EltVT.getSizeInBits() >= 32)
1990         return EVT::getVectorVT(Context, MVT::i1, NumElts);
1991     }
1992   }
1993 
1994   return VT.changeVectorElementTypeToInteger();
1995 }
1996 
1997 /// Helper for getByValTypeAlignment to determine
1998 /// the desired ByVal argument alignment.
getMaxByValAlign(Type * Ty,unsigned & MaxAlign)1999 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
2000   if (MaxAlign == 16)
2001     return;
2002   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
2003     if (VTy->getBitWidth() == 128)
2004       MaxAlign = 16;
2005   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2006     unsigned EltAlign = 0;
2007     getMaxByValAlign(ATy->getElementType(), EltAlign);
2008     if (EltAlign > MaxAlign)
2009       MaxAlign = EltAlign;
2010   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2011     for (auto *EltTy : STy->elements()) {
2012       unsigned EltAlign = 0;
2013       getMaxByValAlign(EltTy, EltAlign);
2014       if (EltAlign > MaxAlign)
2015         MaxAlign = EltAlign;
2016       if (MaxAlign == 16)
2017         break;
2018     }
2019   }
2020 }
2021 
2022 /// Return the desired alignment for ByVal aggregate
2023 /// function arguments in the caller parameter area. For X86, aggregates
2024 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
2025 /// are at 4-byte boundaries.
getByValTypeAlignment(Type * Ty,const DataLayout & DL) const2026 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
2027                                                   const DataLayout &DL) const {
2028   if (Subtarget.is64Bit()) {
2029     // Max of 8 and alignment of type.
2030     unsigned TyAlign = DL.getABITypeAlignment(Ty);
2031     if (TyAlign > 8)
2032       return TyAlign;
2033     return 8;
2034   }
2035 
2036   unsigned Align = 4;
2037   if (Subtarget.hasSSE1())
2038     getMaxByValAlign(Ty, Align);
2039   return Align;
2040 }
2041 
2042 /// Returns the target specific optimal type for load
2043 /// and store operations as a result of memset, memcpy, and memmove
2044 /// lowering. If DstAlign is zero that means it's safe to destination
2045 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
2046 /// means there isn't a need to check it against alignment requirement,
2047 /// probably because the source does not need to be loaded. If 'IsMemset' is
2048 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
2049 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
2050 /// source is constant so it does not need to be loaded.
2051 /// It returns EVT::Other if the type should be determined using generic
2052 /// target-independent logic.
2053 EVT
getOptimalMemOpType(uint64_t Size,unsigned DstAlign,unsigned SrcAlign,bool IsMemset,bool ZeroMemset,bool MemcpyStrSrc,MachineFunction & MF) const2054 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
2055                                        unsigned DstAlign, unsigned SrcAlign,
2056                                        bool IsMemset, bool ZeroMemset,
2057                                        bool MemcpyStrSrc,
2058                                        MachineFunction &MF) const {
2059   const Function &F = MF.getFunction();
2060   if (!F.hasFnAttribute(Attribute::NoImplicitFloat)) {
2061     if (Size >= 16 &&
2062         (!Subtarget.isUnalignedMem16Slow() ||
2063          ((DstAlign == 0 || DstAlign >= 16) &&
2064           (SrcAlign == 0 || SrcAlign >= 16)))) {
2065       // FIXME: Check if unaligned 32-byte accesses are slow.
2066       if (Size >= 32 && Subtarget.hasAVX()) {
2067         // Although this isn't a well-supported type for AVX1, we'll let
2068         // legalization and shuffle lowering produce the optimal codegen. If we
2069         // choose an optimal type with a vector element larger than a byte,
2070         // getMemsetStores() may create an intermediate splat (using an integer
2071         // multiply) before we splat as a vector.
2072         return MVT::v32i8;
2073       }
2074       if (Subtarget.hasSSE2())
2075         return MVT::v16i8;
2076       // TODO: Can SSE1 handle a byte vector?
2077       // If we have SSE1 registers we should be able to use them.
2078       if (Subtarget.hasSSE1() && (Subtarget.is64Bit() || Subtarget.hasX87()))
2079         return MVT::v4f32;
2080     } else if ((!IsMemset || ZeroMemset) && !MemcpyStrSrc && Size >= 8 &&
2081                !Subtarget.is64Bit() && Subtarget.hasSSE2()) {
2082       // Do not use f64 to lower memcpy if source is string constant. It's
2083       // better to use i32 to avoid the loads.
2084       // Also, do not use f64 to lower memset unless this is a memset of zeros.
2085       // The gymnastics of splatting a byte value into an XMM register and then
2086       // only using 8-byte stores (because this is a CPU with slow unaligned
2087       // 16-byte accesses) makes that a loser.
2088       return MVT::f64;
2089     }
2090   }
2091   // This is a compromise. If we reach here, unaligned accesses may be slow on
2092   // this target. However, creating smaller, aligned accesses could be even
2093   // slower and would certainly be a lot more code.
2094   if (Subtarget.is64Bit() && Size >= 8)
2095     return MVT::i64;
2096   return MVT::i32;
2097 }
2098 
isSafeMemOpType(MVT VT) const2099 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2100   if (VT == MVT::f32)
2101     return X86ScalarSSEf32;
2102   else if (VT == MVT::f64)
2103     return X86ScalarSSEf64;
2104   return true;
2105 }
2106 
2107 bool
allowsMisalignedMemoryAccesses(EVT VT,unsigned,unsigned,bool * Fast) const2108 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
2109                                                   unsigned,
2110                                                   unsigned,
2111                                                   bool *Fast) const {
2112   if (Fast) {
2113     switch (VT.getSizeInBits()) {
2114     default:
2115       // 8-byte and under are always assumed to be fast.
2116       *Fast = true;
2117       break;
2118     case 128:
2119       *Fast = !Subtarget.isUnalignedMem16Slow();
2120       break;
2121     case 256:
2122       *Fast = !Subtarget.isUnalignedMem32Slow();
2123       break;
2124     // TODO: What about AVX-512 (512-bit) accesses?
2125     }
2126   }
2127   // Misaligned accesses of any size are always allowed.
2128   return true;
2129 }
2130 
2131 /// Return the entry encoding for a jump table in the
2132 /// current function.  The returned value is a member of the
2133 /// MachineJumpTableInfo::JTEntryKind enum.
getJumpTableEncoding() const2134 unsigned X86TargetLowering::getJumpTableEncoding() const {
2135   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2136   // symbol.
2137   if (isPositionIndependent() && Subtarget.isPICStyleGOT())
2138     return MachineJumpTableInfo::EK_Custom32;
2139 
2140   // Otherwise, use the normal jump table encoding heuristics.
2141   return TargetLowering::getJumpTableEncoding();
2142 }
2143 
useSoftFloat() const2144 bool X86TargetLowering::useSoftFloat() const {
2145   return Subtarget.useSoftFloat();
2146 }
2147 
markLibCallAttributes(MachineFunction * MF,unsigned CC,ArgListTy & Args) const2148 void X86TargetLowering::markLibCallAttributes(MachineFunction *MF, unsigned CC,
2149                                               ArgListTy &Args) const {
2150 
2151   // Only relabel X86-32 for C / Stdcall CCs.
2152   if (Subtarget.is64Bit())
2153     return;
2154   if (CC != CallingConv::C && CC != CallingConv::X86_StdCall)
2155     return;
2156   unsigned ParamRegs = 0;
2157   if (auto *M = MF->getFunction().getParent())
2158     ParamRegs = M->getNumberRegisterParameters();
2159 
2160   // Mark the first N int arguments as having reg
2161   for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
2162     Type *T = Args[Idx].Ty;
2163     if (T->isIntOrPtrTy())
2164       if (MF->getDataLayout().getTypeAllocSize(T) <= 8) {
2165         unsigned numRegs = 1;
2166         if (MF->getDataLayout().getTypeAllocSize(T) > 4)
2167           numRegs = 2;
2168         if (ParamRegs < numRegs)
2169           return;
2170         ParamRegs -= numRegs;
2171         Args[Idx].IsInReg = true;
2172       }
2173   }
2174 }
2175 
2176 const MCExpr *
LowerCustomJumpTableEntry(const MachineJumpTableInfo * MJTI,const MachineBasicBlock * MBB,unsigned uid,MCContext & Ctx) const2177 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2178                                              const MachineBasicBlock *MBB,
2179                                              unsigned uid,MCContext &Ctx) const{
2180   assert(isPositionIndependent() && Subtarget.isPICStyleGOT());
2181   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2182   // entries.
2183   return MCSymbolRefExpr::create(MBB->getSymbol(),
2184                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2185 }
2186 
2187 /// Returns relocation base for the given PIC jumptable.
getPICJumpTableRelocBase(SDValue Table,SelectionDAG & DAG) const2188 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2189                                                     SelectionDAG &DAG) const {
2190   if (!Subtarget.is64Bit())
2191     // This doesn't have SDLoc associated with it, but is not really the
2192     // same as a Register.
2193     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2194                        getPointerTy(DAG.getDataLayout()));
2195   return Table;
2196 }
2197 
2198 /// This returns the relocation base for the given PIC jumptable,
2199 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2200 const MCExpr *X86TargetLowering::
getPICJumpTableRelocBaseExpr(const MachineFunction * MF,unsigned JTI,MCContext & Ctx) const2201 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2202                              MCContext &Ctx) const {
2203   // X86-64 uses RIP relative addressing based on the jump table label.
2204   if (Subtarget.isPICStyleRIPRel())
2205     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2206 
2207   // Otherwise, the reference is relative to the PIC base.
2208   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2209 }
2210 
2211 std::pair<const TargetRegisterClass *, uint8_t>
findRepresentativeClass(const TargetRegisterInfo * TRI,MVT VT) const2212 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2213                                            MVT VT) const {
2214   const TargetRegisterClass *RRC = nullptr;
2215   uint8_t Cost = 1;
2216   switch (VT.SimpleTy) {
2217   default:
2218     return TargetLowering::findRepresentativeClass(TRI, VT);
2219   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2220     RRC = Subtarget.is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2221     break;
2222   case MVT::x86mmx:
2223     RRC = &X86::VR64RegClass;
2224     break;
2225   case MVT::f32: case MVT::f64:
2226   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2227   case MVT::v4f32: case MVT::v2f64:
2228   case MVT::v32i8: case MVT::v16i16: case MVT::v8i32: case MVT::v4i64:
2229   case MVT::v8f32: case MVT::v4f64:
2230   case MVT::v64i8: case MVT::v32i16: case MVT::v16i32: case MVT::v8i64:
2231   case MVT::v16f32: case MVT::v8f64:
2232     RRC = &X86::VR128XRegClass;
2233     break;
2234   }
2235   return std::make_pair(RRC, Cost);
2236 }
2237 
getAddressSpace() const2238 unsigned X86TargetLowering::getAddressSpace() const {
2239   if (Subtarget.is64Bit())
2240     return (getTargetMachine().getCodeModel() == CodeModel::Kernel) ? 256 : 257;
2241   return 256;
2242 }
2243 
hasStackGuardSlotTLS(const Triple & TargetTriple)2244 static bool hasStackGuardSlotTLS(const Triple &TargetTriple) {
2245   return TargetTriple.isOSGlibc() || TargetTriple.isOSFuchsia() ||
2246          (TargetTriple.isAndroid() && !TargetTriple.isAndroidVersionLT(17));
2247 }
2248 
SegmentOffset(IRBuilder<> & IRB,unsigned Offset,unsigned AddressSpace)2249 static Constant* SegmentOffset(IRBuilder<> &IRB,
2250                                unsigned Offset, unsigned AddressSpace) {
2251   return ConstantExpr::getIntToPtr(
2252       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2253       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2254 }
2255 
getIRStackGuard(IRBuilder<> & IRB) const2256 Value *X86TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
2257   // glibc, bionic, and Fuchsia have a special slot for the stack guard in
2258   // tcbhead_t; use it instead of the usual global variable (see
2259   // sysdeps/{i386,x86_64}/nptl/tls.h)
2260   if (hasStackGuardSlotTLS(Subtarget.getTargetTriple())) {
2261     if (Subtarget.isTargetFuchsia()) {
2262       // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
2263       return SegmentOffset(IRB, 0x10, getAddressSpace());
2264     } else {
2265       // %fs:0x28, unless we're using a Kernel code model, in which case
2266       // it's %gs:0x28.  gs:0x14 on i386.
2267       unsigned Offset = (Subtarget.is64Bit()) ? 0x28 : 0x14;
2268       return SegmentOffset(IRB, Offset, getAddressSpace());
2269     }
2270   }
2271 
2272   return TargetLowering::getIRStackGuard(IRB);
2273 }
2274 
insertSSPDeclarations(Module & M) const2275 void X86TargetLowering::insertSSPDeclarations(Module &M) const {
2276   // MSVC CRT provides functionalities for stack protection.
2277   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2278       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2279     // MSVC CRT has a global variable holding security cookie.
2280     M.getOrInsertGlobal("__security_cookie",
2281                         Type::getInt8PtrTy(M.getContext()));
2282 
2283     // MSVC CRT has a function to validate security cookie.
2284     auto *SecurityCheckCookie = cast<Function>(
2285         M.getOrInsertFunction("__security_check_cookie",
2286                               Type::getVoidTy(M.getContext()),
2287                               Type::getInt8PtrTy(M.getContext())));
2288     SecurityCheckCookie->setCallingConv(CallingConv::X86_FastCall);
2289     SecurityCheckCookie->addAttribute(1, Attribute::AttrKind::InReg);
2290     return;
2291   }
2292   // glibc, bionic, and Fuchsia have a special slot for the stack guard.
2293   if (hasStackGuardSlotTLS(Subtarget.getTargetTriple()))
2294     return;
2295   TargetLowering::insertSSPDeclarations(M);
2296 }
2297 
getSDagStackGuard(const Module & M) const2298 Value *X86TargetLowering::getSDagStackGuard(const Module &M) const {
2299   // MSVC CRT has a global variable holding security cookie.
2300   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2301       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2302     return M.getGlobalVariable("__security_cookie");
2303   }
2304   return TargetLowering::getSDagStackGuard(M);
2305 }
2306 
getSSPStackGuardCheck(const Module & M) const2307 Value *X86TargetLowering::getSSPStackGuardCheck(const Module &M) const {
2308   // MSVC CRT has a function to validate security cookie.
2309   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2310       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2311     return M.getFunction("__security_check_cookie");
2312   }
2313   return TargetLowering::getSSPStackGuardCheck(M);
2314 }
2315 
getSafeStackPointerLocation(IRBuilder<> & IRB) const2316 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2317   if (Subtarget.getTargetTriple().isOSContiki())
2318     return getDefaultSafeStackPointerLocation(IRB, false);
2319 
2320   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2321   // definition of TLS_SLOT_SAFESTACK in
2322   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2323   if (Subtarget.isTargetAndroid()) {
2324     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2325     // %gs:0x24 on i386
2326     unsigned Offset = (Subtarget.is64Bit()) ? 0x48 : 0x24;
2327     return SegmentOffset(IRB, Offset, getAddressSpace());
2328   }
2329 
2330   // Fuchsia is similar.
2331   if (Subtarget.isTargetFuchsia()) {
2332     // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
2333     return SegmentOffset(IRB, 0x18, getAddressSpace());
2334   }
2335 
2336   return TargetLowering::getSafeStackPointerLocation(IRB);
2337 }
2338 
isNoopAddrSpaceCast(unsigned SrcAS,unsigned DestAS) const2339 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2340                                             unsigned DestAS) const {
2341   assert(SrcAS != DestAS && "Expected different address spaces!");
2342 
2343   return SrcAS < 256 && DestAS < 256;
2344 }
2345 
2346 //===----------------------------------------------------------------------===//
2347 //               Return Value Calling Convention Implementation
2348 //===----------------------------------------------------------------------===//
2349 
2350 #include "X86GenCallingConv.inc"
2351 
CanLowerReturn(CallingConv::ID CallConv,MachineFunction & MF,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,LLVMContext & Context) const2352 bool X86TargetLowering::CanLowerReturn(
2353     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2354     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2355   SmallVector<CCValAssign, 16> RVLocs;
2356   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2357   return CCInfo.CheckReturn(Outs, RetCC_X86);
2358 }
2359 
getScratchRegisters(CallingConv::ID) const2360 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2361   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2362   return ScratchRegs;
2363 }
2364 
2365 /// Lowers masks values (v*i1) to the local register values
2366 /// \returns DAG node after lowering to register type
lowerMasksToReg(const SDValue & ValArg,const EVT & ValLoc,const SDLoc & Dl,SelectionDAG & DAG)2367 static SDValue lowerMasksToReg(const SDValue &ValArg, const EVT &ValLoc,
2368                                const SDLoc &Dl, SelectionDAG &DAG) {
2369   EVT ValVT = ValArg.getValueType();
2370 
2371   if (ValVT == MVT::v1i1)
2372     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Dl, ValLoc, ValArg,
2373                        DAG.getIntPtrConstant(0, Dl));
2374 
2375   if ((ValVT == MVT::v8i1 && (ValLoc == MVT::i8 || ValLoc == MVT::i32)) ||
2376       (ValVT == MVT::v16i1 && (ValLoc == MVT::i16 || ValLoc == MVT::i32))) {
2377     // Two stage lowering might be required
2378     // bitcast:   v8i1 -> i8 / v16i1 -> i16
2379     // anyextend: i8   -> i32 / i16   -> i32
2380     EVT TempValLoc = ValVT == MVT::v8i1 ? MVT::i8 : MVT::i16;
2381     SDValue ValToCopy = DAG.getBitcast(TempValLoc, ValArg);
2382     if (ValLoc == MVT::i32)
2383       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValToCopy);
2384     return ValToCopy;
2385   }
2386 
2387   if ((ValVT == MVT::v32i1 && ValLoc == MVT::i32) ||
2388       (ValVT == MVT::v64i1 && ValLoc == MVT::i64)) {
2389     // One stage lowering is required
2390     // bitcast:   v32i1 -> i32 / v64i1 -> i64
2391     return DAG.getBitcast(ValLoc, ValArg);
2392   }
2393 
2394   return DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValArg);
2395 }
2396 
2397 /// Breaks v64i1 value into two registers and adds the new node to the DAG
Passv64i1ArgInRegs(const SDLoc & Dl,SelectionDAG & DAG,SDValue Chain,SDValue & Arg,SmallVector<std::pair<unsigned,SDValue>,8> & RegsToPass,CCValAssign & VA,CCValAssign & NextVA,const X86Subtarget & Subtarget)2398 static void Passv64i1ArgInRegs(
2399     const SDLoc &Dl, SelectionDAG &DAG, SDValue Chain, SDValue &Arg,
2400     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, CCValAssign &VA,
2401     CCValAssign &NextVA, const X86Subtarget &Subtarget) {
2402   assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
2403   assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2404   assert(Arg.getValueType() == MVT::i64 && "Expecting 64 bit value");
2405   assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2406          "The value should reside in two registers");
2407 
2408   // Before splitting the value we cast it to i64
2409   Arg = DAG.getBitcast(MVT::i64, Arg);
2410 
2411   // Splitting the value into two i32 types
2412   SDValue Lo, Hi;
2413   Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2414                    DAG.getConstant(0, Dl, MVT::i32));
2415   Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2416                    DAG.getConstant(1, Dl, MVT::i32));
2417 
2418   // Attach the two i32 types into corresponding registers
2419   RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
2420   RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Hi));
2421 }
2422 
2423 SDValue
LowerReturn(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SDLoc & dl,SelectionDAG & DAG) const2424 X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2425                                bool isVarArg,
2426                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2427                                const SmallVectorImpl<SDValue> &OutVals,
2428                                const SDLoc &dl, SelectionDAG &DAG) const {
2429   MachineFunction &MF = DAG.getMachineFunction();
2430   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2431 
2432   // In some cases we need to disable registers from the default CSR list.
2433   // For example, when they are used for argument passing.
2434   bool ShouldDisableCalleeSavedRegister =
2435       CallConv == CallingConv::X86_RegCall ||
2436       MF.getFunction().hasFnAttribute("no_caller_saved_registers");
2437 
2438   if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2439     report_fatal_error("X86 interrupts may not return any value");
2440 
2441   SmallVector<CCValAssign, 16> RVLocs;
2442   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2443   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2444 
2445   SDValue Flag;
2446   SmallVector<SDValue, 6> RetOps;
2447   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2448   // Operand #1 = Bytes To Pop
2449   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2450                    MVT::i32));
2451 
2452   // Copy the result values into the output registers.
2453   for (unsigned I = 0, OutsIndex = 0, E = RVLocs.size(); I != E;
2454        ++I, ++OutsIndex) {
2455     CCValAssign &VA = RVLocs[I];
2456     assert(VA.isRegLoc() && "Can only return in registers!");
2457 
2458     // Add the register to the CalleeSaveDisableRegs list.
2459     if (ShouldDisableCalleeSavedRegister)
2460       MF.getRegInfo().disableCalleeSavedRegister(VA.getLocReg());
2461 
2462     SDValue ValToCopy = OutVals[OutsIndex];
2463     EVT ValVT = ValToCopy.getValueType();
2464 
2465     // Promote values to the appropriate types.
2466     if (VA.getLocInfo() == CCValAssign::SExt)
2467       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2468     else if (VA.getLocInfo() == CCValAssign::ZExt)
2469       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2470     else if (VA.getLocInfo() == CCValAssign::AExt) {
2471       if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2472         ValToCopy = lowerMasksToReg(ValToCopy, VA.getLocVT(), dl, DAG);
2473       else
2474         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2475     }
2476     else if (VA.getLocInfo() == CCValAssign::BCvt)
2477       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2478 
2479     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2480            "Unexpected FP-extend for return value.");
2481 
2482     // If this is x86-64, and we disabled SSE, we can't return FP values,
2483     // or SSE or MMX vectors.
2484     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2485          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2486         (Subtarget.is64Bit() && !Subtarget.hasSSE1())) {
2487       errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2488       VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2489     } else if (ValVT == MVT::f64 &&
2490                (Subtarget.is64Bit() && !Subtarget.hasSSE2())) {
2491       // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2492       // llvm-gcc has never done it right and no one has noticed, so this
2493       // should be OK for now.
2494       errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
2495       VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2496     }
2497 
2498     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2499     // the RET instruction and handled by the FP Stackifier.
2500     if (VA.getLocReg() == X86::FP0 ||
2501         VA.getLocReg() == X86::FP1) {
2502       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2503       // change the value to the FP stack register class.
2504       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2505         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2506       RetOps.push_back(ValToCopy);
2507       // Don't emit a copytoreg.
2508       continue;
2509     }
2510 
2511     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2512     // which is returned in RAX / RDX.
2513     if (Subtarget.is64Bit()) {
2514       if (ValVT == MVT::x86mmx) {
2515         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2516           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2517           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2518                                   ValToCopy);
2519           // If we don't have SSE2 available, convert to v4f32 so the generated
2520           // register is legal.
2521           if (!Subtarget.hasSSE2())
2522             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2523         }
2524       }
2525     }
2526 
2527     SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2528 
2529     if (VA.needsCustom()) {
2530       assert(VA.getValVT() == MVT::v64i1 &&
2531              "Currently the only custom case is when we split v64i1 to 2 regs");
2532 
2533       Passv64i1ArgInRegs(dl, DAG, Chain, ValToCopy, RegsToPass, VA, RVLocs[++I],
2534                          Subtarget);
2535 
2536       assert(2 == RegsToPass.size() &&
2537              "Expecting two registers after Pass64BitArgInRegs");
2538 
2539       // Add the second register to the CalleeSaveDisableRegs list.
2540       if (ShouldDisableCalleeSavedRegister)
2541         MF.getRegInfo().disableCalleeSavedRegister(RVLocs[I].getLocReg());
2542     } else {
2543       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
2544     }
2545 
2546     // Add nodes to the DAG and add the values into the RetOps list
2547     for (auto &Reg : RegsToPass) {
2548       Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, Flag);
2549       Flag = Chain.getValue(1);
2550       RetOps.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
2551     }
2552   }
2553 
2554   // Swift calling convention does not require we copy the sret argument
2555   // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
2556 
2557   // All x86 ABIs require that for returning structs by value we copy
2558   // the sret argument into %rax/%eax (depending on ABI) for the return.
2559   // We saved the argument into a virtual register in the entry block,
2560   // so now we copy the value out and into %rax/%eax.
2561   //
2562   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2563   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2564   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2565   // either case FuncInfo->setSRetReturnReg() will have been called.
2566   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2567     // When we have both sret and another return value, we should use the
2568     // original Chain stored in RetOps[0], instead of the current Chain updated
2569     // in the above loop. If we only have sret, RetOps[0] equals to Chain.
2570 
2571     // For the case of sret and another return value, we have
2572     //   Chain_0 at the function entry
2573     //   Chain_1 = getCopyToReg(Chain_0) in the above loop
2574     // If we use Chain_1 in getCopyFromReg, we will have
2575     //   Val = getCopyFromReg(Chain_1)
2576     //   Chain_2 = getCopyToReg(Chain_1, Val) from below
2577 
2578     // getCopyToReg(Chain_0) will be glued together with
2579     // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
2580     // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
2581     //   Data dependency from Unit B to Unit A due to usage of Val in
2582     //     getCopyToReg(Chain_1, Val)
2583     //   Chain dependency from Unit A to Unit B
2584 
2585     // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
2586     SDValue Val = DAG.getCopyFromReg(RetOps[0], dl, SRetReg,
2587                                      getPointerTy(MF.getDataLayout()));
2588 
2589     unsigned RetValReg
2590         = (Subtarget.is64Bit() && !Subtarget.isTarget64BitILP32()) ?
2591           X86::RAX : X86::EAX;
2592     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2593     Flag = Chain.getValue(1);
2594 
2595     // RAX/EAX now acts like a return value.
2596     RetOps.push_back(
2597         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2598 
2599     // Add the returned register to the CalleeSaveDisableRegs list.
2600     if (ShouldDisableCalleeSavedRegister)
2601       MF.getRegInfo().disableCalleeSavedRegister(RetValReg);
2602   }
2603 
2604   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
2605   const MCPhysReg *I =
2606       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2607   if (I) {
2608     for (; *I; ++I) {
2609       if (X86::GR64RegClass.contains(*I))
2610         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2611       else
2612         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2613     }
2614   }
2615 
2616   RetOps[0] = Chain;  // Update chain.
2617 
2618   // Add the flag if we have it.
2619   if (Flag.getNode())
2620     RetOps.push_back(Flag);
2621 
2622   X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2623   if (CallConv == CallingConv::X86_INTR)
2624     opcode = X86ISD::IRET;
2625   return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2626 }
2627 
isUsedByReturnOnly(SDNode * N,SDValue & Chain) const2628 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2629   if (N->getNumValues() != 1 || !N->hasNUsesOfValue(1, 0))
2630     return false;
2631 
2632   SDValue TCChain = Chain;
2633   SDNode *Copy = *N->use_begin();
2634   if (Copy->getOpcode() == ISD::CopyToReg) {
2635     // If the copy has a glue operand, we conservatively assume it isn't safe to
2636     // perform a tail call.
2637     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2638       return false;
2639     TCChain = Copy->getOperand(0);
2640   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2641     return false;
2642 
2643   bool HasRet = false;
2644   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2645        UI != UE; ++UI) {
2646     if (UI->getOpcode() != X86ISD::RET_FLAG)
2647       return false;
2648     // If we are returning more than one value, we can definitely
2649     // not make a tail call see PR19530
2650     if (UI->getNumOperands() > 4)
2651       return false;
2652     if (UI->getNumOperands() == 4 &&
2653         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2654       return false;
2655     HasRet = true;
2656   }
2657 
2658   if (!HasRet)
2659     return false;
2660 
2661   Chain = TCChain;
2662   return true;
2663 }
2664 
getTypeForExtReturn(LLVMContext & Context,EVT VT,ISD::NodeType ExtendKind) const2665 EVT X86TargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
2666                                            ISD::NodeType ExtendKind) const {
2667   MVT ReturnMVT = MVT::i32;
2668 
2669   bool Darwin = Subtarget.getTargetTriple().isOSDarwin();
2670   if (VT == MVT::i1 || (!Darwin && (VT == MVT::i8 || VT == MVT::i16))) {
2671     // The ABI does not require i1, i8 or i16 to be extended.
2672     //
2673     // On Darwin, there is code in the wild relying on Clang's old behaviour of
2674     // always extending i8/i16 return values, so keep doing that for now.
2675     // (PR26665).
2676     ReturnMVT = MVT::i8;
2677   }
2678 
2679   EVT MinVT = getRegisterType(Context, ReturnMVT);
2680   return VT.bitsLT(MinVT) ? MinVT : VT;
2681 }
2682 
2683 /// Reads two 32 bit registers and creates a 64 bit mask value.
2684 /// \param VA The current 32 bit value that need to be assigned.
2685 /// \param NextVA The next 32 bit value that need to be assigned.
2686 /// \param Root The parent DAG node.
2687 /// \param [in,out] InFlag Represents SDvalue in the parent DAG node for
2688 ///                        glue purposes. In the case the DAG is already using
2689 ///                        physical register instead of virtual, we should glue
2690 ///                        our new SDValue to InFlag SDvalue.
2691 /// \return a new SDvalue of size 64bit.
getv64i1Argument(CCValAssign & VA,CCValAssign & NextVA,SDValue & Root,SelectionDAG & DAG,const SDLoc & Dl,const X86Subtarget & Subtarget,SDValue * InFlag=nullptr)2692 static SDValue getv64i1Argument(CCValAssign &VA, CCValAssign &NextVA,
2693                                 SDValue &Root, SelectionDAG &DAG,
2694                                 const SDLoc &Dl, const X86Subtarget &Subtarget,
2695                                 SDValue *InFlag = nullptr) {
2696   assert((Subtarget.hasBWI()) && "Expected AVX512BW target!");
2697   assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2698   assert(VA.getValVT() == MVT::v64i1 &&
2699          "Expecting first location of 64 bit width type");
2700   assert(NextVA.getValVT() == VA.getValVT() &&
2701          "The locations should have the same type");
2702   assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2703          "The values should reside in two registers");
2704 
2705   SDValue Lo, Hi;
2706   unsigned Reg;
2707   SDValue ArgValueLo, ArgValueHi;
2708 
2709   MachineFunction &MF = DAG.getMachineFunction();
2710   const TargetRegisterClass *RC = &X86::GR32RegClass;
2711 
2712   // Read a 32 bit value from the registers.
2713   if (nullptr == InFlag) {
2714     // When no physical register is present,
2715     // create an intermediate virtual register.
2716     Reg = MF.addLiveIn(VA.getLocReg(), RC);
2717     ArgValueLo = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2718     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2719     ArgValueHi = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2720   } else {
2721     // When a physical register is available read the value from it and glue
2722     // the reads together.
2723     ArgValueLo =
2724       DAG.getCopyFromReg(Root, Dl, VA.getLocReg(), MVT::i32, *InFlag);
2725     *InFlag = ArgValueLo.getValue(2);
2726     ArgValueHi =
2727       DAG.getCopyFromReg(Root, Dl, NextVA.getLocReg(), MVT::i32, *InFlag);
2728     *InFlag = ArgValueHi.getValue(2);
2729   }
2730 
2731   // Convert the i32 type into v32i1 type.
2732   Lo = DAG.getBitcast(MVT::v32i1, ArgValueLo);
2733 
2734   // Convert the i32 type into v32i1 type.
2735   Hi = DAG.getBitcast(MVT::v32i1, ArgValueHi);
2736 
2737   // Concatenate the two values together.
2738   return DAG.getNode(ISD::CONCAT_VECTORS, Dl, MVT::v64i1, Lo, Hi);
2739 }
2740 
2741 /// The function will lower a register of various sizes (8/16/32/64)
2742 /// to a mask value of the expected size (v8i1/v16i1/v32i1/v64i1)
2743 /// \returns a DAG node contains the operand after lowering to mask type.
lowerRegToMasks(const SDValue & ValArg,const EVT & ValVT,const EVT & ValLoc,const SDLoc & Dl,SelectionDAG & DAG)2744 static SDValue lowerRegToMasks(const SDValue &ValArg, const EVT &ValVT,
2745                                const EVT &ValLoc, const SDLoc &Dl,
2746                                SelectionDAG &DAG) {
2747   SDValue ValReturned = ValArg;
2748 
2749   if (ValVT == MVT::v1i1)
2750     return DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v1i1, ValReturned);
2751 
2752   if (ValVT == MVT::v64i1) {
2753     // In 32 bit machine, this case is handled by getv64i1Argument
2754     assert(ValLoc == MVT::i64 && "Expecting only i64 locations");
2755     // In 64 bit machine, There is no need to truncate the value only bitcast
2756   } else {
2757     MVT maskLen;
2758     switch (ValVT.getSimpleVT().SimpleTy) {
2759     case MVT::v8i1:
2760       maskLen = MVT::i8;
2761       break;
2762     case MVT::v16i1:
2763       maskLen = MVT::i16;
2764       break;
2765     case MVT::v32i1:
2766       maskLen = MVT::i32;
2767       break;
2768     default:
2769       llvm_unreachable("Expecting a vector of i1 types");
2770     }
2771 
2772     ValReturned = DAG.getNode(ISD::TRUNCATE, Dl, maskLen, ValReturned);
2773   }
2774   return DAG.getBitcast(ValVT, ValReturned);
2775 }
2776 
2777 /// Lower the result values of a call into the
2778 /// appropriate copies out of appropriate physical registers.
2779 ///
LowerCallResult(SDValue Chain,SDValue InFlag,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals,uint32_t * RegMask) const2780 SDValue X86TargetLowering::LowerCallResult(
2781     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2782     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2783     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
2784     uint32_t *RegMask) const {
2785 
2786   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2787   // Assign locations to each value returned by this call.
2788   SmallVector<CCValAssign, 16> RVLocs;
2789   bool Is64Bit = Subtarget.is64Bit();
2790   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2791                  *DAG.getContext());
2792   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2793 
2794   // Copy all of the result registers out of their specified physreg.
2795   for (unsigned I = 0, InsIndex = 0, E = RVLocs.size(); I != E;
2796        ++I, ++InsIndex) {
2797     CCValAssign &VA = RVLocs[I];
2798     EVT CopyVT = VA.getLocVT();
2799 
2800     // In some calling conventions we need to remove the used registers
2801     // from the register mask.
2802     if (RegMask) {
2803       for (MCSubRegIterator SubRegs(VA.getLocReg(), TRI, /*IncludeSelf=*/true);
2804            SubRegs.isValid(); ++SubRegs)
2805         RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
2806     }
2807 
2808     // If this is x86-64, and we disabled SSE, we can't return FP values
2809     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2810         ((Is64Bit || Ins[InsIndex].Flags.isInReg()) && !Subtarget.hasSSE1())) {
2811       errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2812       VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2813     }
2814 
2815     // If we prefer to use the value in xmm registers, copy it out as f80 and
2816     // use a truncate to move it from fp stack reg to xmm reg.
2817     bool RoundAfterCopy = false;
2818     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2819         isScalarFPTypeInSSEReg(VA.getValVT())) {
2820       if (!Subtarget.hasX87())
2821         report_fatal_error("X87 register return with X87 disabled");
2822       CopyVT = MVT::f80;
2823       RoundAfterCopy = (CopyVT != VA.getLocVT());
2824     }
2825 
2826     SDValue Val;
2827     if (VA.needsCustom()) {
2828       assert(VA.getValVT() == MVT::v64i1 &&
2829              "Currently the only custom case is when we split v64i1 to 2 regs");
2830       Val =
2831           getv64i1Argument(VA, RVLocs[++I], Chain, DAG, dl, Subtarget, &InFlag);
2832     } else {
2833       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), CopyVT, InFlag)
2834                   .getValue(1);
2835       Val = Chain.getValue(0);
2836       InFlag = Chain.getValue(2);
2837     }
2838 
2839     if (RoundAfterCopy)
2840       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2841                         // This truncation won't change the value.
2842                         DAG.getIntPtrConstant(1, dl));
2843 
2844     if (VA.isExtInLoc() && (VA.getValVT().getScalarType() == MVT::i1)) {
2845       if (VA.getValVT().isVector() &&
2846           ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
2847            (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
2848         // promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
2849         Val = lowerRegToMasks(Val, VA.getValVT(), VA.getLocVT(), dl, DAG);
2850       } else
2851         Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2852     }
2853 
2854     InVals.push_back(Val);
2855   }
2856 
2857   return Chain;
2858 }
2859 
2860 //===----------------------------------------------------------------------===//
2861 //                C & StdCall & Fast Calling Convention implementation
2862 //===----------------------------------------------------------------------===//
2863 //  StdCall calling convention seems to be standard for many Windows' API
2864 //  routines and around. It differs from C calling convention just a little:
2865 //  callee should clean up the stack, not caller. Symbols should be also
2866 //  decorated in some fancy way :) It doesn't support any vector arguments.
2867 //  For info on fast calling convention see Fast Calling Convention (tail call)
2868 //  implementation LowerX86_32FastCCCallTo.
2869 
2870 /// CallIsStructReturn - Determines whether a call uses struct return
2871 /// semantics.
2872 enum StructReturnType {
2873   NotStructReturn,
2874   RegStructReturn,
2875   StackStructReturn
2876 };
2877 static StructReturnType
callIsStructReturn(ArrayRef<ISD::OutputArg> Outs,bool IsMCU)2878 callIsStructReturn(ArrayRef<ISD::OutputArg> Outs, bool IsMCU) {
2879   if (Outs.empty())
2880     return NotStructReturn;
2881 
2882   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2883   if (!Flags.isSRet())
2884     return NotStructReturn;
2885   if (Flags.isInReg() || IsMCU)
2886     return RegStructReturn;
2887   return StackStructReturn;
2888 }
2889 
2890 /// Determines whether a function uses struct return semantics.
2891 static StructReturnType
argsAreStructReturn(ArrayRef<ISD::InputArg> Ins,bool IsMCU)2892 argsAreStructReturn(ArrayRef<ISD::InputArg> Ins, bool IsMCU) {
2893   if (Ins.empty())
2894     return NotStructReturn;
2895 
2896   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2897   if (!Flags.isSRet())
2898     return NotStructReturn;
2899   if (Flags.isInReg() || IsMCU)
2900     return RegStructReturn;
2901   return StackStructReturn;
2902 }
2903 
2904 /// Make a copy of an aggregate at address specified by "Src" to address
2905 /// "Dst" with size and alignment information specified by the specific
2906 /// parameter attribute. The copy will be passed as a byval function parameter.
CreateCopyOfByValArgument(SDValue Src,SDValue Dst,SDValue Chain,ISD::ArgFlagsTy Flags,SelectionDAG & DAG,const SDLoc & dl)2907 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
2908                                          SDValue Chain, ISD::ArgFlagsTy Flags,
2909                                          SelectionDAG &DAG, const SDLoc &dl) {
2910   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2911 
2912   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2913                        /*isVolatile*/false, /*AlwaysInline=*/true,
2914                        /*isTailCall*/false,
2915                        MachinePointerInfo(), MachinePointerInfo());
2916 }
2917 
2918 /// Return true if the calling convention is one that we can guarantee TCO for.
canGuaranteeTCO(CallingConv::ID CC)2919 static bool canGuaranteeTCO(CallingConv::ID CC) {
2920   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2921           CC == CallingConv::X86_RegCall || CC == CallingConv::HiPE ||
2922           CC == CallingConv::HHVM);
2923 }
2924 
2925 /// Return true if we might ever do TCO for calls with this calling convention.
mayTailCallThisCC(CallingConv::ID CC)2926 static bool mayTailCallThisCC(CallingConv::ID CC) {
2927   switch (CC) {
2928   // C calling conventions:
2929   case CallingConv::C:
2930   case CallingConv::Win64:
2931   case CallingConv::X86_64_SysV:
2932   // Callee pop conventions:
2933   case CallingConv::X86_ThisCall:
2934   case CallingConv::X86_StdCall:
2935   case CallingConv::X86_VectorCall:
2936   case CallingConv::X86_FastCall:
2937     return true;
2938   default:
2939     return canGuaranteeTCO(CC);
2940   }
2941 }
2942 
2943 /// Return true if the function is being made into a tailcall target by
2944 /// changing its ABI.
shouldGuaranteeTCO(CallingConv::ID CC,bool GuaranteedTailCallOpt)2945 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2946   return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2947 }
2948 
mayBeEmittedAsTailCall(const CallInst * CI) const2949 bool X86TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2950   auto Attr =
2951       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2952   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2953     return false;
2954 
2955   ImmutableCallSite CS(CI);
2956   CallingConv::ID CalleeCC = CS.getCallingConv();
2957   if (!mayTailCallThisCC(CalleeCC))
2958     return false;
2959 
2960   return true;
2961 }
2962 
2963 SDValue
LowerMemArgument(SDValue Chain,CallingConv::ID CallConv,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,const CCValAssign & VA,MachineFrameInfo & MFI,unsigned i) const2964 X86TargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
2965                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2966                                     const SDLoc &dl, SelectionDAG &DAG,
2967                                     const CCValAssign &VA,
2968                                     MachineFrameInfo &MFI, unsigned i) const {
2969   // Create the nodes corresponding to a load from this parameter slot.
2970   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2971   bool AlwaysUseMutable = shouldGuaranteeTCO(
2972       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2973   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2974   EVT ValVT;
2975   MVT PtrVT = getPointerTy(DAG.getDataLayout());
2976 
2977   // If value is passed by pointer we have address passed instead of the value
2978   // itself. No need to extend if the mask value and location share the same
2979   // absolute size.
2980   bool ExtendedInMem =
2981       VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1 &&
2982       VA.getValVT().getSizeInBits() != VA.getLocVT().getSizeInBits();
2983 
2984   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2985     ValVT = VA.getLocVT();
2986   else
2987     ValVT = VA.getValVT();
2988 
2989   // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2990   // taken by a return address.
2991   int Offset = 0;
2992   if (CallConv == CallingConv::X86_INTR) {
2993     // X86 interrupts may take one or two arguments.
2994     // On the stack there will be no return address as in regular call.
2995     // Offset of last argument need to be set to -4/-8 bytes.
2996     // Where offset of the first argument out of two, should be set to 0 bytes.
2997     Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2998     if (Subtarget.is64Bit() && Ins.size() == 2) {
2999       // The stack pointer needs to be realigned for 64 bit handlers with error
3000       // code, so the argument offset changes by 8 bytes.
3001       Offset += 8;
3002     }
3003   }
3004 
3005   // FIXME: For now, all byval parameter objects are marked mutable. This can be
3006   // changed with more analysis.
3007   // In case of tail call optimization mark all arguments mutable. Since they
3008   // could be overwritten by lowering of arguments in case of a tail call.
3009   if (Flags.isByVal()) {
3010     unsigned Bytes = Flags.getByValSize();
3011     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
3012 
3013     // FIXME: For now, all byval parameter objects are marked as aliasing. This
3014     // can be improved with deeper analysis.
3015     int FI = MFI.CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable,
3016                                    /*isAliased=*/true);
3017     // Adjust SP offset of interrupt parameter.
3018     if (CallConv == CallingConv::X86_INTR) {
3019       MFI.setObjectOffset(FI, Offset);
3020     }
3021     return DAG.getFrameIndex(FI, PtrVT);
3022   }
3023 
3024   // This is an argument in memory. We might be able to perform copy elision.
3025   if (Flags.isCopyElisionCandidate()) {
3026     EVT ArgVT = Ins[i].ArgVT;
3027     SDValue PartAddr;
3028     if (Ins[i].PartOffset == 0) {
3029       // If this is a one-part value or the first part of a multi-part value,
3030       // create a stack object for the entire argument value type and return a
3031       // load from our portion of it. This assumes that if the first part of an
3032       // argument is in memory, the rest will also be in memory.
3033       int FI = MFI.CreateFixedObject(ArgVT.getStoreSize(), VA.getLocMemOffset(),
3034                                      /*Immutable=*/false);
3035       PartAddr = DAG.getFrameIndex(FI, PtrVT);
3036       return DAG.getLoad(
3037           ValVT, dl, Chain, PartAddr,
3038           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3039     } else {
3040       // This is not the first piece of an argument in memory. See if there is
3041       // already a fixed stack object including this offset. If so, assume it
3042       // was created by the PartOffset == 0 branch above and create a load from
3043       // the appropriate offset into it.
3044       int64_t PartBegin = VA.getLocMemOffset();
3045       int64_t PartEnd = PartBegin + ValVT.getSizeInBits() / 8;
3046       int FI = MFI.getObjectIndexBegin();
3047       for (; MFI.isFixedObjectIndex(FI); ++FI) {
3048         int64_t ObjBegin = MFI.getObjectOffset(FI);
3049         int64_t ObjEnd = ObjBegin + MFI.getObjectSize(FI);
3050         if (ObjBegin <= PartBegin && PartEnd <= ObjEnd)
3051           break;
3052       }
3053       if (MFI.isFixedObjectIndex(FI)) {
3054         SDValue Addr =
3055             DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getFrameIndex(FI, PtrVT),
3056                         DAG.getIntPtrConstant(Ins[i].PartOffset, dl));
3057         return DAG.getLoad(
3058             ValVT, dl, Chain, Addr,
3059             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI,
3060                                               Ins[i].PartOffset));
3061       }
3062     }
3063   }
3064 
3065   int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
3066                                  VA.getLocMemOffset(), isImmutable);
3067 
3068   // Set SExt or ZExt flag.
3069   if (VA.getLocInfo() == CCValAssign::ZExt) {
3070     MFI.setObjectZExt(FI, true);
3071   } else if (VA.getLocInfo() == CCValAssign::SExt) {
3072     MFI.setObjectSExt(FI, true);
3073   }
3074 
3075   // Adjust SP offset of interrupt parameter.
3076   if (CallConv == CallingConv::X86_INTR) {
3077     MFI.setObjectOffset(FI, Offset);
3078   }
3079 
3080   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3081   SDValue Val = DAG.getLoad(
3082       ValVT, dl, Chain, FIN,
3083       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3084   return ExtendedInMem
3085              ? (VA.getValVT().isVector()
3086                     ? DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VA.getValVT(), Val)
3087                     : DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val))
3088              : Val;
3089 }
3090 
3091 // FIXME: Get this from tablegen.
get64BitArgumentGPRs(CallingConv::ID CallConv,const X86Subtarget & Subtarget)3092 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
3093                                                 const X86Subtarget &Subtarget) {
3094   assert(Subtarget.is64Bit());
3095 
3096   if (Subtarget.isCallingConvWin64(CallConv)) {
3097     static const MCPhysReg GPR64ArgRegsWin64[] = {
3098       X86::RCX, X86::RDX, X86::R8,  X86::R9
3099     };
3100     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
3101   }
3102 
3103   static const MCPhysReg GPR64ArgRegs64Bit[] = {
3104     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
3105   };
3106   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
3107 }
3108 
3109 // FIXME: Get this from tablegen.
get64BitArgumentXMMs(MachineFunction & MF,CallingConv::ID CallConv,const X86Subtarget & Subtarget)3110 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
3111                                                 CallingConv::ID CallConv,
3112                                                 const X86Subtarget &Subtarget) {
3113   assert(Subtarget.is64Bit());
3114   if (Subtarget.isCallingConvWin64(CallConv)) {
3115     // The XMM registers which might contain var arg parameters are shadowed
3116     // in their paired GPR.  So we only need to save the GPR to their home
3117     // slots.
3118     // TODO: __vectorcall will change this.
3119     return None;
3120   }
3121 
3122   const Function &F = MF.getFunction();
3123   bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
3124   bool isSoftFloat = Subtarget.useSoftFloat();
3125   assert(!(isSoftFloat && NoImplicitFloatOps) &&
3126          "SSE register cannot be used when SSE is disabled!");
3127   if (isSoftFloat || NoImplicitFloatOps || !Subtarget.hasSSE1())
3128     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
3129     // registers.
3130     return None;
3131 
3132   static const MCPhysReg XMMArgRegs64Bit[] = {
3133     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3134     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3135   };
3136   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
3137 }
3138 
3139 #ifndef NDEBUG
isSortedByValueNo(ArrayRef<CCValAssign> ArgLocs)3140 static bool isSortedByValueNo(ArrayRef<CCValAssign> ArgLocs) {
3141   return std::is_sorted(ArgLocs.begin(), ArgLocs.end(),
3142                         [](const CCValAssign &A, const CCValAssign &B) -> bool {
3143                           return A.getValNo() < B.getValNo();
3144                         });
3145 }
3146 #endif
3147 
LowerFormalArguments(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const3148 SDValue X86TargetLowering::LowerFormalArguments(
3149     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3150     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3151     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3152   MachineFunction &MF = DAG.getMachineFunction();
3153   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3154   const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
3155 
3156   const Function &F = MF.getFunction();
3157   if (F.hasExternalLinkage() && Subtarget.isTargetCygMing() &&
3158       F.getName() == "main")
3159     FuncInfo->setForceFramePointer(true);
3160 
3161   MachineFrameInfo &MFI = MF.getFrameInfo();
3162   bool Is64Bit = Subtarget.is64Bit();
3163   bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3164 
3165   assert(
3166       !(isVarArg && canGuaranteeTCO(CallConv)) &&
3167       "Var args not supported with calling conv' regcall, fastcc, ghc or hipe");
3168 
3169   if (CallConv == CallingConv::X86_INTR) {
3170     bool isLegal = Ins.size() == 1 ||
3171                    (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
3172                                         (!Is64Bit && Ins[1].VT == MVT::i32)));
3173     if (!isLegal)
3174       report_fatal_error("X86 interrupts may take one or two arguments");
3175   }
3176 
3177   // Assign locations to all of the incoming arguments.
3178   SmallVector<CCValAssign, 16> ArgLocs;
3179   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3180 
3181   // Allocate shadow area for Win64.
3182   if (IsWin64)
3183     CCInfo.AllocateStack(32, 8);
3184 
3185   CCInfo.AnalyzeArguments(Ins, CC_X86);
3186 
3187   // In vectorcall calling convention a second pass is required for the HVA
3188   // types.
3189   if (CallingConv::X86_VectorCall == CallConv) {
3190     CCInfo.AnalyzeArgumentsSecondPass(Ins, CC_X86);
3191   }
3192 
3193   // The next loop assumes that the locations are in the same order of the
3194   // input arguments.
3195   assert(isSortedByValueNo(ArgLocs) &&
3196          "Argument Location list must be sorted before lowering");
3197 
3198   SDValue ArgValue;
3199   for (unsigned I = 0, InsIndex = 0, E = ArgLocs.size(); I != E;
3200        ++I, ++InsIndex) {
3201     assert(InsIndex < Ins.size() && "Invalid Ins index");
3202     CCValAssign &VA = ArgLocs[I];
3203 
3204     if (VA.isRegLoc()) {
3205       EVT RegVT = VA.getLocVT();
3206       if (VA.needsCustom()) {
3207         assert(
3208             VA.getValVT() == MVT::v64i1 &&
3209             "Currently the only custom case is when we split v64i1 to 2 regs");
3210 
3211         // v64i1 values, in regcall calling convention, that are
3212         // compiled to 32 bit arch, are split up into two registers.
3213         ArgValue =
3214             getv64i1Argument(VA, ArgLocs[++I], Chain, DAG, dl, Subtarget);
3215       } else {
3216         const TargetRegisterClass *RC;
3217         if (RegVT == MVT::i8)
3218           RC = &X86::GR8RegClass;
3219         else if (RegVT == MVT::i16)
3220           RC = &X86::GR16RegClass;
3221         else if (RegVT == MVT::i32)
3222           RC = &X86::GR32RegClass;
3223         else if (Is64Bit && RegVT == MVT::i64)
3224           RC = &X86::GR64RegClass;
3225         else if (RegVT == MVT::f32)
3226           RC = Subtarget.hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
3227         else if (RegVT == MVT::f64)
3228           RC = Subtarget.hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
3229         else if (RegVT == MVT::f80)
3230           RC = &X86::RFP80RegClass;
3231         else if (RegVT == MVT::f128)
3232           RC = &X86::VR128RegClass;
3233         else if (RegVT.is512BitVector())
3234           RC = &X86::VR512RegClass;
3235         else if (RegVT.is256BitVector())
3236           RC = Subtarget.hasVLX() ? &X86::VR256XRegClass : &X86::VR256RegClass;
3237         else if (RegVT.is128BitVector())
3238           RC = Subtarget.hasVLX() ? &X86::VR128XRegClass : &X86::VR128RegClass;
3239         else if (RegVT == MVT::x86mmx)
3240           RC = &X86::VR64RegClass;
3241         else if (RegVT == MVT::v1i1)
3242           RC = &X86::VK1RegClass;
3243         else if (RegVT == MVT::v8i1)
3244           RC = &X86::VK8RegClass;
3245         else if (RegVT == MVT::v16i1)
3246           RC = &X86::VK16RegClass;
3247         else if (RegVT == MVT::v32i1)
3248           RC = &X86::VK32RegClass;
3249         else if (RegVT == MVT::v64i1)
3250           RC = &X86::VK64RegClass;
3251         else
3252           llvm_unreachable("Unknown argument type!");
3253 
3254         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3255         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3256       }
3257 
3258       // If this is an 8 or 16-bit value, it is really passed promoted to 32
3259       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
3260       // right size.
3261       if (VA.getLocInfo() == CCValAssign::SExt)
3262         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3263                                DAG.getValueType(VA.getValVT()));
3264       else if (VA.getLocInfo() == CCValAssign::ZExt)
3265         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3266                                DAG.getValueType(VA.getValVT()));
3267       else if (VA.getLocInfo() == CCValAssign::BCvt)
3268         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
3269 
3270       if (VA.isExtInLoc()) {
3271         // Handle MMX values passed in XMM regs.
3272         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
3273           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
3274         else if (VA.getValVT().isVector() &&
3275                  VA.getValVT().getScalarType() == MVT::i1 &&
3276                  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3277                   (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3278           // Promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3279           ArgValue = lowerRegToMasks(ArgValue, VA.getValVT(), RegVT, dl, DAG);
3280         } else
3281           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3282       }
3283     } else {
3284       assert(VA.isMemLoc());
3285       ArgValue =
3286           LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, InsIndex);
3287     }
3288 
3289     // If value is passed via pointer - do a load.
3290     if (VA.getLocInfo() == CCValAssign::Indirect && !Ins[I].Flags.isByVal())
3291       ArgValue =
3292           DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, MachinePointerInfo());
3293 
3294     InVals.push_back(ArgValue);
3295   }
3296 
3297   for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3298     // Swift calling convention does not require we copy the sret argument
3299     // into %rax/%eax for the return. We don't set SRetReturnReg for Swift.
3300     if (CallConv == CallingConv::Swift)
3301       continue;
3302 
3303     // All x86 ABIs require that for returning structs by value we copy the
3304     // sret argument into %rax/%eax (depending on ABI) for the return. Save
3305     // the argument into a virtual register so that we can access it from the
3306     // return points.
3307     if (Ins[I].Flags.isSRet()) {
3308       unsigned Reg = FuncInfo->getSRetReturnReg();
3309       if (!Reg) {
3310         MVT PtrTy = getPointerTy(DAG.getDataLayout());
3311         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3312         FuncInfo->setSRetReturnReg(Reg);
3313       }
3314       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[I]);
3315       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3316       break;
3317     }
3318   }
3319 
3320   unsigned StackSize = CCInfo.getNextStackOffset();
3321   // Align stack specially for tail calls.
3322   if (shouldGuaranteeTCO(CallConv,
3323                          MF.getTarget().Options.GuaranteedTailCallOpt))
3324     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
3325 
3326   // If the function takes variable number of arguments, make a frame index for
3327   // the start of the first vararg value... for expansion of llvm.va_start. We
3328   // can skip this if there are no va_start calls.
3329   if (MFI.hasVAStart() &&
3330       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
3331                    CallConv != CallingConv::X86_ThisCall))) {
3332     FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
3333   }
3334 
3335   // Figure out if XMM registers are in use.
3336   assert(!(Subtarget.useSoftFloat() &&
3337            F.hasFnAttribute(Attribute::NoImplicitFloat)) &&
3338          "SSE register cannot be used when SSE is disabled!");
3339 
3340   // 64-bit calling conventions support varargs and register parameters, so we
3341   // have to do extra work to spill them in the prologue.
3342   if (Is64Bit && isVarArg && MFI.hasVAStart()) {
3343     // Find the first unallocated argument registers.
3344     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
3345     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
3346     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
3347     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
3348     assert(!(NumXMMRegs && !Subtarget.hasSSE1()) &&
3349            "SSE register cannot be used when SSE is disabled!");
3350 
3351     // Gather all the live in physical registers.
3352     SmallVector<SDValue, 6> LiveGPRs;
3353     SmallVector<SDValue, 8> LiveXMMRegs;
3354     SDValue ALVal;
3355     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
3356       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
3357       LiveGPRs.push_back(
3358           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
3359     }
3360     if (!ArgXMMs.empty()) {
3361       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3362       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
3363       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
3364         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
3365         LiveXMMRegs.push_back(
3366             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
3367       }
3368     }
3369 
3370     if (IsWin64) {
3371       // Get to the caller-allocated home save location.  Add 8 to account
3372       // for the return address.
3373       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
3374       FuncInfo->setRegSaveFrameIndex(
3375           MFI.CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
3376       // Fixup to set vararg frame on shadow area (4 x i64).
3377       if (NumIntRegs < 4)
3378         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
3379     } else {
3380       // For X86-64, if there are vararg parameters that are passed via
3381       // registers, then we must store them to their spots on the stack so
3382       // they may be loaded by dereferencing the result of va_next.
3383       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
3384       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
3385       FuncInfo->setRegSaveFrameIndex(MFI.CreateStackObject(
3386           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
3387     }
3388 
3389     // Store the integer parameter registers.
3390     SmallVector<SDValue, 8> MemOps;
3391     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
3392                                       getPointerTy(DAG.getDataLayout()));
3393     unsigned Offset = FuncInfo->getVarArgsGPOffset();
3394     for (SDValue Val : LiveGPRs) {
3395       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3396                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
3397       SDValue Store =
3398           DAG.getStore(Val.getValue(1), dl, Val, FIN,
3399                        MachinePointerInfo::getFixedStack(
3400                            DAG.getMachineFunction(),
3401                            FuncInfo->getRegSaveFrameIndex(), Offset));
3402       MemOps.push_back(Store);
3403       Offset += 8;
3404     }
3405 
3406     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
3407       // Now store the XMM (fp + vector) parameter registers.
3408       SmallVector<SDValue, 12> SaveXMMOps;
3409       SaveXMMOps.push_back(Chain);
3410       SaveXMMOps.push_back(ALVal);
3411       SaveXMMOps.push_back(DAG.getIntPtrConstant(
3412                              FuncInfo->getRegSaveFrameIndex(), dl));
3413       SaveXMMOps.push_back(DAG.getIntPtrConstant(
3414                              FuncInfo->getVarArgsFPOffset(), dl));
3415       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
3416                         LiveXMMRegs.end());
3417       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
3418                                    MVT::Other, SaveXMMOps));
3419     }
3420 
3421     if (!MemOps.empty())
3422       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3423   }
3424 
3425   if (isVarArg && MFI.hasMustTailInVarArgFunc()) {
3426     // Find the largest legal vector type.
3427     MVT VecVT = MVT::Other;
3428     // FIXME: Only some x86_32 calling conventions support AVX512.
3429     if (Subtarget.hasAVX512() &&
3430         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
3431                      CallConv == CallingConv::Intel_OCL_BI)))
3432       VecVT = MVT::v16f32;
3433     else if (Subtarget.hasAVX())
3434       VecVT = MVT::v8f32;
3435     else if (Subtarget.hasSSE2())
3436       VecVT = MVT::v4f32;
3437 
3438     // We forward some GPRs and some vector types.
3439     SmallVector<MVT, 2> RegParmTypes;
3440     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
3441     RegParmTypes.push_back(IntVT);
3442     if (VecVT != MVT::Other)
3443       RegParmTypes.push_back(VecVT);
3444 
3445     // Compute the set of forwarded registers. The rest are scratch.
3446     SmallVectorImpl<ForwardedRegister> &Forwards =
3447         FuncInfo->getForwardedMustTailRegParms();
3448     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
3449 
3450     // Conservatively forward AL on x86_64, since it might be used for varargs.
3451     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
3452       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3453       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
3454     }
3455 
3456     // Copy all forwards from physical to virtual registers.
3457     for (ForwardedRegister &F : Forwards) {
3458       // FIXME: Can we use a less constrained schedule?
3459       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3460       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
3461       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
3462     }
3463   }
3464 
3465   // Some CCs need callee pop.
3466   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3467                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
3468     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
3469   } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
3470     // X86 interrupts must pop the error code (and the alignment padding) if
3471     // present.
3472     FuncInfo->setBytesToPopOnReturn(Is64Bit ? 16 : 4);
3473   } else {
3474     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
3475     // If this is an sret function, the return should pop the hidden pointer.
3476     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3477         !Subtarget.getTargetTriple().isOSMSVCRT() &&
3478         argsAreStructReturn(Ins, Subtarget.isTargetMCU()) == StackStructReturn)
3479       FuncInfo->setBytesToPopOnReturn(4);
3480   }
3481 
3482   if (!Is64Bit) {
3483     // RegSaveFrameIndex is X86-64 only.
3484     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
3485     if (CallConv == CallingConv::X86_FastCall ||
3486         CallConv == CallingConv::X86_ThisCall)
3487       // fastcc functions can't have varargs.
3488       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
3489   }
3490 
3491   FuncInfo->setArgumentStackSize(StackSize);
3492 
3493   if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
3494     EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
3495     if (Personality == EHPersonality::CoreCLR) {
3496       assert(Is64Bit);
3497       // TODO: Add a mechanism to frame lowering that will allow us to indicate
3498       // that we'd prefer this slot be allocated towards the bottom of the frame
3499       // (i.e. near the stack pointer after allocating the frame).  Every
3500       // funclet needs a copy of this slot in its (mostly empty) frame, and the
3501       // offset from the bottom of this and each funclet's frame must be the
3502       // same, so the size of funclets' (mostly empty) frames is dictated by
3503       // how far this slot is from the bottom (since they allocate just enough
3504       // space to accommodate holding this slot at the correct offset).
3505       int PSPSymFI = MFI.CreateStackObject(8, 8, /*isSS=*/false);
3506       EHInfo->PSPSymFrameIdx = PSPSymFI;
3507     }
3508   }
3509 
3510   if (CallConv == CallingConv::X86_RegCall ||
3511       F.hasFnAttribute("no_caller_saved_registers")) {
3512     MachineRegisterInfo &MRI = MF.getRegInfo();
3513     for (std::pair<unsigned, unsigned> Pair : MRI.liveins())
3514       MRI.disableCalleeSavedRegister(Pair.first);
3515   }
3516 
3517   return Chain;
3518 }
3519 
LowerMemOpCallTo(SDValue Chain,SDValue StackPtr,SDValue Arg,const SDLoc & dl,SelectionDAG & DAG,const CCValAssign & VA,ISD::ArgFlagsTy Flags) const3520 SDValue X86TargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
3521                                             SDValue Arg, const SDLoc &dl,
3522                                             SelectionDAG &DAG,
3523                                             const CCValAssign &VA,
3524                                             ISD::ArgFlagsTy Flags) const {
3525   unsigned LocMemOffset = VA.getLocMemOffset();
3526   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3527   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3528                        StackPtr, PtrOff);
3529   if (Flags.isByVal())
3530     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3531 
3532   return DAG.getStore(
3533       Chain, dl, Arg, PtrOff,
3534       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
3535 }
3536 
3537 /// Emit a load of return address if tail call
3538 /// optimization is performed and it is required.
EmitTailCallLoadRetAddr(SelectionDAG & DAG,SDValue & OutRetAddr,SDValue Chain,bool IsTailCall,bool Is64Bit,int FPDiff,const SDLoc & dl) const3539 SDValue X86TargetLowering::EmitTailCallLoadRetAddr(
3540     SelectionDAG &DAG, SDValue &OutRetAddr, SDValue Chain, bool IsTailCall,
3541     bool Is64Bit, int FPDiff, const SDLoc &dl) const {
3542   // Adjust the Return address stack slot.
3543   EVT VT = getPointerTy(DAG.getDataLayout());
3544   OutRetAddr = getReturnAddressFrameIndex(DAG);
3545 
3546   // Load the "old" Return address.
3547   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo());
3548   return SDValue(OutRetAddr.getNode(), 1);
3549 }
3550 
3551 /// Emit a store of the return address if tail call
3552 /// optimization is performed and it is required (FPDiff!=0).
EmitTailCallStoreRetAddr(SelectionDAG & DAG,MachineFunction & MF,SDValue Chain,SDValue RetAddrFrIdx,EVT PtrVT,unsigned SlotSize,int FPDiff,const SDLoc & dl)3553 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3554                                         SDValue Chain, SDValue RetAddrFrIdx,
3555                                         EVT PtrVT, unsigned SlotSize,
3556                                         int FPDiff, const SDLoc &dl) {
3557   // Store the return address to the appropriate stack slot.
3558   if (!FPDiff) return Chain;
3559   // Calculate the new stack slot for the return address.
3560   int NewReturnAddrFI =
3561     MF.getFrameInfo().CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3562                                          false);
3563   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3564   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3565                        MachinePointerInfo::getFixedStack(
3566                            DAG.getMachineFunction(), NewReturnAddrFI));
3567   return Chain;
3568 }
3569 
3570 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3571 /// operation of specified width.
getMOVL(SelectionDAG & DAG,const SDLoc & dl,MVT VT,SDValue V1,SDValue V2)3572 static SDValue getMOVL(SelectionDAG &DAG, const SDLoc &dl, MVT VT, SDValue V1,
3573                        SDValue V2) {
3574   unsigned NumElems = VT.getVectorNumElements();
3575   SmallVector<int, 8> Mask;
3576   Mask.push_back(NumElems);
3577   for (unsigned i = 1; i != NumElems; ++i)
3578     Mask.push_back(i);
3579   return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
3580 }
3581 
3582 SDValue
LowerCall(TargetLowering::CallLoweringInfo & CLI,SmallVectorImpl<SDValue> & InVals) const3583 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3584                              SmallVectorImpl<SDValue> &InVals) const {
3585   SelectionDAG &DAG                     = CLI.DAG;
3586   SDLoc &dl                             = CLI.DL;
3587   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3588   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3589   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3590   SDValue Chain                         = CLI.Chain;
3591   SDValue Callee                        = CLI.Callee;
3592   CallingConv::ID CallConv              = CLI.CallConv;
3593   bool &isTailCall                      = CLI.IsTailCall;
3594   bool isVarArg                         = CLI.IsVarArg;
3595 
3596   MachineFunction &MF = DAG.getMachineFunction();
3597   bool Is64Bit        = Subtarget.is64Bit();
3598   bool IsWin64        = Subtarget.isCallingConvWin64(CallConv);
3599   StructReturnType SR = callIsStructReturn(Outs, Subtarget.isTargetMCU());
3600   bool IsSibcall      = false;
3601   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3602   auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
3603   const auto *CI = dyn_cast_or_null<CallInst>(CLI.CS.getInstruction());
3604   const Function *Fn = CI ? CI->getCalledFunction() : nullptr;
3605   bool HasNCSR = (CI && CI->hasFnAttr("no_caller_saved_registers")) ||
3606                  (Fn && Fn->hasFnAttribute("no_caller_saved_registers"));
3607   const auto *II = dyn_cast_or_null<InvokeInst>(CLI.CS.getInstruction());
3608   bool HasNoCfCheck =
3609       (CI && CI->doesNoCfCheck()) || (II && II->doesNoCfCheck());
3610   const Module *M = MF.getMMI().getModule();
3611   Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
3612 
3613   if (CallConv == CallingConv::X86_INTR)
3614     report_fatal_error("X86 interrupts may not be called directly");
3615 
3616   if (Attr.getValueAsString() == "true")
3617     isTailCall = false;
3618 
3619   if (Subtarget.isPICStyleGOT() &&
3620       !MF.getTarget().Options.GuaranteedTailCallOpt) {
3621     // If we are using a GOT, disable tail calls to external symbols with
3622     // default visibility. Tail calling such a symbol requires using a GOT
3623     // relocation, which forces early binding of the symbol. This breaks code
3624     // that require lazy function symbol resolution. Using musttail or
3625     // GuaranteedTailCallOpt will override this.
3626     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3627     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3628                G->getGlobal()->hasDefaultVisibility()))
3629       isTailCall = false;
3630   }
3631 
3632   bool IsMustTail = CLI.CS && CLI.CS.isMustTailCall();
3633   if (IsMustTail) {
3634     // Force this to be a tail call.  The verifier rules are enough to ensure
3635     // that we can lower this successfully without moving the return address
3636     // around.
3637     isTailCall = true;
3638   } else if (isTailCall) {
3639     // Check if it's really possible to do a tail call.
3640     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3641                     isVarArg, SR != NotStructReturn,
3642                     MF.getFunction().hasStructRetAttr(), CLI.RetTy,
3643                     Outs, OutVals, Ins, DAG);
3644 
3645     // Sibcalls are automatically detected tailcalls which do not require
3646     // ABI changes.
3647     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3648       IsSibcall = true;
3649 
3650     if (isTailCall)
3651       ++NumTailCalls;
3652   }
3653 
3654   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3655          "Var args not supported with calling convention fastcc, ghc or hipe");
3656 
3657   // Analyze operands of the call, assigning locations to each operand.
3658   SmallVector<CCValAssign, 16> ArgLocs;
3659   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3660 
3661   // Allocate shadow area for Win64.
3662   if (IsWin64)
3663     CCInfo.AllocateStack(32, 8);
3664 
3665   CCInfo.AnalyzeArguments(Outs, CC_X86);
3666 
3667   // In vectorcall calling convention a second pass is required for the HVA
3668   // types.
3669   if (CallingConv::X86_VectorCall == CallConv) {
3670     CCInfo.AnalyzeArgumentsSecondPass(Outs, CC_X86);
3671   }
3672 
3673   // Get a count of how many bytes are to be pushed on the stack.
3674   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3675   if (IsSibcall)
3676     // This is a sibcall. The memory operands are available in caller's
3677     // own caller's stack.
3678     NumBytes = 0;
3679   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3680            canGuaranteeTCO(CallConv))
3681     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3682 
3683   int FPDiff = 0;
3684   if (isTailCall && !IsSibcall && !IsMustTail) {
3685     // Lower arguments at fp - stackoffset + fpdiff.
3686     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3687 
3688     FPDiff = NumBytesCallerPushed - NumBytes;
3689 
3690     // Set the delta of movement of the returnaddr stackslot.
3691     // But only set if delta is greater than previous delta.
3692     if (FPDiff < X86Info->getTCReturnAddrDelta())
3693       X86Info->setTCReturnAddrDelta(FPDiff);
3694   }
3695 
3696   unsigned NumBytesToPush = NumBytes;
3697   unsigned NumBytesToPop = NumBytes;
3698 
3699   // If we have an inalloca argument, all stack space has already been allocated
3700   // for us and be right at the top of the stack.  We don't support multiple
3701   // arguments passed in memory when using inalloca.
3702   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3703     NumBytesToPush = 0;
3704     if (!ArgLocs.back().isMemLoc())
3705       report_fatal_error("cannot use inalloca attribute on a register "
3706                          "parameter");
3707     if (ArgLocs.back().getLocMemOffset() != 0)
3708       report_fatal_error("any parameter with the inalloca attribute must be "
3709                          "the only memory argument");
3710   }
3711 
3712   if (!IsSibcall)
3713     Chain = DAG.getCALLSEQ_START(Chain, NumBytesToPush,
3714                                  NumBytes - NumBytesToPush, dl);
3715 
3716   SDValue RetAddrFrIdx;
3717   // Load return address for tail calls.
3718   if (isTailCall && FPDiff)
3719     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3720                                     Is64Bit, FPDiff, dl);
3721 
3722   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3723   SmallVector<SDValue, 8> MemOpChains;
3724   SDValue StackPtr;
3725 
3726   // The next loop assumes that the locations are in the same order of the
3727   // input arguments.
3728   assert(isSortedByValueNo(ArgLocs) &&
3729          "Argument Location list must be sorted before lowering");
3730 
3731   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3732   // of tail call optimization arguments are handle later.
3733   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3734   for (unsigned I = 0, OutIndex = 0, E = ArgLocs.size(); I != E;
3735        ++I, ++OutIndex) {
3736     assert(OutIndex < Outs.size() && "Invalid Out index");
3737     // Skip inalloca arguments, they have already been written.
3738     ISD::ArgFlagsTy Flags = Outs[OutIndex].Flags;
3739     if (Flags.isInAlloca())
3740       continue;
3741 
3742     CCValAssign &VA = ArgLocs[I];
3743     EVT RegVT = VA.getLocVT();
3744     SDValue Arg = OutVals[OutIndex];
3745     bool isByVal = Flags.isByVal();
3746 
3747     // Promote the value if needed.
3748     switch (VA.getLocInfo()) {
3749     default: llvm_unreachable("Unknown loc info!");
3750     case CCValAssign::Full: break;
3751     case CCValAssign::SExt:
3752       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3753       break;
3754     case CCValAssign::ZExt:
3755       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3756       break;
3757     case CCValAssign::AExt:
3758       if (Arg.getValueType().isVector() &&
3759           Arg.getValueType().getVectorElementType() == MVT::i1)
3760         Arg = lowerMasksToReg(Arg, RegVT, dl, DAG);
3761       else if (RegVT.is128BitVector()) {
3762         // Special case: passing MMX values in XMM registers.
3763         Arg = DAG.getBitcast(MVT::i64, Arg);
3764         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3765         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3766       } else
3767         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3768       break;
3769     case CCValAssign::BCvt:
3770       Arg = DAG.getBitcast(RegVT, Arg);
3771       break;
3772     case CCValAssign::Indirect: {
3773       if (isByVal) {
3774         // Memcpy the argument to a temporary stack slot to prevent
3775         // the caller from seeing any modifications the callee may make
3776         // as guaranteed by the `byval` attribute.
3777         int FrameIdx = MF.getFrameInfo().CreateStackObject(
3778             Flags.getByValSize(), std::max(16, (int)Flags.getByValAlign()),
3779             false);
3780         SDValue StackSlot =
3781             DAG.getFrameIndex(FrameIdx, getPointerTy(DAG.getDataLayout()));
3782         Chain =
3783             CreateCopyOfByValArgument(Arg, StackSlot, Chain, Flags, DAG, dl);
3784         // From now on treat this as a regular pointer
3785         Arg = StackSlot;
3786         isByVal = false;
3787       } else {
3788         // Store the argument.
3789         SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3790         int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3791         Chain = DAG.getStore(
3792             Chain, dl, Arg, SpillSlot,
3793             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3794         Arg = SpillSlot;
3795       }
3796       break;
3797     }
3798     }
3799 
3800     if (VA.needsCustom()) {
3801       assert(VA.getValVT() == MVT::v64i1 &&
3802              "Currently the only custom case is when we split v64i1 to 2 regs");
3803       // Split v64i1 value into two registers
3804       Passv64i1ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++I],
3805                          Subtarget);
3806     } else if (VA.isRegLoc()) {
3807       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3808       if (isVarArg && IsWin64) {
3809         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3810         // shadow reg if callee is a varargs function.
3811         unsigned ShadowReg = 0;
3812         switch (VA.getLocReg()) {
3813         case X86::XMM0: ShadowReg = X86::RCX; break;
3814         case X86::XMM1: ShadowReg = X86::RDX; break;
3815         case X86::XMM2: ShadowReg = X86::R8; break;
3816         case X86::XMM3: ShadowReg = X86::R9; break;
3817         }
3818         if (ShadowReg)
3819           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3820       }
3821     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3822       assert(VA.isMemLoc());
3823       if (!StackPtr.getNode())
3824         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3825                                       getPointerTy(DAG.getDataLayout()));
3826       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3827                                              dl, DAG, VA, Flags));
3828     }
3829   }
3830 
3831   if (!MemOpChains.empty())
3832     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3833 
3834   if (Subtarget.isPICStyleGOT()) {
3835     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3836     // GOT pointer.
3837     if (!isTailCall) {
3838       RegsToPass.push_back(std::make_pair(
3839           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3840                                           getPointerTy(DAG.getDataLayout()))));
3841     } else {
3842       // If we are tail calling and generating PIC/GOT style code load the
3843       // address of the callee into ECX. The value in ecx is used as target of
3844       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3845       // for tail calls on PIC/GOT architectures. Normally we would just put the
3846       // address of GOT into ebx and then call target@PLT. But for tail calls
3847       // ebx would be restored (since ebx is callee saved) before jumping to the
3848       // target@PLT.
3849 
3850       // Note: The actual moving to ECX is done further down.
3851       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3852       if (G && !G->getGlobal()->hasLocalLinkage() &&
3853           G->getGlobal()->hasDefaultVisibility())
3854         Callee = LowerGlobalAddress(Callee, DAG);
3855       else if (isa<ExternalSymbolSDNode>(Callee))
3856         Callee = LowerExternalSymbol(Callee, DAG);
3857     }
3858   }
3859 
3860   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3861     // From AMD64 ABI document:
3862     // For calls that may call functions that use varargs or stdargs
3863     // (prototype-less calls or calls to functions containing ellipsis (...) in
3864     // the declaration) %al is used as hidden argument to specify the number
3865     // of SSE registers used. The contents of %al do not need to match exactly
3866     // the number of registers, but must be an ubound on the number of SSE
3867     // registers used and is in the range 0 - 8 inclusive.
3868 
3869     // Count the number of XMM registers allocated.
3870     static const MCPhysReg XMMArgRegs[] = {
3871       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3872       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3873     };
3874     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3875     assert((Subtarget.hasSSE1() || !NumXMMRegs)
3876            && "SSE registers cannot be used when SSE is disabled");
3877 
3878     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3879                                         DAG.getConstant(NumXMMRegs, dl,
3880                                                         MVT::i8)));
3881   }
3882 
3883   if (isVarArg && IsMustTail) {
3884     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3885     for (const auto &F : Forwards) {
3886       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3887       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3888     }
3889   }
3890 
3891   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3892   // don't need this because the eligibility check rejects calls that require
3893   // shuffling arguments passed in memory.
3894   if (!IsSibcall && isTailCall) {
3895     // Force all the incoming stack arguments to be loaded from the stack
3896     // before any new outgoing arguments are stored to the stack, because the
3897     // outgoing stack slots may alias the incoming argument stack slots, and
3898     // the alias isn't otherwise explicit. This is slightly more conservative
3899     // than necessary, because it means that each store effectively depends
3900     // on every argument instead of just those arguments it would clobber.
3901     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3902 
3903     SmallVector<SDValue, 8> MemOpChains2;
3904     SDValue FIN;
3905     int FI = 0;
3906     for (unsigned I = 0, OutsIndex = 0, E = ArgLocs.size(); I != E;
3907          ++I, ++OutsIndex) {
3908       CCValAssign &VA = ArgLocs[I];
3909 
3910       if (VA.isRegLoc()) {
3911         if (VA.needsCustom()) {
3912           assert((CallConv == CallingConv::X86_RegCall) &&
3913                  "Expecting custom case only in regcall calling convention");
3914           // This means that we are in special case where one argument was
3915           // passed through two register locations - Skip the next location
3916           ++I;
3917         }
3918 
3919         continue;
3920       }
3921 
3922       assert(VA.isMemLoc());
3923       SDValue Arg = OutVals[OutsIndex];
3924       ISD::ArgFlagsTy Flags = Outs[OutsIndex].Flags;
3925       // Skip inalloca arguments.  They don't require any work.
3926       if (Flags.isInAlloca())
3927         continue;
3928       // Create frame index.
3929       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3930       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3931       FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3932       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3933 
3934       if (Flags.isByVal()) {
3935         // Copy relative to framepointer.
3936         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3937         if (!StackPtr.getNode())
3938           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3939                                         getPointerTy(DAG.getDataLayout()));
3940         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3941                              StackPtr, Source);
3942 
3943         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3944                                                          ArgChain,
3945                                                          Flags, DAG, dl));
3946       } else {
3947         // Store relative to framepointer.
3948         MemOpChains2.push_back(DAG.getStore(
3949             ArgChain, dl, Arg, FIN,
3950             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
3951       }
3952     }
3953 
3954     if (!MemOpChains2.empty())
3955       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3956 
3957     // Store the return address to the appropriate stack slot.
3958     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3959                                      getPointerTy(DAG.getDataLayout()),
3960                                      RegInfo->getSlotSize(), FPDiff, dl);
3961   }
3962 
3963   // Build a sequence of copy-to-reg nodes chained together with token chain
3964   // and flag operands which copy the outgoing args into registers.
3965   SDValue InFlag;
3966   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3967     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3968                              RegsToPass[i].second, InFlag);
3969     InFlag = Chain.getValue(1);
3970   }
3971 
3972   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3973     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3974     // In the 64-bit large code model, we have to make all calls
3975     // through a register, since the call instruction's 32-bit
3976     // pc-relative offset may not be large enough to hold the whole
3977     // address.
3978   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3979     // If the callee is a GlobalAddress node (quite common, every direct call
3980     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3981     // it.
3982     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3983 
3984     // We should use extra load for direct calls to dllimported functions in
3985     // non-JIT mode.
3986     const GlobalValue *GV = G->getGlobal();
3987     if (!GV->hasDLLImportStorageClass()) {
3988       unsigned char OpFlags = Subtarget.classifyGlobalFunctionReference(GV);
3989 
3990       Callee = DAG.getTargetGlobalAddress(
3991           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3992 
3993       if (OpFlags == X86II::MO_GOTPCREL) {
3994         // Add a wrapper.
3995         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3996           getPointerTy(DAG.getDataLayout()), Callee);
3997         // Add extra indirection
3998         Callee = DAG.getLoad(
3999             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
4000             MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4001       }
4002     }
4003   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4004     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
4005     unsigned char OpFlags =
4006         Subtarget.classifyGlobalFunctionReference(nullptr, *Mod);
4007 
4008     Callee = DAG.getTargetExternalSymbol(
4009         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
4010 
4011     if (OpFlags == X86II::MO_GOTPCREL) {
4012       Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
4013           getPointerTy(DAG.getDataLayout()), Callee);
4014       Callee = DAG.getLoad(
4015           getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
4016           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4017     }
4018   } else if (Subtarget.isTarget64BitILP32() &&
4019              Callee->getValueType(0) == MVT::i32) {
4020     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
4021     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
4022   }
4023 
4024   // Returns a chain & a flag for retval copy to use.
4025   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4026   SmallVector<SDValue, 8> Ops;
4027 
4028   if (!IsSibcall && isTailCall) {
4029     Chain = DAG.getCALLSEQ_END(Chain,
4030                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
4031                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4032     InFlag = Chain.getValue(1);
4033   }
4034 
4035   Ops.push_back(Chain);
4036   Ops.push_back(Callee);
4037 
4038   if (isTailCall)
4039     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
4040 
4041   // Add argument registers to the end of the list so that they are known live
4042   // into the call.
4043   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4044     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4045                                   RegsToPass[i].second.getValueType()));
4046 
4047   // Add a register mask operand representing the call-preserved registers.
4048   // If HasNCSR is asserted (attribute NoCallerSavedRegisters exists) then we
4049   // set X86_INTR calling convention because it has the same CSR mask
4050   // (same preserved registers).
4051   const uint32_t *Mask = RegInfo->getCallPreservedMask(
4052       MF, HasNCSR ? (CallingConv::ID)CallingConv::X86_INTR : CallConv);
4053   assert(Mask && "Missing call preserved mask for calling convention");
4054 
4055   // If this is an invoke in a 32-bit function using a funclet-based
4056   // personality, assume the function clobbers all registers. If an exception
4057   // is thrown, the runtime will not restore CSRs.
4058   // FIXME: Model this more precisely so that we can register allocate across
4059   // the normal edge and spill and fill across the exceptional edge.
4060   if (!Is64Bit && CLI.CS && CLI.CS.isInvoke()) {
4061     const Function &CallerFn = MF.getFunction();
4062     EHPersonality Pers =
4063         CallerFn.hasPersonalityFn()
4064             ? classifyEHPersonality(CallerFn.getPersonalityFn())
4065             : EHPersonality::Unknown;
4066     if (isFuncletEHPersonality(Pers))
4067       Mask = RegInfo->getNoPreservedMask();
4068   }
4069 
4070   // Define a new register mask from the existing mask.
4071   uint32_t *RegMask = nullptr;
4072 
4073   // In some calling conventions we need to remove the used physical registers
4074   // from the reg mask.
4075   if (CallConv == CallingConv::X86_RegCall || HasNCSR) {
4076     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4077 
4078     // Allocate a new Reg Mask and copy Mask.
4079     RegMask = MF.allocateRegMask();
4080     unsigned RegMaskSize = MachineOperand::getRegMaskSize(TRI->getNumRegs());
4081     memcpy(RegMask, Mask, sizeof(RegMask[0]) * RegMaskSize);
4082 
4083     // Make sure all sub registers of the argument registers are reset
4084     // in the RegMask.
4085     for (auto const &RegPair : RegsToPass)
4086       for (MCSubRegIterator SubRegs(RegPair.first, TRI, /*IncludeSelf=*/true);
4087            SubRegs.isValid(); ++SubRegs)
4088         RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
4089 
4090     // Create the RegMask Operand according to our updated mask.
4091     Ops.push_back(DAG.getRegisterMask(RegMask));
4092   } else {
4093     // Create the RegMask Operand according to the static mask.
4094     Ops.push_back(DAG.getRegisterMask(Mask));
4095   }
4096 
4097   if (InFlag.getNode())
4098     Ops.push_back(InFlag);
4099 
4100   if (isTailCall) {
4101     // We used to do:
4102     //// If this is the first return lowered for this function, add the regs
4103     //// to the liveout set for the function.
4104     // This isn't right, although it's probably harmless on x86; liveouts
4105     // should be computed from returns not tail calls.  Consider a void
4106     // function making a tail call to a function returning int.
4107     MF.getFrameInfo().setHasTailCall();
4108     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
4109   }
4110 
4111   if (HasNoCfCheck && IsCFProtectionSupported) {
4112     Chain = DAG.getNode(X86ISD::NT_CALL, dl, NodeTys, Ops);
4113   } else {
4114     Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
4115   }
4116   InFlag = Chain.getValue(1);
4117 
4118   // Create the CALLSEQ_END node.
4119   unsigned NumBytesForCalleeToPop;
4120   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
4121                        DAG.getTarget().Options.GuaranteedTailCallOpt))
4122     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
4123   else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
4124            !Subtarget.getTargetTriple().isOSMSVCRT() &&
4125            SR == StackStructReturn)
4126     // If this is a call to a struct-return function, the callee
4127     // pops the hidden struct pointer, so we have to push it back.
4128     // This is common for Darwin/X86, Linux & Mingw32 targets.
4129     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
4130     NumBytesForCalleeToPop = 4;
4131   else
4132     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
4133 
4134   if (CLI.DoesNotReturn && !getTargetMachine().Options.TrapUnreachable) {
4135     // No need to reset the stack after the call if the call doesn't return. To
4136     // make the MI verify, we'll pretend the callee does it for us.
4137     NumBytesForCalleeToPop = NumBytes;
4138   }
4139 
4140   // Returns a flag for retval copy to use.
4141   if (!IsSibcall) {
4142     Chain = DAG.getCALLSEQ_END(Chain,
4143                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
4144                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
4145                                                      true),
4146                                InFlag, dl);
4147     InFlag = Chain.getValue(1);
4148   }
4149 
4150   // Handle result values, copying them out of physregs into vregs that we
4151   // return.
4152   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
4153                          InVals, RegMask);
4154 }
4155 
4156 //===----------------------------------------------------------------------===//
4157 //                Fast Calling Convention (tail call) implementation
4158 //===----------------------------------------------------------------------===//
4159 
4160 //  Like std call, callee cleans arguments, convention except that ECX is
4161 //  reserved for storing the tail called function address. Only 2 registers are
4162 //  free for argument passing (inreg). Tail call optimization is performed
4163 //  provided:
4164 //                * tailcallopt is enabled
4165 //                * caller/callee are fastcc
4166 //  On X86_64 architecture with GOT-style position independent code only local
4167 //  (within module) calls are supported at the moment.
4168 //  To keep the stack aligned according to platform abi the function
4169 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
4170 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
4171 //  If a tail called function callee has more arguments than the caller the
4172 //  caller needs to make sure that there is room to move the RETADDR to. This is
4173 //  achieved by reserving an area the size of the argument delta right after the
4174 //  original RETADDR, but before the saved framepointer or the spilled registers
4175 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
4176 //  stack layout:
4177 //    arg1
4178 //    arg2
4179 //    RETADDR
4180 //    [ new RETADDR
4181 //      move area ]
4182 //    (possible EBP)
4183 //    ESI
4184 //    EDI
4185 //    local1 ..
4186 
4187 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
4188 /// requirement.
4189 unsigned
GetAlignedArgumentStackSize(unsigned StackSize,SelectionDAG & DAG) const4190 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
4191                                                SelectionDAG& DAG) const {
4192   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4193   const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
4194   unsigned StackAlignment = TFI.getStackAlignment();
4195   uint64_t AlignMask = StackAlignment - 1;
4196   int64_t Offset = StackSize;
4197   unsigned SlotSize = RegInfo->getSlotSize();
4198   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
4199     // Number smaller than 12 so just add the difference.
4200     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
4201   } else {
4202     // Mask out lower bits, add stackalignment once plus the 12 bytes.
4203     Offset = ((~AlignMask) & Offset) + StackAlignment +
4204       (StackAlignment-SlotSize);
4205   }
4206   return Offset;
4207 }
4208 
4209 /// Return true if the given stack call argument is already available in the
4210 /// same position (relatively) of the caller's incoming argument stack.
4211 static
MatchingStackOffset(SDValue Arg,unsigned Offset,ISD::ArgFlagsTy Flags,MachineFrameInfo & MFI,const MachineRegisterInfo * MRI,const X86InstrInfo * TII,const CCValAssign & VA)4212 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
4213                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
4214                          const X86InstrInfo *TII, const CCValAssign &VA) {
4215   unsigned Bytes = Arg.getValueSizeInBits() / 8;
4216 
4217   for (;;) {
4218     // Look through nodes that don't alter the bits of the incoming value.
4219     unsigned Op = Arg.getOpcode();
4220     if (Op == ISD::ZERO_EXTEND || Op == ISD::ANY_EXTEND || Op == ISD::BITCAST) {
4221       Arg = Arg.getOperand(0);
4222       continue;
4223     }
4224     if (Op == ISD::TRUNCATE) {
4225       const SDValue &TruncInput = Arg.getOperand(0);
4226       if (TruncInput.getOpcode() == ISD::AssertZext &&
4227           cast<VTSDNode>(TruncInput.getOperand(1))->getVT() ==
4228               Arg.getValueType()) {
4229         Arg = TruncInput.getOperand(0);
4230         continue;
4231       }
4232     }
4233     break;
4234   }
4235 
4236   int FI = INT_MAX;
4237   if (Arg.getOpcode() == ISD::CopyFromReg) {
4238     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
4239     if (!TargetRegisterInfo::isVirtualRegister(VR))
4240       return false;
4241     MachineInstr *Def = MRI->getVRegDef(VR);
4242     if (!Def)
4243       return false;
4244     if (!Flags.isByVal()) {
4245       if (!TII->isLoadFromStackSlot(*Def, FI))
4246         return false;
4247     } else {
4248       unsigned Opcode = Def->getOpcode();
4249       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
4250            Opcode == X86::LEA64_32r) &&
4251           Def->getOperand(1).isFI()) {
4252         FI = Def->getOperand(1).getIndex();
4253         Bytes = Flags.getByValSize();
4254       } else
4255         return false;
4256     }
4257   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
4258     if (Flags.isByVal())
4259       // ByVal argument is passed in as a pointer but it's now being
4260       // dereferenced. e.g.
4261       // define @foo(%struct.X* %A) {
4262       //   tail call @bar(%struct.X* byval %A)
4263       // }
4264       return false;
4265     SDValue Ptr = Ld->getBasePtr();
4266     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
4267     if (!FINode)
4268       return false;
4269     FI = FINode->getIndex();
4270   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
4271     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
4272     FI = FINode->getIndex();
4273     Bytes = Flags.getByValSize();
4274   } else
4275     return false;
4276 
4277   assert(FI != INT_MAX);
4278   if (!MFI.isFixedObjectIndex(FI))
4279     return false;
4280 
4281   if (Offset != MFI.getObjectOffset(FI))
4282     return false;
4283 
4284   // If this is not byval, check that the argument stack object is immutable.
4285   // inalloca and argument copy elision can create mutable argument stack
4286   // objects. Byval objects can be mutated, but a byval call intends to pass the
4287   // mutated memory.
4288   if (!Flags.isByVal() && !MFI.isImmutableObjectIndex(FI))
4289     return false;
4290 
4291   if (VA.getLocVT().getSizeInBits() > Arg.getValueSizeInBits()) {
4292     // If the argument location is wider than the argument type, check that any
4293     // extension flags match.
4294     if (Flags.isZExt() != MFI.isObjectZExt(FI) ||
4295         Flags.isSExt() != MFI.isObjectSExt(FI)) {
4296       return false;
4297     }
4298   }
4299 
4300   return Bytes == MFI.getObjectSize(FI);
4301 }
4302 
4303 /// Check whether the call is eligible for tail call optimization. Targets
4304 /// that want to do tail call optimization should implement this function.
IsEligibleForTailCallOptimization(SDValue Callee,CallingConv::ID CalleeCC,bool isVarArg,bool isCalleeStructRet,bool isCallerStructRet,Type * RetTy,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SmallVectorImpl<ISD::InputArg> & Ins,SelectionDAG & DAG) const4305 bool X86TargetLowering::IsEligibleForTailCallOptimization(
4306     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
4307     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
4308     const SmallVectorImpl<ISD::OutputArg> &Outs,
4309     const SmallVectorImpl<SDValue> &OutVals,
4310     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4311   if (!mayTailCallThisCC(CalleeCC))
4312     return false;
4313 
4314   // If -tailcallopt is specified, make fastcc functions tail-callable.
4315   MachineFunction &MF = DAG.getMachineFunction();
4316   const Function &CallerF = MF.getFunction();
4317 
4318   // If the function return type is x86_fp80 and the callee return type is not,
4319   // then the FP_EXTEND of the call result is not a nop. It's not safe to
4320   // perform a tailcall optimization here.
4321   if (CallerF.getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
4322     return false;
4323 
4324   CallingConv::ID CallerCC = CallerF.getCallingConv();
4325   bool CCMatch = CallerCC == CalleeCC;
4326   bool IsCalleeWin64 = Subtarget.isCallingConvWin64(CalleeCC);
4327   bool IsCallerWin64 = Subtarget.isCallingConvWin64(CallerCC);
4328 
4329   // Win64 functions have extra shadow space for argument homing. Don't do the
4330   // sibcall if the caller and callee have mismatched expectations for this
4331   // space.
4332   if (IsCalleeWin64 != IsCallerWin64)
4333     return false;
4334 
4335   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
4336     if (canGuaranteeTCO(CalleeCC) && CCMatch)
4337       return true;
4338     return false;
4339   }
4340 
4341   // Look for obvious safe cases to perform tail call optimization that do not
4342   // require ABI changes. This is what gcc calls sibcall.
4343 
4344   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
4345   // emit a special epilogue.
4346   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4347   if (RegInfo->needsStackRealignment(MF))
4348     return false;
4349 
4350   // Also avoid sibcall optimization if either caller or callee uses struct
4351   // return semantics.
4352   if (isCalleeStructRet || isCallerStructRet)
4353     return false;
4354 
4355   // Do not sibcall optimize vararg calls unless all arguments are passed via
4356   // registers.
4357   LLVMContext &C = *DAG.getContext();
4358   if (isVarArg && !Outs.empty()) {
4359     // Optimizing for varargs on Win64 is unlikely to be safe without
4360     // additional testing.
4361     if (IsCalleeWin64 || IsCallerWin64)
4362       return false;
4363 
4364     SmallVector<CCValAssign, 16> ArgLocs;
4365     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4366 
4367     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
4368     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
4369       if (!ArgLocs[i].isRegLoc())
4370         return false;
4371   }
4372 
4373   // If the call result is in ST0 / ST1, it needs to be popped off the x87
4374   // stack.  Therefore, if it's not used by the call it is not safe to optimize
4375   // this into a sibcall.
4376   bool Unused = false;
4377   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4378     if (!Ins[i].Used) {
4379       Unused = true;
4380       break;
4381     }
4382   }
4383   if (Unused) {
4384     SmallVector<CCValAssign, 16> RVLocs;
4385     CCState CCInfo(CalleeCC, false, MF, RVLocs, C);
4386     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
4387     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4388       CCValAssign &VA = RVLocs[i];
4389       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
4390         return false;
4391     }
4392   }
4393 
4394   // Check that the call results are passed in the same way.
4395   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
4396                                   RetCC_X86, RetCC_X86))
4397     return false;
4398   // The callee has to preserve all registers the caller needs to preserve.
4399   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
4400   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
4401   if (!CCMatch) {
4402     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
4403     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
4404       return false;
4405   }
4406 
4407   unsigned StackArgsSize = 0;
4408 
4409   // If the callee takes no arguments then go on to check the results of the
4410   // call.
4411   if (!Outs.empty()) {
4412     // Check if stack adjustment is needed. For now, do not do this if any
4413     // argument is passed on the stack.
4414     SmallVector<CCValAssign, 16> ArgLocs;
4415     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4416 
4417     // Allocate shadow area for Win64
4418     if (IsCalleeWin64)
4419       CCInfo.AllocateStack(32, 8);
4420 
4421     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
4422     StackArgsSize = CCInfo.getNextStackOffset();
4423 
4424     if (CCInfo.getNextStackOffset()) {
4425       // Check if the arguments are already laid out in the right way as
4426       // the caller's fixed stack objects.
4427       MachineFrameInfo &MFI = MF.getFrameInfo();
4428       const MachineRegisterInfo *MRI = &MF.getRegInfo();
4429       const X86InstrInfo *TII = Subtarget.getInstrInfo();
4430       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4431         CCValAssign &VA = ArgLocs[i];
4432         SDValue Arg = OutVals[i];
4433         ISD::ArgFlagsTy Flags = Outs[i].Flags;
4434         if (VA.getLocInfo() == CCValAssign::Indirect)
4435           return false;
4436         if (!VA.isRegLoc()) {
4437           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
4438                                    MFI, MRI, TII, VA))
4439             return false;
4440         }
4441       }
4442     }
4443 
4444     bool PositionIndependent = isPositionIndependent();
4445     // If the tailcall address may be in a register, then make sure it's
4446     // possible to register allocate for it. In 32-bit, the call address can
4447     // only target EAX, EDX, or ECX since the tail call must be scheduled after
4448     // callee-saved registers are restored. These happen to be the same
4449     // registers used to pass 'inreg' arguments so watch out for those.
4450     if (!Subtarget.is64Bit() && ((!isa<GlobalAddressSDNode>(Callee) &&
4451                                   !isa<ExternalSymbolSDNode>(Callee)) ||
4452                                  PositionIndependent)) {
4453       unsigned NumInRegs = 0;
4454       // In PIC we need an extra register to formulate the address computation
4455       // for the callee.
4456       unsigned MaxInRegs = PositionIndependent ? 2 : 3;
4457 
4458       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4459         CCValAssign &VA = ArgLocs[i];
4460         if (!VA.isRegLoc())
4461           continue;
4462         unsigned Reg = VA.getLocReg();
4463         switch (Reg) {
4464         default: break;
4465         case X86::EAX: case X86::EDX: case X86::ECX:
4466           if (++NumInRegs == MaxInRegs)
4467             return false;
4468           break;
4469         }
4470       }
4471     }
4472 
4473     const MachineRegisterInfo &MRI = MF.getRegInfo();
4474     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
4475       return false;
4476   }
4477 
4478   bool CalleeWillPop =
4479       X86::isCalleePop(CalleeCC, Subtarget.is64Bit(), isVarArg,
4480                        MF.getTarget().Options.GuaranteedTailCallOpt);
4481 
4482   if (unsigned BytesToPop =
4483           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
4484     // If we have bytes to pop, the callee must pop them.
4485     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
4486     if (!CalleePopMatches)
4487       return false;
4488   } else if (CalleeWillPop && StackArgsSize > 0) {
4489     // If we don't have bytes to pop, make sure the callee doesn't pop any.
4490     return false;
4491   }
4492 
4493   return true;
4494 }
4495 
4496 FastISel *
createFastISel(FunctionLoweringInfo & funcInfo,const TargetLibraryInfo * libInfo) const4497 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
4498                                   const TargetLibraryInfo *libInfo) const {
4499   return X86::createFastISel(funcInfo, libInfo);
4500 }
4501 
4502 //===----------------------------------------------------------------------===//
4503 //                           Other Lowering Hooks
4504 //===----------------------------------------------------------------------===//
4505 
MayFoldLoad(SDValue Op)4506 static bool MayFoldLoad(SDValue Op) {
4507   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
4508 }
4509 
MayFoldIntoStore(SDValue Op)4510 static bool MayFoldIntoStore(SDValue Op) {
4511   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
4512 }
4513 
MayFoldIntoZeroExtend(SDValue Op)4514 static bool MayFoldIntoZeroExtend(SDValue Op) {
4515   if (Op.hasOneUse()) {
4516     unsigned Opcode = Op.getNode()->use_begin()->getOpcode();
4517     return (ISD::ZERO_EXTEND == Opcode);
4518   }
4519   return false;
4520 }
4521 
isTargetShuffle(unsigned Opcode)4522 static bool isTargetShuffle(unsigned Opcode) {
4523   switch(Opcode) {
4524   default: return false;
4525   case X86ISD::BLENDI:
4526   case X86ISD::PSHUFB:
4527   case X86ISD::PSHUFD:
4528   case X86ISD::PSHUFHW:
4529   case X86ISD::PSHUFLW:
4530   case X86ISD::SHUFP:
4531   case X86ISD::INSERTPS:
4532   case X86ISD::EXTRQI:
4533   case X86ISD::INSERTQI:
4534   case X86ISD::PALIGNR:
4535   case X86ISD::VSHLDQ:
4536   case X86ISD::VSRLDQ:
4537   case X86ISD::MOVLHPS:
4538   case X86ISD::MOVHLPS:
4539   case X86ISD::MOVSHDUP:
4540   case X86ISD::MOVSLDUP:
4541   case X86ISD::MOVDDUP:
4542   case X86ISD::MOVSS:
4543   case X86ISD::MOVSD:
4544   case X86ISD::UNPCKL:
4545   case X86ISD::UNPCKH:
4546   case X86ISD::VBROADCAST:
4547   case X86ISD::VPERMILPI:
4548   case X86ISD::VPERMILPV:
4549   case X86ISD::VPERM2X128:
4550   case X86ISD::SHUF128:
4551   case X86ISD::VPERMIL2:
4552   case X86ISD::VPERMI:
4553   case X86ISD::VPPERM:
4554   case X86ISD::VPERMV:
4555   case X86ISD::VPERMV3:
4556   case X86ISD::VZEXT_MOVL:
4557     return true;
4558   }
4559 }
4560 
isTargetShuffleVariableMask(unsigned Opcode)4561 static bool isTargetShuffleVariableMask(unsigned Opcode) {
4562   switch (Opcode) {
4563   default: return false;
4564   // Target Shuffles.
4565   case X86ISD::PSHUFB:
4566   case X86ISD::VPERMILPV:
4567   case X86ISD::VPERMIL2:
4568   case X86ISD::VPPERM:
4569   case X86ISD::VPERMV:
4570   case X86ISD::VPERMV3:
4571     return true;
4572   // 'Faux' Target Shuffles.
4573   case ISD::OR:
4574   case ISD::AND:
4575   case X86ISD::ANDNP:
4576     return true;
4577   }
4578 }
4579 
getReturnAddressFrameIndex(SelectionDAG & DAG) const4580 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
4581   MachineFunction &MF = DAG.getMachineFunction();
4582   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4583   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
4584   int ReturnAddrIndex = FuncInfo->getRAIndex();
4585 
4586   if (ReturnAddrIndex == 0) {
4587     // Set up a frame object for the return address.
4588     unsigned SlotSize = RegInfo->getSlotSize();
4589     ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize,
4590                                                           -(int64_t)SlotSize,
4591                                                           false);
4592     FuncInfo->setRAIndex(ReturnAddrIndex);
4593   }
4594 
4595   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
4596 }
4597 
isOffsetSuitableForCodeModel(int64_t Offset,CodeModel::Model M,bool hasSymbolicDisplacement)4598 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
4599                                        bool hasSymbolicDisplacement) {
4600   // Offset should fit into 32 bit immediate field.
4601   if (!isInt<32>(Offset))
4602     return false;
4603 
4604   // If we don't have a symbolic displacement - we don't have any extra
4605   // restrictions.
4606   if (!hasSymbolicDisplacement)
4607     return true;
4608 
4609   // FIXME: Some tweaks might be needed for medium code model.
4610   if (M != CodeModel::Small && M != CodeModel::Kernel)
4611     return false;
4612 
4613   // For small code model we assume that latest object is 16MB before end of 31
4614   // bits boundary. We may also accept pretty large negative constants knowing
4615   // that all objects are in the positive half of address space.
4616   if (M == CodeModel::Small && Offset < 16*1024*1024)
4617     return true;
4618 
4619   // For kernel code model we know that all object resist in the negative half
4620   // of 32bits address space. We may not accept negative offsets, since they may
4621   // be just off and we may accept pretty large positive ones.
4622   if (M == CodeModel::Kernel && Offset >= 0)
4623     return true;
4624 
4625   return false;
4626 }
4627 
4628 /// Determines whether the callee is required to pop its own arguments.
4629 /// Callee pop is necessary to support tail calls.
isCalleePop(CallingConv::ID CallingConv,bool is64Bit,bool IsVarArg,bool GuaranteeTCO)4630 bool X86::isCalleePop(CallingConv::ID CallingConv,
4631                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4632   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4633   // can guarantee TCO.
4634   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4635     return true;
4636 
4637   switch (CallingConv) {
4638   default:
4639     return false;
4640   case CallingConv::X86_StdCall:
4641   case CallingConv::X86_FastCall:
4642   case CallingConv::X86_ThisCall:
4643   case CallingConv::X86_VectorCall:
4644     return !is64Bit;
4645   }
4646 }
4647 
4648 /// Return true if the condition is an unsigned comparison operation.
isX86CCUnsigned(unsigned X86CC)4649 static bool isX86CCUnsigned(unsigned X86CC) {
4650   switch (X86CC) {
4651   default:
4652     llvm_unreachable("Invalid integer condition!");
4653   case X86::COND_E:
4654   case X86::COND_NE:
4655   case X86::COND_B:
4656   case X86::COND_A:
4657   case X86::COND_BE:
4658   case X86::COND_AE:
4659     return true;
4660   case X86::COND_G:
4661   case X86::COND_GE:
4662   case X86::COND_L:
4663   case X86::COND_LE:
4664     return false;
4665   }
4666 }
4667 
TranslateIntegerX86CC(ISD::CondCode SetCCOpcode)4668 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4669   switch (SetCCOpcode) {
4670   default: llvm_unreachable("Invalid integer condition!");
4671   case ISD::SETEQ:  return X86::COND_E;
4672   case ISD::SETGT:  return X86::COND_G;
4673   case ISD::SETGE:  return X86::COND_GE;
4674   case ISD::SETLT:  return X86::COND_L;
4675   case ISD::SETLE:  return X86::COND_LE;
4676   case ISD::SETNE:  return X86::COND_NE;
4677   case ISD::SETULT: return X86::COND_B;
4678   case ISD::SETUGT: return X86::COND_A;
4679   case ISD::SETULE: return X86::COND_BE;
4680   case ISD::SETUGE: return X86::COND_AE;
4681   }
4682 }
4683 
4684 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4685 /// condition code, returning the condition code and the LHS/RHS of the
4686 /// comparison to make.
TranslateX86CC(ISD::CondCode SetCCOpcode,const SDLoc & DL,bool isFP,SDValue & LHS,SDValue & RHS,SelectionDAG & DAG)4687 static X86::CondCode TranslateX86CC(ISD::CondCode SetCCOpcode, const SDLoc &DL,
4688                                bool isFP, SDValue &LHS, SDValue &RHS,
4689                                SelectionDAG &DAG) {
4690   if (!isFP) {
4691     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4692       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4693         // X > -1   -> X == 0, jump !sign.
4694         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4695         return X86::COND_NS;
4696       }
4697       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4698         // X < 0   -> X == 0, jump on sign.
4699         return X86::COND_S;
4700       }
4701       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4702         // X < 1   -> X <= 0
4703         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4704         return X86::COND_LE;
4705       }
4706     }
4707 
4708     return TranslateIntegerX86CC(SetCCOpcode);
4709   }
4710 
4711   // First determine if it is required or is profitable to flip the operands.
4712 
4713   // If LHS is a foldable load, but RHS is not, flip the condition.
4714   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4715       !ISD::isNON_EXTLoad(RHS.getNode())) {
4716     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4717     std::swap(LHS, RHS);
4718   }
4719 
4720   switch (SetCCOpcode) {
4721   default: break;
4722   case ISD::SETOLT:
4723   case ISD::SETOLE:
4724   case ISD::SETUGT:
4725   case ISD::SETUGE:
4726     std::swap(LHS, RHS);
4727     break;
4728   }
4729 
4730   // On a floating point condition, the flags are set as follows:
4731   // ZF  PF  CF   op
4732   //  0 | 0 | 0 | X > Y
4733   //  0 | 0 | 1 | X < Y
4734   //  1 | 0 | 0 | X == Y
4735   //  1 | 1 | 1 | unordered
4736   switch (SetCCOpcode) {
4737   default: llvm_unreachable("Condcode should be pre-legalized away");
4738   case ISD::SETUEQ:
4739   case ISD::SETEQ:   return X86::COND_E;
4740   case ISD::SETOLT:              // flipped
4741   case ISD::SETOGT:
4742   case ISD::SETGT:   return X86::COND_A;
4743   case ISD::SETOLE:              // flipped
4744   case ISD::SETOGE:
4745   case ISD::SETGE:   return X86::COND_AE;
4746   case ISD::SETUGT:              // flipped
4747   case ISD::SETULT:
4748   case ISD::SETLT:   return X86::COND_B;
4749   case ISD::SETUGE:              // flipped
4750   case ISD::SETULE:
4751   case ISD::SETLE:   return X86::COND_BE;
4752   case ISD::SETONE:
4753   case ISD::SETNE:   return X86::COND_NE;
4754   case ISD::SETUO:   return X86::COND_P;
4755   case ISD::SETO:    return X86::COND_NP;
4756   case ISD::SETOEQ:
4757   case ISD::SETUNE:  return X86::COND_INVALID;
4758   }
4759 }
4760 
4761 /// Is there a floating point cmov for the specific X86 condition code?
4762 /// Current x86 isa includes the following FP cmov instructions:
4763 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
hasFPCMov(unsigned X86CC)4764 static bool hasFPCMov(unsigned X86CC) {
4765   switch (X86CC) {
4766   default:
4767     return false;
4768   case X86::COND_B:
4769   case X86::COND_BE:
4770   case X86::COND_E:
4771   case X86::COND_P:
4772   case X86::COND_A:
4773   case X86::COND_AE:
4774   case X86::COND_NE:
4775   case X86::COND_NP:
4776     return true;
4777   }
4778 }
4779 
4780 
getTgtMemIntrinsic(IntrinsicInfo & Info,const CallInst & I,MachineFunction & MF,unsigned Intrinsic) const4781 bool X86TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
4782                                            const CallInst &I,
4783                                            MachineFunction &MF,
4784                                            unsigned Intrinsic) const {
4785 
4786   const IntrinsicData* IntrData = getIntrinsicWithChain(Intrinsic);
4787   if (!IntrData)
4788     return false;
4789 
4790   Info.opc = ISD::INTRINSIC_W_CHAIN;
4791   Info.flags = MachineMemOperand::MONone;
4792   Info.offset = 0;
4793 
4794   switch (IntrData->Type) {
4795   case TRUNCATE_TO_MEM_VI8:
4796   case TRUNCATE_TO_MEM_VI16:
4797   case TRUNCATE_TO_MEM_VI32: {
4798     Info.ptrVal = I.getArgOperand(0);
4799     MVT VT  = MVT::getVT(I.getArgOperand(1)->getType());
4800     MVT ScalarVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
4801     if (IntrData->Type == TRUNCATE_TO_MEM_VI8)
4802       ScalarVT = MVT::i8;
4803     else if (IntrData->Type == TRUNCATE_TO_MEM_VI16)
4804       ScalarVT = MVT::i16;
4805     else if (IntrData->Type == TRUNCATE_TO_MEM_VI32)
4806       ScalarVT = MVT::i32;
4807 
4808     Info.memVT = MVT::getVectorVT(ScalarVT, VT.getVectorNumElements());
4809     Info.align = 1;
4810     Info.flags |= MachineMemOperand::MOStore;
4811     break;
4812   }
4813   default:
4814     return false;
4815   }
4816 
4817   return true;
4818 }
4819 
4820 /// Returns true if the target can instruction select the
4821 /// specified FP immediate natively. If false, the legalizer will
4822 /// materialize the FP immediate as a load from a constant pool.
isFPImmLegal(const APFloat & Imm,EVT VT) const4823 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4824   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4825     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4826       return true;
4827   }
4828   return false;
4829 }
4830 
shouldReduceLoadWidth(SDNode * Load,ISD::LoadExtType ExtTy,EVT NewVT) const4831 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4832                                               ISD::LoadExtType ExtTy,
4833                                               EVT NewVT) const {
4834   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4835   // relocation target a movq or addq instruction: don't let the load shrink.
4836   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4837   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4838     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4839       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4840   return true;
4841 }
4842 
4843 /// Returns true if it is beneficial to convert a load of a constant
4844 /// to just the constant itself.
shouldConvertConstantLoadToIntImm(const APInt & Imm,Type * Ty) const4845 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4846                                                           Type *Ty) const {
4847   assert(Ty->isIntegerTy());
4848 
4849   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4850   if (BitSize == 0 || BitSize > 64)
4851     return false;
4852   return true;
4853 }
4854 
reduceSelectOfFPConstantLoads(bool IsFPSetCC) const4855 bool X86TargetLowering::reduceSelectOfFPConstantLoads(bool IsFPSetCC) const {
4856   // If we are using XMM registers in the ABI and the condition of the select is
4857   // a floating-point compare and we have blendv or conditional move, then it is
4858   // cheaper to select instead of doing a cross-register move and creating a
4859   // load that depends on the compare result.
4860   return !IsFPSetCC || !Subtarget.isTarget64BitLP64() || !Subtarget.hasAVX();
4861 }
4862 
convertSelectOfConstantsToMath(EVT VT) const4863 bool X86TargetLowering::convertSelectOfConstantsToMath(EVT VT) const {
4864   // TODO: It might be a win to ease or lift this restriction, but the generic
4865   // folds in DAGCombiner conflict with vector folds for an AVX512 target.
4866   if (VT.isVector() && Subtarget.hasAVX512())
4867     return false;
4868 
4869   return true;
4870 }
4871 
decomposeMulByConstant(EVT VT,SDValue C) const4872 bool X86TargetLowering::decomposeMulByConstant(EVT VT, SDValue C) const {
4873   // TODO: We handle scalars using custom code, but generic combining could make
4874   // that unnecessary.
4875   APInt MulC;
4876   if (!ISD::isConstantSplatVector(C.getNode(), MulC))
4877     return false;
4878 
4879   // If vector multiply is legal, assume that's faster than shl + add/sub.
4880   // TODO: Multiply is a complex op with higher latency and lower througput in
4881   //       most implementations, so this check could be loosened based on type
4882   //       and/or a CPU attribute.
4883   if (isOperationLegal(ISD::MUL, VT))
4884     return false;
4885 
4886   // shl+add, shl+sub, shl+add+neg
4887   return (MulC + 1).isPowerOf2() || (MulC - 1).isPowerOf2() ||
4888          (1 - MulC).isPowerOf2() || (-(MulC + 1)).isPowerOf2();
4889 }
4890 
shouldUseStrictFP_TO_INT(EVT FpVT,EVT IntVT,bool IsSigned) const4891 bool X86TargetLowering::shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT,
4892                                                  bool IsSigned) const {
4893   // f80 UINT_TO_FP is more efficient using Strict code if FCMOV is available.
4894   return !IsSigned && FpVT == MVT::f80 && Subtarget.hasCMov();
4895 }
4896 
isExtractSubvectorCheap(EVT ResVT,EVT SrcVT,unsigned Index) const4897 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
4898                                                 unsigned Index) const {
4899   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4900     return false;
4901 
4902   // Mask vectors support all subregister combinations and operations that
4903   // extract half of vector.
4904   if (ResVT.getVectorElementType() == MVT::i1)
4905     return Index == 0 || ((ResVT.getSizeInBits() == SrcVT.getSizeInBits()*2) &&
4906                           (Index == ResVT.getVectorNumElements()));
4907 
4908   return (Index % ResVT.getVectorNumElements()) == 0;
4909 }
4910 
shouldScalarizeBinop(SDValue VecOp) const4911 bool X86TargetLowering::shouldScalarizeBinop(SDValue VecOp) const {
4912   // If the vector op is not supported, try to convert to scalar.
4913   EVT VecVT = VecOp.getValueType();
4914   if (!isOperationLegalOrCustomOrPromote(VecOp.getOpcode(), VecVT))
4915     return true;
4916 
4917   // If the vector op is supported, but the scalar op is not, the transform may
4918   // not be worthwhile.
4919   EVT ScalarVT = VecVT.getScalarType();
4920   return isOperationLegalOrCustomOrPromote(VecOp.getOpcode(), ScalarVT);
4921 }
4922 
isCheapToSpeculateCttz() const4923 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4924   // Speculate cttz only if we can directly use TZCNT.
4925   return Subtarget.hasBMI();
4926 }
4927 
isCheapToSpeculateCtlz() const4928 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4929   // Speculate ctlz only if we can directly use LZCNT.
4930   return Subtarget.hasLZCNT();
4931 }
4932 
isLoadBitCastBeneficial(EVT LoadVT,EVT BitcastVT) const4933 bool X86TargetLowering::isLoadBitCastBeneficial(EVT LoadVT,
4934                                                 EVT BitcastVT) const {
4935   if (!Subtarget.hasAVX512() && !LoadVT.isVector() && BitcastVT.isVector() &&
4936       BitcastVT.getVectorElementType() == MVT::i1)
4937     return false;
4938 
4939   if (!Subtarget.hasDQI() && BitcastVT == MVT::v8i1 && LoadVT == MVT::i8)
4940     return false;
4941 
4942   return TargetLowering::isLoadBitCastBeneficial(LoadVT, BitcastVT);
4943 }
4944 
canMergeStoresTo(unsigned AddressSpace,EVT MemVT,const SelectionDAG & DAG) const4945 bool X86TargetLowering::canMergeStoresTo(unsigned AddressSpace, EVT MemVT,
4946                                          const SelectionDAG &DAG) const {
4947   // Do not merge to float value size (128 bytes) if no implicit
4948   // float attribute is set.
4949   bool NoFloat = DAG.getMachineFunction().getFunction().hasFnAttribute(
4950       Attribute::NoImplicitFloat);
4951 
4952   if (NoFloat) {
4953     unsigned MaxIntSize = Subtarget.is64Bit() ? 64 : 32;
4954     return (MemVT.getSizeInBits() <= MaxIntSize);
4955   }
4956   return true;
4957 }
4958 
isCtlzFast() const4959 bool X86TargetLowering::isCtlzFast() const {
4960   return Subtarget.hasFastLZCNT();
4961 }
4962 
isMaskAndCmp0FoldingBeneficial(const Instruction & AndI) const4963 bool X86TargetLowering::isMaskAndCmp0FoldingBeneficial(
4964     const Instruction &AndI) const {
4965   return true;
4966 }
4967 
hasAndNotCompare(SDValue Y) const4968 bool X86TargetLowering::hasAndNotCompare(SDValue Y) const {
4969   EVT VT = Y.getValueType();
4970 
4971   if (VT.isVector())
4972     return false;
4973 
4974   if (!Subtarget.hasBMI())
4975     return false;
4976 
4977   // There are only 32-bit and 64-bit forms for 'andn'.
4978   if (VT != MVT::i32 && VT != MVT::i64)
4979     return false;
4980 
4981   return !isa<ConstantSDNode>(Y);
4982 }
4983 
hasAndNot(SDValue Y) const4984 bool X86TargetLowering::hasAndNot(SDValue Y) const {
4985   EVT VT = Y.getValueType();
4986 
4987   if (!VT.isVector())
4988     return hasAndNotCompare(Y);
4989 
4990   // Vector.
4991 
4992   if (!Subtarget.hasSSE1() || VT.getSizeInBits() < 128)
4993     return false;
4994 
4995   if (VT == MVT::v4i32)
4996     return true;
4997 
4998   return Subtarget.hasSSE2();
4999 }
5000 
preferShiftsToClearExtremeBits(SDValue Y) const5001 bool X86TargetLowering::preferShiftsToClearExtremeBits(SDValue Y) const {
5002   EVT VT = Y.getValueType();
5003 
5004   // For vectors, we don't have a preference, but we probably want a mask.
5005   if (VT.isVector())
5006     return false;
5007 
5008   // 64-bit shifts on 32-bit targets produce really bad bloated code.
5009   if (VT == MVT::i64 && !Subtarget.is64Bit())
5010     return false;
5011 
5012   return true;
5013 }
5014 
shouldSplatInsEltVarIndex(EVT VT) const5015 bool X86TargetLowering::shouldSplatInsEltVarIndex(EVT VT) const {
5016   // Any legal vector type can be splatted more efficiently than
5017   // loading/spilling from memory.
5018   return isTypeLegal(VT);
5019 }
5020 
hasFastEqualityCompare(unsigned NumBits) const5021 MVT X86TargetLowering::hasFastEqualityCompare(unsigned NumBits) const {
5022   MVT VT = MVT::getIntegerVT(NumBits);
5023   if (isTypeLegal(VT))
5024     return VT;
5025 
5026   // PMOVMSKB can handle this.
5027   if (NumBits == 128 && isTypeLegal(MVT::v16i8))
5028     return MVT::v16i8;
5029 
5030   // VPMOVMSKB can handle this.
5031   if (NumBits == 256 && isTypeLegal(MVT::v32i8))
5032     return MVT::v32i8;
5033 
5034   // TODO: Allow 64-bit type for 32-bit target.
5035   // TODO: 512-bit types should be allowed, but make sure that those
5036   // cases are handled in combineVectorSizedSetCCEquality().
5037 
5038   return MVT::INVALID_SIMPLE_VALUE_TYPE;
5039 }
5040 
5041 /// Val is the undef sentinel value or equal to the specified value.
isUndefOrEqual(int Val,int CmpVal)5042 static bool isUndefOrEqual(int Val, int CmpVal) {
5043   return ((Val == SM_SentinelUndef) || (Val == CmpVal));
5044 }
5045 
5046 /// Val is either the undef or zero sentinel value.
isUndefOrZero(int Val)5047 static bool isUndefOrZero(int Val) {
5048   return ((Val == SM_SentinelUndef) || (Val == SM_SentinelZero));
5049 }
5050 
5051 /// Return true if every element in Mask, beginning
5052 /// from position Pos and ending in Pos+Size is the undef sentinel value.
isUndefInRange(ArrayRef<int> Mask,unsigned Pos,unsigned Size)5053 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
5054   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
5055     if (Mask[i] != SM_SentinelUndef)
5056       return false;
5057   return true;
5058 }
5059 
5060 /// Return true if Val falls within the specified range (L, H].
isInRange(int Val,int Low,int Hi)5061 static bool isInRange(int Val, int Low, int Hi) {
5062   return (Val >= Low && Val < Hi);
5063 }
5064 
5065 /// Return true if the value of any element in Mask falls within the specified
5066 /// range (L, H].
isAnyInRange(ArrayRef<int> Mask,int Low,int Hi)5067 static bool isAnyInRange(ArrayRef<int> Mask, int Low, int Hi) {
5068   for (int M : Mask)
5069     if (isInRange(M, Low, Hi))
5070       return true;
5071   return false;
5072 }
5073 
5074 /// Return true if Val is undef or if its value falls within the
5075 /// specified range (L, H].
isUndefOrInRange(int Val,int Low,int Hi)5076 static bool isUndefOrInRange(int Val, int Low, int Hi) {
5077   return (Val == SM_SentinelUndef) || isInRange(Val, Low, Hi);
5078 }
5079 
5080 /// Return true if every element in Mask is undef or if its value
5081 /// falls within the specified range (L, H].
isUndefOrInRange(ArrayRef<int> Mask,int Low,int Hi)5082 static bool isUndefOrInRange(ArrayRef<int> Mask,
5083                              int Low, int Hi) {
5084   for (int M : Mask)
5085     if (!isUndefOrInRange(M, Low, Hi))
5086       return false;
5087   return true;
5088 }
5089 
5090 /// Return true if Val is undef, zero or if its value falls within the
5091 /// specified range (L, H].
isUndefOrZeroOrInRange(int Val,int Low,int Hi)5092 static bool isUndefOrZeroOrInRange(int Val, int Low, int Hi) {
5093   return isUndefOrZero(Val) || isInRange(Val, Low, Hi);
5094 }
5095 
5096 /// Return true if every element in Mask is undef, zero or if its value
5097 /// falls within the specified range (L, H].
isUndefOrZeroOrInRange(ArrayRef<int> Mask,int Low,int Hi)5098 static bool isUndefOrZeroOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
5099   for (int M : Mask)
5100     if (!isUndefOrZeroOrInRange(M, Low, Hi))
5101       return false;
5102   return true;
5103 }
5104 
5105 /// Return true if every element in Mask, beginning
5106 /// from position Pos and ending in Pos + Size, falls within the specified
5107 /// sequence (Low, Low + Step, ..., Low + (Size - 1) * Step) or is undef.
isSequentialOrUndefInRange(ArrayRef<int> Mask,unsigned Pos,unsigned Size,int Low,int Step=1)5108 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, unsigned Pos,
5109                                        unsigned Size, int Low, int Step = 1) {
5110   for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
5111     if (!isUndefOrEqual(Mask[i], Low))
5112       return false;
5113   return true;
5114 }
5115 
5116 /// Return true if every element in Mask, beginning
5117 /// from position Pos and ending in Pos+Size, falls within the specified
5118 /// sequential range (Low, Low+Size], or is undef or is zero.
isSequentialOrUndefOrZeroInRange(ArrayRef<int> Mask,unsigned Pos,unsigned Size,int Low)5119 static bool isSequentialOrUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
5120                                              unsigned Size, int Low) {
5121   for (unsigned i = Pos, e = Pos + Size; i != e; ++i, ++Low)
5122     if (!isUndefOrZero(Mask[i]) && Mask[i] != Low)
5123       return false;
5124   return true;
5125 }
5126 
5127 /// Return true if every element in Mask, beginning
5128 /// from position Pos and ending in Pos+Size is undef or is zero.
isUndefOrZeroInRange(ArrayRef<int> Mask,unsigned Pos,unsigned Size)5129 static bool isUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
5130                                  unsigned Size) {
5131   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
5132     if (!isUndefOrZero(Mask[i]))
5133       return false;
5134   return true;
5135 }
5136 
5137 /// Helper function to test whether a shuffle mask could be
5138 /// simplified by widening the elements being shuffled.
5139 ///
5140 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
5141 /// leaves it in an unspecified state.
5142 ///
5143 /// NOTE: This must handle normal vector shuffle masks and *target* vector
5144 /// shuffle masks. The latter have the special property of a '-2' representing
5145 /// a zero-ed lane of a vector.
canWidenShuffleElements(ArrayRef<int> Mask,SmallVectorImpl<int> & WidenedMask)5146 static bool canWidenShuffleElements(ArrayRef<int> Mask,
5147                                     SmallVectorImpl<int> &WidenedMask) {
5148   WidenedMask.assign(Mask.size() / 2, 0);
5149   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
5150     int M0 = Mask[i];
5151     int M1 = Mask[i + 1];
5152 
5153     // If both elements are undef, its trivial.
5154     if (M0 == SM_SentinelUndef && M1 == SM_SentinelUndef) {
5155       WidenedMask[i / 2] = SM_SentinelUndef;
5156       continue;
5157     }
5158 
5159     // Check for an undef mask and a mask value properly aligned to fit with
5160     // a pair of values. If we find such a case, use the non-undef mask's value.
5161     if (M0 == SM_SentinelUndef && M1 >= 0 && (M1 % 2) == 1) {
5162       WidenedMask[i / 2] = M1 / 2;
5163       continue;
5164     }
5165     if (M1 == SM_SentinelUndef && M0 >= 0 && (M0 % 2) == 0) {
5166       WidenedMask[i / 2] = M0 / 2;
5167       continue;
5168     }
5169 
5170     // When zeroing, we need to spread the zeroing across both lanes to widen.
5171     if (M0 == SM_SentinelZero || M1 == SM_SentinelZero) {
5172       if ((M0 == SM_SentinelZero || M0 == SM_SentinelUndef) &&
5173           (M1 == SM_SentinelZero || M1 == SM_SentinelUndef)) {
5174         WidenedMask[i / 2] = SM_SentinelZero;
5175         continue;
5176       }
5177       return false;
5178     }
5179 
5180     // Finally check if the two mask values are adjacent and aligned with
5181     // a pair.
5182     if (M0 != SM_SentinelUndef && (M0 % 2) == 0 && (M0 + 1) == M1) {
5183       WidenedMask[i / 2] = M0 / 2;
5184       continue;
5185     }
5186 
5187     // Otherwise we can't safely widen the elements used in this shuffle.
5188     return false;
5189   }
5190   assert(WidenedMask.size() == Mask.size() / 2 &&
5191          "Incorrect size of mask after widening the elements!");
5192 
5193   return true;
5194 }
5195 
canWidenShuffleElements(ArrayRef<int> Mask,const APInt & Zeroable,SmallVectorImpl<int> & WidenedMask)5196 static bool canWidenShuffleElements(ArrayRef<int> Mask,
5197                                     const APInt &Zeroable,
5198                                     SmallVectorImpl<int> &WidenedMask) {
5199   SmallVector<int, 32> TargetMask(Mask.begin(), Mask.end());
5200   for (int i = 0, Size = TargetMask.size(); i < Size; ++i) {
5201     if (TargetMask[i] == SM_SentinelUndef)
5202       continue;
5203     if (Zeroable[i])
5204       TargetMask[i] = SM_SentinelZero;
5205   }
5206   return canWidenShuffleElements(TargetMask, WidenedMask);
5207 }
5208 
canWidenShuffleElements(ArrayRef<int> Mask)5209 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
5210   SmallVector<int, 32> WidenedMask;
5211   return canWidenShuffleElements(Mask, WidenedMask);
5212 }
5213 
5214 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
isZeroNode(SDValue Elt)5215 bool X86::isZeroNode(SDValue Elt) {
5216   return isNullConstant(Elt) || isNullFPConstant(Elt);
5217 }
5218 
5219 // Build a vector of constants.
5220 // Use an UNDEF node if MaskElt == -1.
5221 // Split 64-bit constants in the 32-bit mode.
getConstVector(ArrayRef<int> Values,MVT VT,SelectionDAG & DAG,const SDLoc & dl,bool IsMask=false)5222 static SDValue getConstVector(ArrayRef<int> Values, MVT VT, SelectionDAG &DAG,
5223                               const SDLoc &dl, bool IsMask = false) {
5224 
5225   SmallVector<SDValue, 32>  Ops;
5226   bool Split = false;
5227 
5228   MVT ConstVecVT = VT;
5229   unsigned NumElts = VT.getVectorNumElements();
5230   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
5231   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
5232     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
5233     Split = true;
5234   }
5235 
5236   MVT EltVT = ConstVecVT.getVectorElementType();
5237   for (unsigned i = 0; i < NumElts; ++i) {
5238     bool IsUndef = Values[i] < 0 && IsMask;
5239     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
5240       DAG.getConstant(Values[i], dl, EltVT);
5241     Ops.push_back(OpNode);
5242     if (Split)
5243       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
5244                     DAG.getConstant(0, dl, EltVT));
5245   }
5246   SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
5247   if (Split)
5248     ConstsNode = DAG.getBitcast(VT, ConstsNode);
5249   return ConstsNode;
5250 }
5251 
getConstVector(ArrayRef<APInt> Bits,APInt & Undefs,MVT VT,SelectionDAG & DAG,const SDLoc & dl)5252 static SDValue getConstVector(ArrayRef<APInt> Bits, APInt &Undefs,
5253                               MVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5254   assert(Bits.size() == Undefs.getBitWidth() &&
5255          "Unequal constant and undef arrays");
5256   SmallVector<SDValue, 32> Ops;
5257   bool Split = false;
5258 
5259   MVT ConstVecVT = VT;
5260   unsigned NumElts = VT.getVectorNumElements();
5261   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
5262   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
5263     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
5264     Split = true;
5265   }
5266 
5267   MVT EltVT = ConstVecVT.getVectorElementType();
5268   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
5269     if (Undefs[i]) {
5270       Ops.append(Split ? 2 : 1, DAG.getUNDEF(EltVT));
5271       continue;
5272     }
5273     const APInt &V = Bits[i];
5274     assert(V.getBitWidth() == VT.getScalarSizeInBits() && "Unexpected sizes");
5275     if (Split) {
5276       Ops.push_back(DAG.getConstant(V.trunc(32), dl, EltVT));
5277       Ops.push_back(DAG.getConstant(V.lshr(32).trunc(32), dl, EltVT));
5278     } else if (EltVT == MVT::f32) {
5279       APFloat FV(APFloat::IEEEsingle(), V);
5280       Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
5281     } else if (EltVT == MVT::f64) {
5282       APFloat FV(APFloat::IEEEdouble(), V);
5283       Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
5284     } else {
5285       Ops.push_back(DAG.getConstant(V, dl, EltVT));
5286     }
5287   }
5288 
5289   SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
5290   return DAG.getBitcast(VT, ConstsNode);
5291 }
5292 
5293 /// Returns a vector of specified type with all zero elements.
getZeroVector(MVT VT,const X86Subtarget & Subtarget,SelectionDAG & DAG,const SDLoc & dl)5294 static SDValue getZeroVector(MVT VT, const X86Subtarget &Subtarget,
5295                              SelectionDAG &DAG, const SDLoc &dl) {
5296   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() ||
5297           VT.getVectorElementType() == MVT::i1) &&
5298          "Unexpected vector type");
5299 
5300   // Try to build SSE/AVX zero vectors as <N x i32> bitcasted to their dest
5301   // type. This ensures they get CSE'd. But if the integer type is not
5302   // available, use a floating-point +0.0 instead.
5303   SDValue Vec;
5304   if (!Subtarget.hasSSE2() && VT.is128BitVector()) {
5305     Vec = DAG.getConstantFP(+0.0, dl, MVT::v4f32);
5306   } else if (VT.getVectorElementType() == MVT::i1) {
5307     assert((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&
5308            "Unexpected vector type");
5309     Vec = DAG.getConstant(0, dl, VT);
5310   } else {
5311     unsigned Num32BitElts = VT.getSizeInBits() / 32;
5312     Vec = DAG.getConstant(0, dl, MVT::getVectorVT(MVT::i32, Num32BitElts));
5313   }
5314   return DAG.getBitcast(VT, Vec);
5315 }
5316 
extractSubVector(SDValue Vec,unsigned IdxVal,SelectionDAG & DAG,const SDLoc & dl,unsigned vectorWidth)5317 static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
5318                                 const SDLoc &dl, unsigned vectorWidth) {
5319   EVT VT = Vec.getValueType();
5320   EVT ElVT = VT.getVectorElementType();
5321   unsigned Factor = VT.getSizeInBits()/vectorWidth;
5322   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
5323                                   VT.getVectorNumElements()/Factor);
5324 
5325   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
5326   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
5327   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
5328 
5329   // This is the index of the first element of the vectorWidth-bit chunk
5330   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
5331   IdxVal &= ~(ElemsPerChunk - 1);
5332 
5333   // If the input is a buildvector just emit a smaller one.
5334   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
5335     return DAG.getBuildVector(ResultVT, dl,
5336                               Vec->ops().slice(IdxVal, ElemsPerChunk));
5337 
5338   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
5339   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
5340 }
5341 
5342 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
5343 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
5344 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
5345 /// instructions or a simple subregister reference. Idx is an index in the
5346 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
5347 /// lowering EXTRACT_VECTOR_ELT operations easier.
extract128BitVector(SDValue Vec,unsigned IdxVal,SelectionDAG & DAG,const SDLoc & dl)5348 static SDValue extract128BitVector(SDValue Vec, unsigned IdxVal,
5349                                    SelectionDAG &DAG, const SDLoc &dl) {
5350   assert((Vec.getValueType().is256BitVector() ||
5351           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
5352   return extractSubVector(Vec, IdxVal, DAG, dl, 128);
5353 }
5354 
5355 /// Generate a DAG to grab 256-bits from a 512-bit vector.
extract256BitVector(SDValue Vec,unsigned IdxVal,SelectionDAG & DAG,const SDLoc & dl)5356 static SDValue extract256BitVector(SDValue Vec, unsigned IdxVal,
5357                                    SelectionDAG &DAG, const SDLoc &dl) {
5358   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
5359   return extractSubVector(Vec, IdxVal, DAG, dl, 256);
5360 }
5361 
insertSubVector(SDValue Result,SDValue Vec,unsigned IdxVal,SelectionDAG & DAG,const SDLoc & dl,unsigned vectorWidth)5362 static SDValue insertSubVector(SDValue Result, SDValue Vec, unsigned IdxVal,
5363                                SelectionDAG &DAG, const SDLoc &dl,
5364                                unsigned vectorWidth) {
5365   assert((vectorWidth == 128 || vectorWidth == 256) &&
5366          "Unsupported vector width");
5367   // Inserting UNDEF is Result
5368   if (Vec.isUndef())
5369     return Result;
5370   EVT VT = Vec.getValueType();
5371   EVT ElVT = VT.getVectorElementType();
5372   EVT ResultVT = Result.getValueType();
5373 
5374   // Insert the relevant vectorWidth bits.
5375   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
5376   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
5377 
5378   // This is the index of the first element of the vectorWidth-bit chunk
5379   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
5380   IdxVal &= ~(ElemsPerChunk - 1);
5381 
5382   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
5383   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
5384 }
5385 
5386 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
5387 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
5388 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
5389 /// simple superregister reference.  Idx is an index in the 128 bits
5390 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
5391 /// lowering INSERT_VECTOR_ELT operations easier.
insert128BitVector(SDValue Result,SDValue Vec,unsigned IdxVal,SelectionDAG & DAG,const SDLoc & dl)5392 static SDValue insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
5393                                   SelectionDAG &DAG, const SDLoc &dl) {
5394   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
5395   return insertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
5396 }
5397 
5398 /// Widen a vector to a larger size with the same scalar type, with the new
5399 /// elements either zero or undef.
widenSubVector(MVT VT,SDValue Vec,bool ZeroNewElements,const X86Subtarget & Subtarget,SelectionDAG & DAG,const SDLoc & dl)5400 static SDValue widenSubVector(MVT VT, SDValue Vec, bool ZeroNewElements,
5401                               const X86Subtarget &Subtarget, SelectionDAG &DAG,
5402                               const SDLoc &dl) {
5403   assert(Vec.getValueSizeInBits() < VT.getSizeInBits() &&
5404          Vec.getValueType().getScalarType() == VT.getScalarType() &&
5405          "Unsupported vector widening type");
5406   SDValue Res = ZeroNewElements ? getZeroVector(VT, Subtarget, DAG, dl)
5407                                 : DAG.getUNDEF(VT);
5408   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, Vec,
5409                      DAG.getIntPtrConstant(0, dl));
5410 }
5411 
5412 // Helper for splitting operands of an operation to legal target size and
5413 // apply a function on each part.
5414 // Useful for operations that are available on SSE2 in 128-bit, on AVX2 in
5415 // 256-bit and on AVX512BW in 512-bit. The argument VT is the type used for
5416 // deciding if/how to split Ops. Ops elements do *not* have to be of type VT.
5417 // The argument Builder is a function that will be applied on each split part:
5418 // SDValue Builder(SelectionDAG&G, SDLoc, ArrayRef<SDValue>)
5419 template <typename F>
SplitOpsAndApply(SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & DL,EVT VT,ArrayRef<SDValue> Ops,F Builder,bool CheckBWI=true)5420 SDValue SplitOpsAndApply(SelectionDAG &DAG, const X86Subtarget &Subtarget,
5421                          const SDLoc &DL, EVT VT, ArrayRef<SDValue> Ops,
5422                          F Builder, bool CheckBWI = true) {
5423   assert(Subtarget.hasSSE2() && "Target assumed to support at least SSE2");
5424   unsigned NumSubs = 1;
5425   if ((CheckBWI && Subtarget.useBWIRegs()) ||
5426       (!CheckBWI && Subtarget.useAVX512Regs())) {
5427     if (VT.getSizeInBits() > 512) {
5428       NumSubs = VT.getSizeInBits() / 512;
5429       assert((VT.getSizeInBits() % 512) == 0 && "Illegal vector size");
5430     }
5431   } else if (Subtarget.hasAVX2()) {
5432     if (VT.getSizeInBits() > 256) {
5433       NumSubs = VT.getSizeInBits() / 256;
5434       assert((VT.getSizeInBits() % 256) == 0 && "Illegal vector size");
5435     }
5436   } else {
5437     if (VT.getSizeInBits() > 128) {
5438       NumSubs = VT.getSizeInBits() / 128;
5439       assert((VT.getSizeInBits() % 128) == 0 && "Illegal vector size");
5440     }
5441   }
5442 
5443   if (NumSubs == 1)
5444     return Builder(DAG, DL, Ops);
5445 
5446   SmallVector<SDValue, 4> Subs;
5447   for (unsigned i = 0; i != NumSubs; ++i) {
5448     SmallVector<SDValue, 2> SubOps;
5449     for (SDValue Op : Ops) {
5450       EVT OpVT = Op.getValueType();
5451       unsigned NumSubElts = OpVT.getVectorNumElements() / NumSubs;
5452       unsigned SizeSub = OpVT.getSizeInBits() / NumSubs;
5453       SubOps.push_back(extractSubVector(Op, i * NumSubElts, DAG, DL, SizeSub));
5454     }
5455     Subs.push_back(Builder(DAG, DL, SubOps));
5456   }
5457   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
5458 }
5459 
5460 // Return true if the instruction zeroes the unused upper part of the
5461 // destination and accepts mask.
isMaskedZeroUpperBitsvXi1(unsigned int Opcode)5462 static bool isMaskedZeroUpperBitsvXi1(unsigned int Opcode) {
5463   switch (Opcode) {
5464   default:
5465     return false;
5466   case X86ISD::CMPM:
5467   case X86ISD::CMPM_RND:
5468   case ISD::SETCC:
5469     return true;
5470   }
5471 }
5472 
5473 /// Insert i1-subvector to i1-vector.
insert1BitVector(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)5474 static SDValue insert1BitVector(SDValue Op, SelectionDAG &DAG,
5475                                 const X86Subtarget &Subtarget) {
5476 
5477   SDLoc dl(Op);
5478   SDValue Vec = Op.getOperand(0);
5479   SDValue SubVec = Op.getOperand(1);
5480   SDValue Idx = Op.getOperand(2);
5481 
5482   if (!isa<ConstantSDNode>(Idx))
5483     return SDValue();
5484 
5485   // Inserting undef is a nop. We can just return the original vector.
5486   if (SubVec.isUndef())
5487     return Vec;
5488 
5489   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5490   if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
5491     return Op;
5492 
5493   MVT OpVT = Op.getSimpleValueType();
5494   unsigned NumElems = OpVT.getVectorNumElements();
5495 
5496   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
5497 
5498   // Extend to natively supported kshift.
5499   MVT WideOpVT = OpVT;
5500   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8)
5501     WideOpVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
5502 
5503   // Inserting into the lsbs of a zero vector is legal. ISel will insert shifts
5504   // if necessary.
5505   if (IdxVal == 0 && ISD::isBuildVectorAllZeros(Vec.getNode())) {
5506     // May need to promote to a legal type.
5507     Op = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5508                      getZeroVector(WideOpVT, Subtarget, DAG, dl),
5509                      SubVec, Idx);
5510     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
5511   }
5512 
5513   MVT SubVecVT = SubVec.getSimpleValueType();
5514   unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
5515 
5516   assert(IdxVal + SubVecNumElems <= NumElems &&
5517          IdxVal % SubVecVT.getSizeInBits() == 0 &&
5518          "Unexpected index value in INSERT_SUBVECTOR");
5519 
5520   SDValue Undef = DAG.getUNDEF(WideOpVT);
5521 
5522   if (IdxVal == 0) {
5523     // Zero lower bits of the Vec
5524     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
5525     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec,
5526                       ZeroIdx);
5527     Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
5528     Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
5529     // Merge them together, SubVec should be zero extended.
5530     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5531                          getZeroVector(WideOpVT, Subtarget, DAG, dl),
5532                          SubVec, ZeroIdx);
5533     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
5534     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
5535   }
5536 
5537   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5538                        Undef, SubVec, ZeroIdx);
5539 
5540   if (Vec.isUndef()) {
5541     assert(IdxVal != 0 && "Unexpected index");
5542     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
5543                          DAG.getConstant(IdxVal, dl, MVT::i8));
5544     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
5545   }
5546 
5547   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
5548     assert(IdxVal != 0 && "Unexpected index");
5549     NumElems = WideOpVT.getVectorNumElements();
5550     unsigned ShiftLeft = NumElems - SubVecNumElems;
5551     unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
5552     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
5553                          DAG.getConstant(ShiftLeft, dl, MVT::i8));
5554     if (ShiftRight != 0)
5555       SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
5556                            DAG.getConstant(ShiftRight, dl, MVT::i8));
5557     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
5558   }
5559 
5560   // Simple case when we put subvector in the upper part
5561   if (IdxVal + SubVecNumElems == NumElems) {
5562     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
5563                          DAG.getConstant(IdxVal, dl, MVT::i8));
5564     if (SubVecNumElems * 2 == NumElems) {
5565       // Special case, use legal zero extending insert_subvector. This allows
5566       // isel to opimitize when bits are known zero.
5567       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVecVT, Vec, ZeroIdx);
5568       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5569                         getZeroVector(WideOpVT, Subtarget, DAG, dl),
5570                         Vec, ZeroIdx);
5571     } else {
5572       // Otherwise use explicit shifts to zero the bits.
5573       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5574                         Undef, Vec, ZeroIdx);
5575       NumElems = WideOpVT.getVectorNumElements();
5576       SDValue ShiftBits = DAG.getConstant(NumElems - IdxVal, dl, MVT::i8);
5577       Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
5578       Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
5579     }
5580     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
5581     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
5582   }
5583 
5584   // Inserting into the middle is more complicated.
5585 
5586   NumElems = WideOpVT.getVectorNumElements();
5587 
5588   // Widen the vector if needed.
5589   Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
5590   // Move the current value of the bit to be replace to the lsbs.
5591   Op = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec,
5592                    DAG.getConstant(IdxVal, dl, MVT::i8));
5593   // Xor with the new bit.
5594   Op = DAG.getNode(ISD::XOR, dl, WideOpVT, Op, SubVec);
5595   // Shift to MSB, filling bottom bits with 0.
5596   unsigned ShiftLeft = NumElems - SubVecNumElems;
5597   Op = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Op,
5598                    DAG.getConstant(ShiftLeft, dl, MVT::i8));
5599   // Shift to the final position, filling upper bits with 0.
5600   unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
5601   Op = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Op,
5602                        DAG.getConstant(ShiftRight, dl, MVT::i8));
5603   // Xor with original vector leaving the new value.
5604   Op = DAG.getNode(ISD::XOR, dl, WideOpVT, Vec, Op);
5605   // Reduce to original width if needed.
5606   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
5607 }
5608 
concatSubVectors(SDValue V1,SDValue V2,EVT VT,unsigned NumElems,SelectionDAG & DAG,const SDLoc & dl,unsigned VectorWidth)5609 static SDValue concatSubVectors(SDValue V1, SDValue V2, EVT VT,
5610                                 unsigned NumElems, SelectionDAG &DAG,
5611                                 const SDLoc &dl, unsigned VectorWidth) {
5612   SDValue V = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, dl, VectorWidth);
5613   return insertSubVector(V, V2, NumElems / 2, DAG, dl, VectorWidth);
5614 }
5615 
5616 /// Returns a vector of specified type with all bits set.
5617 /// Always build ones vectors as <4 x i32>, <8 x i32> or <16 x i32>.
5618 /// Then bitcast to their original type, ensuring they get CSE'd.
getOnesVector(EVT VT,SelectionDAG & DAG,const SDLoc & dl)5619 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5620   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5621          "Expected a 128/256/512-bit vector type");
5622 
5623   APInt Ones = APInt::getAllOnesValue(32);
5624   unsigned NumElts = VT.getSizeInBits() / 32;
5625   SDValue Vec = DAG.getConstant(Ones, dl, MVT::getVectorVT(MVT::i32, NumElts));
5626   return DAG.getBitcast(VT, Vec);
5627 }
5628 
getExtendInVec(bool Signed,const SDLoc & DL,EVT VT,SDValue In,SelectionDAG & DAG)5629 static SDValue getExtendInVec(bool Signed, const SDLoc &DL, EVT VT, SDValue In,
5630                               SelectionDAG &DAG) {
5631   EVT InVT = In.getValueType();
5632   assert(VT.isVector() && InVT.isVector() && "Expected vector VTs.");
5633 
5634   // For 256-bit vectors, we only need the lower (128-bit) input half.
5635   // For 512-bit vectors, we only need the lower input half or quarter.
5636   if (InVT.getSizeInBits() > 128) {
5637     assert(VT.getSizeInBits() == InVT.getSizeInBits() &&
5638            "Expected VTs to be the same size!");
5639     unsigned Scale = VT.getScalarSizeInBits() / InVT.getScalarSizeInBits();
5640     In = extractSubVector(In, 0, DAG, DL,
5641                           std::max(128U, VT.getSizeInBits() / Scale));
5642     InVT = In.getValueType();
5643   }
5644 
5645   if (VT.getVectorNumElements() == InVT.getVectorNumElements())
5646     return DAG.getNode(Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5647                        DL, VT, In);
5648 
5649   return DAG.getNode(Signed ? ISD::SIGN_EXTEND_VECTOR_INREG
5650                             : ISD::ZERO_EXTEND_VECTOR_INREG,
5651                      DL, VT, In);
5652 }
5653 
5654 /// Returns a vector_shuffle node for an unpackl operation.
getUnpackl(SelectionDAG & DAG,const SDLoc & dl,MVT VT,SDValue V1,SDValue V2)5655 static SDValue getUnpackl(SelectionDAG &DAG, const SDLoc &dl, MVT VT,
5656                           SDValue V1, SDValue V2) {
5657   SmallVector<int, 8> Mask;
5658   createUnpackShuffleMask(VT, Mask, /* Lo = */ true, /* Unary = */ false);
5659   return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
5660 }
5661 
5662 /// Returns a vector_shuffle node for an unpackh operation.
getUnpackh(SelectionDAG & DAG,const SDLoc & dl,MVT VT,SDValue V1,SDValue V2)5663 static SDValue getUnpackh(SelectionDAG &DAG, const SDLoc &dl, MVT VT,
5664                           SDValue V1, SDValue V2) {
5665   SmallVector<int, 8> Mask;
5666   createUnpackShuffleMask(VT, Mask, /* Lo = */ false, /* Unary = */ false);
5667   return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
5668 }
5669 
5670 /// Return a vector_shuffle of the specified vector of zero or undef vector.
5671 /// This produces a shuffle where the low element of V2 is swizzled into the
5672 /// zero/undef vector, landing at element Idx.
5673 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
getShuffleVectorZeroOrUndef(SDValue V2,int Idx,bool IsZero,const X86Subtarget & Subtarget,SelectionDAG & DAG)5674 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, int Idx,
5675                                            bool IsZero,
5676                                            const X86Subtarget &Subtarget,
5677                                            SelectionDAG &DAG) {
5678   MVT VT = V2.getSimpleValueType();
5679   SDValue V1 = IsZero
5680     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5681   int NumElems = VT.getVectorNumElements();
5682   SmallVector<int, 16> MaskVec(NumElems);
5683   for (int i = 0; i != NumElems; ++i)
5684     // If this is the insertion idx, put the low elt of V2 here.
5685     MaskVec[i] = (i == Idx) ? NumElems : i;
5686   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, MaskVec);
5687 }
5688 
5689 // Peek through EXTRACT_SUBVECTORs - typically used for AVX1 256-bit intops.
peekThroughEXTRACT_SUBVECTORs(SDValue V)5690 static SDValue peekThroughEXTRACT_SUBVECTORs(SDValue V) {
5691   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
5692     V = V.getOperand(0);
5693   return V;
5694 }
5695 
getTargetConstantFromNode(SDValue Op)5696 static const Constant *getTargetConstantFromNode(SDValue Op) {
5697   Op = peekThroughBitcasts(Op);
5698 
5699   auto *Load = dyn_cast<LoadSDNode>(Op);
5700   if (!Load)
5701     return nullptr;
5702 
5703   SDValue Ptr = Load->getBasePtr();
5704   if (Ptr->getOpcode() == X86ISD::Wrapper ||
5705       Ptr->getOpcode() == X86ISD::WrapperRIP)
5706     Ptr = Ptr->getOperand(0);
5707 
5708   auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
5709   if (!CNode || CNode->isMachineConstantPoolEntry() || CNode->getOffset() != 0)
5710     return nullptr;
5711 
5712   return CNode->getConstVal();
5713 }
5714 
5715 // Extract raw constant bits from constant pools.
getTargetConstantBitsFromNode(SDValue Op,unsigned EltSizeInBits,APInt & UndefElts,SmallVectorImpl<APInt> & EltBits,bool AllowWholeUndefs=true,bool AllowPartialUndefs=true)5716 static bool getTargetConstantBitsFromNode(SDValue Op, unsigned EltSizeInBits,
5717                                           APInt &UndefElts,
5718                                           SmallVectorImpl<APInt> &EltBits,
5719                                           bool AllowWholeUndefs = true,
5720                                           bool AllowPartialUndefs = true) {
5721   assert(EltBits.empty() && "Expected an empty EltBits vector");
5722 
5723   Op = peekThroughBitcasts(Op);
5724 
5725   EVT VT = Op.getValueType();
5726   unsigned SizeInBits = VT.getSizeInBits();
5727   assert((SizeInBits % EltSizeInBits) == 0 && "Can't split constant!");
5728   unsigned NumElts = SizeInBits / EltSizeInBits;
5729 
5730   // Bitcast a source array of element bits to the target size.
5731   auto CastBitData = [&](APInt &UndefSrcElts, ArrayRef<APInt> SrcEltBits) {
5732     unsigned NumSrcElts = UndefSrcElts.getBitWidth();
5733     unsigned SrcEltSizeInBits = SrcEltBits[0].getBitWidth();
5734     assert((NumSrcElts * SrcEltSizeInBits) == SizeInBits &&
5735            "Constant bit sizes don't match");
5736 
5737     // Don't split if we don't allow undef bits.
5738     bool AllowUndefs = AllowWholeUndefs || AllowPartialUndefs;
5739     if (UndefSrcElts.getBoolValue() && !AllowUndefs)
5740       return false;
5741 
5742     // If we're already the right size, don't bother bitcasting.
5743     if (NumSrcElts == NumElts) {
5744       UndefElts = UndefSrcElts;
5745       EltBits.assign(SrcEltBits.begin(), SrcEltBits.end());
5746       return true;
5747     }
5748 
5749     // Extract all the undef/constant element data and pack into single bitsets.
5750     APInt UndefBits(SizeInBits, 0);
5751     APInt MaskBits(SizeInBits, 0);
5752 
5753     for (unsigned i = 0; i != NumSrcElts; ++i) {
5754       unsigned BitOffset = i * SrcEltSizeInBits;
5755       if (UndefSrcElts[i])
5756         UndefBits.setBits(BitOffset, BitOffset + SrcEltSizeInBits);
5757       MaskBits.insertBits(SrcEltBits[i], BitOffset);
5758     }
5759 
5760     // Split the undef/constant single bitset data into the target elements.
5761     UndefElts = APInt(NumElts, 0);
5762     EltBits.resize(NumElts, APInt(EltSizeInBits, 0));
5763 
5764     for (unsigned i = 0; i != NumElts; ++i) {
5765       unsigned BitOffset = i * EltSizeInBits;
5766       APInt UndefEltBits = UndefBits.extractBits(EltSizeInBits, BitOffset);
5767 
5768       // Only treat an element as UNDEF if all bits are UNDEF.
5769       if (UndefEltBits.isAllOnesValue()) {
5770         if (!AllowWholeUndefs)
5771           return false;
5772         UndefElts.setBit(i);
5773         continue;
5774       }
5775 
5776       // If only some bits are UNDEF then treat them as zero (or bail if not
5777       // supported).
5778       if (UndefEltBits.getBoolValue() && !AllowPartialUndefs)
5779         return false;
5780 
5781       APInt Bits = MaskBits.extractBits(EltSizeInBits, BitOffset);
5782       EltBits[i] = Bits.getZExtValue();
5783     }
5784     return true;
5785   };
5786 
5787   // Collect constant bits and insert into mask/undef bit masks.
5788   auto CollectConstantBits = [](const Constant *Cst, APInt &Mask, APInt &Undefs,
5789                                 unsigned UndefBitIndex) {
5790     if (!Cst)
5791       return false;
5792     if (isa<UndefValue>(Cst)) {
5793       Undefs.setBit(UndefBitIndex);
5794       return true;
5795     }
5796     if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
5797       Mask = CInt->getValue();
5798       return true;
5799     }
5800     if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
5801       Mask = CFP->getValueAPF().bitcastToAPInt();
5802       return true;
5803     }
5804     return false;
5805   };
5806 
5807   // Handle UNDEFs.
5808   if (Op.isUndef()) {
5809     APInt UndefSrcElts = APInt::getAllOnesValue(NumElts);
5810     SmallVector<APInt, 64> SrcEltBits(NumElts, APInt(EltSizeInBits, 0));
5811     return CastBitData(UndefSrcElts, SrcEltBits);
5812   }
5813 
5814   // Extract scalar constant bits.
5815   if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) {
5816     APInt UndefSrcElts = APInt::getNullValue(1);
5817     SmallVector<APInt, 64> SrcEltBits(1, Cst->getAPIntValue());
5818     return CastBitData(UndefSrcElts, SrcEltBits);
5819   }
5820   if (auto *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
5821     APInt UndefSrcElts = APInt::getNullValue(1);
5822     APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
5823     SmallVector<APInt, 64> SrcEltBits(1, RawBits);
5824     return CastBitData(UndefSrcElts, SrcEltBits);
5825   }
5826 
5827   // Extract constant bits from build vector.
5828   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5829     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5830     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5831 
5832     APInt UndefSrcElts(NumSrcElts, 0);
5833     SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
5834     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
5835       const SDValue &Src = Op.getOperand(i);
5836       if (Src.isUndef()) {
5837         UndefSrcElts.setBit(i);
5838         continue;
5839       }
5840       auto *Cst = cast<ConstantSDNode>(Src);
5841       SrcEltBits[i] = Cst->getAPIntValue().zextOrTrunc(SrcEltSizeInBits);
5842     }
5843     return CastBitData(UndefSrcElts, SrcEltBits);
5844   }
5845   if (ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) {
5846     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5847     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5848 
5849     APInt UndefSrcElts(NumSrcElts, 0);
5850     SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
5851     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
5852       const SDValue &Src = Op.getOperand(i);
5853       if (Src.isUndef()) {
5854         UndefSrcElts.setBit(i);
5855         continue;
5856       }
5857       auto *Cst = cast<ConstantFPSDNode>(Src);
5858       APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
5859       SrcEltBits[i] = RawBits.zextOrTrunc(SrcEltSizeInBits);
5860     }
5861     return CastBitData(UndefSrcElts, SrcEltBits);
5862   }
5863 
5864   // Extract constant bits from constant pool vector.
5865   if (auto *Cst = getTargetConstantFromNode(Op)) {
5866     Type *CstTy = Cst->getType();
5867     unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
5868     if (!CstTy->isVectorTy() || (CstSizeInBits % SizeInBits) != 0)
5869       return false;
5870 
5871     unsigned SrcEltSizeInBits = CstTy->getScalarSizeInBits();
5872     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5873 
5874     APInt UndefSrcElts(NumSrcElts, 0);
5875     SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
5876     for (unsigned i = 0; i != NumSrcElts; ++i)
5877       if (!CollectConstantBits(Cst->getAggregateElement(i), SrcEltBits[i],
5878                                UndefSrcElts, i))
5879         return false;
5880 
5881     return CastBitData(UndefSrcElts, SrcEltBits);
5882   }
5883 
5884   // Extract constant bits from a broadcasted constant pool scalar.
5885   if (Op.getOpcode() == X86ISD::VBROADCAST &&
5886       EltSizeInBits <= VT.getScalarSizeInBits()) {
5887     if (auto *Broadcast = getTargetConstantFromNode(Op.getOperand(0))) {
5888       unsigned SrcEltSizeInBits = Broadcast->getType()->getScalarSizeInBits();
5889       unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5890 
5891       APInt UndefSrcElts(NumSrcElts, 0);
5892       SmallVector<APInt, 64> SrcEltBits(1, APInt(SrcEltSizeInBits, 0));
5893       if (CollectConstantBits(Broadcast, SrcEltBits[0], UndefSrcElts, 0)) {
5894         if (UndefSrcElts[0])
5895           UndefSrcElts.setBits(0, NumSrcElts);
5896         SrcEltBits.append(NumSrcElts - 1, SrcEltBits[0]);
5897         return CastBitData(UndefSrcElts, SrcEltBits);
5898       }
5899     }
5900   }
5901 
5902   // Extract a rematerialized scalar constant insertion.
5903   if (Op.getOpcode() == X86ISD::VZEXT_MOVL &&
5904       Op.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
5905       isa<ConstantSDNode>(Op.getOperand(0).getOperand(0))) {
5906     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5907     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5908 
5909     APInt UndefSrcElts(NumSrcElts, 0);
5910     SmallVector<APInt, 64> SrcEltBits;
5911     auto *CN = cast<ConstantSDNode>(Op.getOperand(0).getOperand(0));
5912     SrcEltBits.push_back(CN->getAPIntValue().zextOrTrunc(SrcEltSizeInBits));
5913     SrcEltBits.append(NumSrcElts - 1, APInt(SrcEltSizeInBits, 0));
5914     return CastBitData(UndefSrcElts, SrcEltBits);
5915   }
5916 
5917   // Extract constant bits from a subvector's source.
5918   if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5919       isa<ConstantSDNode>(Op.getOperand(1))) {
5920     // TODO - support extract_subvector through bitcasts.
5921     if (EltSizeInBits != VT.getScalarSizeInBits())
5922       return false;
5923 
5924     if (getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
5925                                       UndefElts, EltBits, AllowWholeUndefs,
5926                                       AllowPartialUndefs)) {
5927       EVT SrcVT = Op.getOperand(0).getValueType();
5928       unsigned NumSrcElts = SrcVT.getVectorNumElements();
5929       unsigned NumSubElts = VT.getVectorNumElements();
5930       unsigned BaseIdx = Op.getConstantOperandVal(1);
5931       UndefElts = UndefElts.extractBits(NumSubElts, BaseIdx);
5932       if ((BaseIdx + NumSubElts) != NumSrcElts)
5933         EltBits.erase(EltBits.begin() + BaseIdx + NumSubElts, EltBits.end());
5934       if (BaseIdx != 0)
5935         EltBits.erase(EltBits.begin(), EltBits.begin() + BaseIdx);
5936       return true;
5937     }
5938   }
5939 
5940   // Extract constant bits from shuffle node sources.
5941   if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Op)) {
5942     // TODO - support shuffle through bitcasts.
5943     if (EltSizeInBits != VT.getScalarSizeInBits())
5944       return false;
5945 
5946     ArrayRef<int> Mask = SVN->getMask();
5947     if ((!AllowWholeUndefs || !AllowPartialUndefs) &&
5948         llvm::any_of(Mask, [](int M) { return M < 0; }))
5949       return false;
5950 
5951     APInt UndefElts0, UndefElts1;
5952     SmallVector<APInt, 32> EltBits0, EltBits1;
5953     if (isAnyInRange(Mask, 0, NumElts) &&
5954         !getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
5955                                        UndefElts0, EltBits0, AllowWholeUndefs,
5956                                        AllowPartialUndefs))
5957       return false;
5958     if (isAnyInRange(Mask, NumElts, 2 * NumElts) &&
5959         !getTargetConstantBitsFromNode(Op.getOperand(1), EltSizeInBits,
5960                                        UndefElts1, EltBits1, AllowWholeUndefs,
5961                                        AllowPartialUndefs))
5962       return false;
5963 
5964     UndefElts = APInt::getNullValue(NumElts);
5965     for (int i = 0; i != (int)NumElts; ++i) {
5966       int M = Mask[i];
5967       if (M < 0) {
5968         UndefElts.setBit(i);
5969         EltBits.push_back(APInt::getNullValue(EltSizeInBits));
5970       } else if (M < (int)NumElts) {
5971         if (UndefElts0[M])
5972           UndefElts.setBit(i);
5973         EltBits.push_back(EltBits0[M]);
5974       } else {
5975         if (UndefElts1[M - NumElts])
5976           UndefElts.setBit(i);
5977         EltBits.push_back(EltBits1[M - NumElts]);
5978       }
5979     }
5980     return true;
5981   }
5982 
5983   return false;
5984 }
5985 
isConstantSplat(SDValue Op,APInt & SplatVal)5986 static bool isConstantSplat(SDValue Op, APInt &SplatVal) {
5987   APInt UndefElts;
5988   SmallVector<APInt, 16> EltBits;
5989   if (getTargetConstantBitsFromNode(Op, Op.getScalarValueSizeInBits(),
5990                                     UndefElts, EltBits, true, false)) {
5991     int SplatIndex = -1;
5992     for (int i = 0, e = EltBits.size(); i != e; ++i) {
5993       if (UndefElts[i])
5994         continue;
5995       if (0 <= SplatIndex && EltBits[i] != EltBits[SplatIndex]) {
5996         SplatIndex = -1;
5997         break;
5998       }
5999       SplatIndex = i;
6000     }
6001     if (0 <= SplatIndex) {
6002       SplatVal = EltBits[SplatIndex];
6003       return true;
6004     }
6005   }
6006 
6007   return false;
6008 }
6009 
getTargetShuffleMaskIndices(SDValue MaskNode,unsigned MaskEltSizeInBits,SmallVectorImpl<uint64_t> & RawMask,APInt & UndefElts)6010 static bool getTargetShuffleMaskIndices(SDValue MaskNode,
6011                                         unsigned MaskEltSizeInBits,
6012                                         SmallVectorImpl<uint64_t> &RawMask,
6013                                         APInt &UndefElts) {
6014   // Extract the raw target constant bits.
6015   SmallVector<APInt, 64> EltBits;
6016   if (!getTargetConstantBitsFromNode(MaskNode, MaskEltSizeInBits, UndefElts,
6017                                      EltBits, /* AllowWholeUndefs */ true,
6018                                      /* AllowPartialUndefs */ false))
6019     return false;
6020 
6021   // Insert the extracted elements into the mask.
6022   for (APInt Elt : EltBits)
6023     RawMask.push_back(Elt.getZExtValue());
6024 
6025   return true;
6026 }
6027 
6028 /// Create a shuffle mask that matches the PACKSS/PACKUS truncation.
6029 /// Note: This ignores saturation, so inputs must be checked first.
createPackShuffleMask(MVT VT,SmallVectorImpl<int> & Mask,bool Unary)6030 static void createPackShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
6031                                   bool Unary) {
6032   assert(Mask.empty() && "Expected an empty shuffle mask vector");
6033   unsigned NumElts = VT.getVectorNumElements();
6034   unsigned NumLanes = VT.getSizeInBits() / 128;
6035   unsigned NumEltsPerLane = 128 / VT.getScalarSizeInBits();
6036   unsigned Offset = Unary ? 0 : NumElts;
6037 
6038   for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
6039     for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += 2)
6040       Mask.push_back(Elt + (Lane * NumEltsPerLane));
6041     for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += 2)
6042       Mask.push_back(Elt + (Lane * NumEltsPerLane) + Offset);
6043   }
6044 }
6045 
6046 // Split the demanded elts of a PACKSS/PACKUS node between its operands.
getPackDemandedElts(EVT VT,const APInt & DemandedElts,APInt & DemandedLHS,APInt & DemandedRHS)6047 static void getPackDemandedElts(EVT VT, const APInt &DemandedElts,
6048                                 APInt &DemandedLHS, APInt &DemandedRHS) {
6049   int NumLanes = VT.getSizeInBits() / 128;
6050   int NumElts = DemandedElts.getBitWidth();
6051   int NumInnerElts = NumElts / 2;
6052   int NumEltsPerLane = NumElts / NumLanes;
6053   int NumInnerEltsPerLane = NumInnerElts / NumLanes;
6054 
6055   DemandedLHS = APInt::getNullValue(NumInnerElts);
6056   DemandedRHS = APInt::getNullValue(NumInnerElts);
6057 
6058   // Map DemandedElts to the packed operands.
6059   for (int Lane = 0; Lane != NumLanes; ++Lane) {
6060     for (int Elt = 0; Elt != NumInnerEltsPerLane; ++Elt) {
6061       int OuterIdx = (Lane * NumEltsPerLane) + Elt;
6062       int InnerIdx = (Lane * NumInnerEltsPerLane) + Elt;
6063       if (DemandedElts[OuterIdx])
6064         DemandedLHS.setBit(InnerIdx);
6065       if (DemandedElts[OuterIdx + NumInnerEltsPerLane])
6066         DemandedRHS.setBit(InnerIdx);
6067     }
6068   }
6069 }
6070 
6071 /// Calculates the shuffle mask corresponding to the target-specific opcode.
6072 /// If the mask could be calculated, returns it in \p Mask, returns the shuffle
6073 /// operands in \p Ops, and returns true.
6074 /// Sets \p IsUnary to true if only one source is used. Note that this will set
6075 /// IsUnary for shuffles which use a single input multiple times, and in those
6076 /// cases it will adjust the mask to only have indices within that single input.
6077 /// It is an error to call this with non-empty Mask/Ops vectors.
getTargetShuffleMask(SDNode * N,MVT VT,bool AllowSentinelZero,SmallVectorImpl<SDValue> & Ops,SmallVectorImpl<int> & Mask,bool & IsUnary)6078 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
6079                                  SmallVectorImpl<SDValue> &Ops,
6080                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
6081   unsigned NumElems = VT.getVectorNumElements();
6082   unsigned MaskEltSize = VT.getScalarSizeInBits();
6083   SmallVector<uint64_t, 32> RawMask;
6084   APInt RawUndefs;
6085   SDValue ImmN;
6086 
6087   assert(Mask.empty() && "getTargetShuffleMask expects an empty Mask vector");
6088   assert(Ops.empty() && "getTargetShuffleMask expects an empty Ops vector");
6089 
6090   IsUnary = false;
6091   bool IsFakeUnary = false;
6092   switch (N->getOpcode()) {
6093   case X86ISD::BLENDI:
6094     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6095     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6096     ImmN = N->getOperand(N->getNumOperands() - 1);
6097     DecodeBLENDMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
6098     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6099     break;
6100   case X86ISD::SHUFP:
6101     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6102     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6103     ImmN = N->getOperand(N->getNumOperands() - 1);
6104     DecodeSHUFPMask(NumElems, MaskEltSize,
6105                     cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
6106     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6107     break;
6108   case X86ISD::INSERTPS:
6109     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6110     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6111     ImmN = N->getOperand(N->getNumOperands() - 1);
6112     DecodeINSERTPSMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
6113     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6114     break;
6115   case X86ISD::EXTRQI:
6116     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6117     if (isa<ConstantSDNode>(N->getOperand(1)) &&
6118         isa<ConstantSDNode>(N->getOperand(2))) {
6119       int BitLen = N->getConstantOperandVal(1);
6120       int BitIdx = N->getConstantOperandVal(2);
6121       DecodeEXTRQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
6122       IsUnary = true;
6123     }
6124     break;
6125   case X86ISD::INSERTQI:
6126     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6127     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6128     if (isa<ConstantSDNode>(N->getOperand(2)) &&
6129         isa<ConstantSDNode>(N->getOperand(3))) {
6130       int BitLen = N->getConstantOperandVal(2);
6131       int BitIdx = N->getConstantOperandVal(3);
6132       DecodeINSERTQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
6133       IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6134     }
6135     break;
6136   case X86ISD::UNPCKH:
6137     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6138     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6139     DecodeUNPCKHMask(NumElems, MaskEltSize, Mask);
6140     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6141     break;
6142   case X86ISD::UNPCKL:
6143     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6144     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6145     DecodeUNPCKLMask(NumElems, MaskEltSize, Mask);
6146     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6147     break;
6148   case X86ISD::MOVHLPS:
6149     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6150     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6151     DecodeMOVHLPSMask(NumElems, Mask);
6152     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6153     break;
6154   case X86ISD::MOVLHPS:
6155     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6156     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6157     DecodeMOVLHPSMask(NumElems, Mask);
6158     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6159     break;
6160   case X86ISD::PALIGNR:
6161     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6162     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6163     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6164     ImmN = N->getOperand(N->getNumOperands() - 1);
6165     DecodePALIGNRMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
6166                       Mask);
6167     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6168     Ops.push_back(N->getOperand(1));
6169     Ops.push_back(N->getOperand(0));
6170     break;
6171   case X86ISD::VSHLDQ:
6172     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6173     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6174     ImmN = N->getOperand(N->getNumOperands() - 1);
6175     DecodePSLLDQMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
6176                      Mask);
6177     IsUnary = true;
6178     break;
6179   case X86ISD::VSRLDQ:
6180     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6181     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6182     ImmN = N->getOperand(N->getNumOperands() - 1);
6183     DecodePSRLDQMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
6184                      Mask);
6185     IsUnary = true;
6186     break;
6187   case X86ISD::PSHUFD:
6188   case X86ISD::VPERMILPI:
6189     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6190     ImmN = N->getOperand(N->getNumOperands() - 1);
6191     DecodePSHUFMask(NumElems, MaskEltSize,
6192                     cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
6193     IsUnary = true;
6194     break;
6195   case X86ISD::PSHUFHW:
6196     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6197     ImmN = N->getOperand(N->getNumOperands() - 1);
6198     DecodePSHUFHWMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
6199                       Mask);
6200     IsUnary = true;
6201     break;
6202   case X86ISD::PSHUFLW:
6203     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6204     ImmN = N->getOperand(N->getNumOperands() - 1);
6205     DecodePSHUFLWMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
6206                       Mask);
6207     IsUnary = true;
6208     break;
6209   case X86ISD::VZEXT_MOVL:
6210     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6211     DecodeZeroMoveLowMask(NumElems, Mask);
6212     IsUnary = true;
6213     break;
6214   case X86ISD::VBROADCAST: {
6215     SDValue N0 = N->getOperand(0);
6216     // See if we're broadcasting from index 0 of an EXTRACT_SUBVECTOR. If so,
6217     // add the pre-extracted value to the Ops vector.
6218     if (N0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6219         N0.getOperand(0).getValueType() == VT &&
6220         N0.getConstantOperandVal(1) == 0)
6221       Ops.push_back(N0.getOperand(0));
6222 
6223     // We only decode broadcasts of same-sized vectors, unless the broadcast
6224     // came from an extract from the original width. If we found one, we
6225     // pushed it the Ops vector above.
6226     if (N0.getValueType() == VT || !Ops.empty()) {
6227       DecodeVectorBroadcast(NumElems, Mask);
6228       IsUnary = true;
6229       break;
6230     }
6231     return false;
6232   }
6233   case X86ISD::VPERMILPV: {
6234     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6235     IsUnary = true;
6236     SDValue MaskNode = N->getOperand(1);
6237     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6238                                     RawUndefs)) {
6239       DecodeVPERMILPMask(NumElems, MaskEltSize, RawMask, RawUndefs, Mask);
6240       break;
6241     }
6242     return false;
6243   }
6244   case X86ISD::PSHUFB: {
6245     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6246     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6247     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6248     IsUnary = true;
6249     SDValue MaskNode = N->getOperand(1);
6250     if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
6251       DecodePSHUFBMask(RawMask, RawUndefs, Mask);
6252       break;
6253     }
6254     return false;
6255   }
6256   case X86ISD::VPERMI:
6257     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6258     ImmN = N->getOperand(N->getNumOperands() - 1);
6259     DecodeVPERMMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
6260     IsUnary = true;
6261     break;
6262   case X86ISD::MOVSS:
6263   case X86ISD::MOVSD:
6264     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6265     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6266     DecodeScalarMoveMask(NumElems, /* IsLoad */ false, Mask);
6267     break;
6268   case X86ISD::VPERM2X128:
6269     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6270     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6271     ImmN = N->getOperand(N->getNumOperands() - 1);
6272     DecodeVPERM2X128Mask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
6273                          Mask);
6274     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6275     break;
6276   case X86ISD::SHUF128:
6277     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6278     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6279     ImmN = N->getOperand(N->getNumOperands() - 1);
6280     decodeVSHUF64x2FamilyMask(NumElems, MaskEltSize,
6281                               cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
6282     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6283     break;
6284   case X86ISD::MOVSLDUP:
6285     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6286     DecodeMOVSLDUPMask(NumElems, Mask);
6287     IsUnary = true;
6288     break;
6289   case X86ISD::MOVSHDUP:
6290     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6291     DecodeMOVSHDUPMask(NumElems, Mask);
6292     IsUnary = true;
6293     break;
6294   case X86ISD::MOVDDUP:
6295     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6296     DecodeMOVDDUPMask(NumElems, Mask);
6297     IsUnary = true;
6298     break;
6299   case X86ISD::VPERMIL2: {
6300     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6301     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6302     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6303     SDValue MaskNode = N->getOperand(2);
6304     SDValue CtrlNode = N->getOperand(3);
6305     if (ConstantSDNode *CtrlOp = dyn_cast<ConstantSDNode>(CtrlNode)) {
6306       unsigned CtrlImm = CtrlOp->getZExtValue();
6307       if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6308                                       RawUndefs)) {
6309         DecodeVPERMIL2PMask(NumElems, MaskEltSize, CtrlImm, RawMask, RawUndefs,
6310                             Mask);
6311         break;
6312       }
6313     }
6314     return false;
6315   }
6316   case X86ISD::VPPERM: {
6317     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6318     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6319     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6320     SDValue MaskNode = N->getOperand(2);
6321     if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
6322       DecodeVPPERMMask(RawMask, RawUndefs, Mask);
6323       break;
6324     }
6325     return false;
6326   }
6327   case X86ISD::VPERMV: {
6328     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6329     IsUnary = true;
6330     // Unlike most shuffle nodes, VPERMV's mask operand is operand 0.
6331     Ops.push_back(N->getOperand(1));
6332     SDValue MaskNode = N->getOperand(0);
6333     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6334                                     RawUndefs)) {
6335       DecodeVPERMVMask(RawMask, RawUndefs, Mask);
6336       break;
6337     }
6338     return false;
6339   }
6340   case X86ISD::VPERMV3: {
6341     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6342     assert(N->getOperand(2).getValueType() == VT && "Unexpected value type");
6343     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(2);
6344     // Unlike most shuffle nodes, VPERMV3's mask operand is the middle one.
6345     Ops.push_back(N->getOperand(0));
6346     Ops.push_back(N->getOperand(2));
6347     SDValue MaskNode = N->getOperand(1);
6348     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6349                                     RawUndefs)) {
6350       DecodeVPERMV3Mask(RawMask, RawUndefs, Mask);
6351       break;
6352     }
6353     return false;
6354   }
6355   default: llvm_unreachable("unknown target shuffle node");
6356   }
6357 
6358   // Empty mask indicates the decode failed.
6359   if (Mask.empty())
6360     return false;
6361 
6362   // Check if we're getting a shuffle mask with zero'd elements.
6363   if (!AllowSentinelZero)
6364     if (any_of(Mask, [](int M) { return M == SM_SentinelZero; }))
6365       return false;
6366 
6367   // If we have a fake unary shuffle, the shuffle mask is spread across two
6368   // inputs that are actually the same node. Re-map the mask to always point
6369   // into the first input.
6370   if (IsFakeUnary)
6371     for (int &M : Mask)
6372       if (M >= (int)Mask.size())
6373         M -= Mask.size();
6374 
6375   // If we didn't already add operands in the opcode-specific code, default to
6376   // adding 1 or 2 operands starting at 0.
6377   if (Ops.empty()) {
6378     Ops.push_back(N->getOperand(0));
6379     if (!IsUnary || IsFakeUnary)
6380       Ops.push_back(N->getOperand(1));
6381   }
6382 
6383   return true;
6384 }
6385 
6386 /// Check a target shuffle mask's inputs to see if we can set any values to
6387 /// SM_SentinelZero - this is for elements that are known to be zero
6388 /// (not just zeroable) from their inputs.
6389 /// Returns true if the target shuffle mask was decoded.
setTargetShuffleZeroElements(SDValue N,SmallVectorImpl<int> & Mask,SmallVectorImpl<SDValue> & Ops)6390 static bool setTargetShuffleZeroElements(SDValue N,
6391                                          SmallVectorImpl<int> &Mask,
6392                                          SmallVectorImpl<SDValue> &Ops) {
6393   bool IsUnary;
6394   if (!isTargetShuffle(N.getOpcode()))
6395     return false;
6396 
6397   MVT VT = N.getSimpleValueType();
6398   if (!getTargetShuffleMask(N.getNode(), VT, true, Ops, Mask, IsUnary))
6399     return false;
6400 
6401   SDValue V1 = Ops[0];
6402   SDValue V2 = IsUnary ? V1 : Ops[1];
6403 
6404   V1 = peekThroughBitcasts(V1);
6405   V2 = peekThroughBitcasts(V2);
6406 
6407   assert((VT.getSizeInBits() % Mask.size()) == 0 &&
6408          "Illegal split of shuffle value type");
6409   unsigned EltSizeInBits = VT.getSizeInBits() / Mask.size();
6410 
6411   // Extract known constant input data.
6412   APInt UndefSrcElts[2];
6413   SmallVector<APInt, 32> SrcEltBits[2];
6414   bool IsSrcConstant[2] = {
6415       getTargetConstantBitsFromNode(V1, EltSizeInBits, UndefSrcElts[0],
6416                                     SrcEltBits[0], true, false),
6417       getTargetConstantBitsFromNode(V2, EltSizeInBits, UndefSrcElts[1],
6418                                     SrcEltBits[1], true, false)};
6419 
6420   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6421     int M = Mask[i];
6422 
6423     // Already decoded as SM_SentinelZero / SM_SentinelUndef.
6424     if (M < 0)
6425       continue;
6426 
6427     // Determine shuffle input and normalize the mask.
6428     unsigned SrcIdx = M / Size;
6429     SDValue V = M < Size ? V1 : V2;
6430     M %= Size;
6431 
6432     // We are referencing an UNDEF input.
6433     if (V.isUndef()) {
6434       Mask[i] = SM_SentinelUndef;
6435       continue;
6436     }
6437 
6438     // SCALAR_TO_VECTOR - only the first element is defined, and the rest UNDEF.
6439     // TODO: We currently only set UNDEF for integer types - floats use the same
6440     // registers as vectors and many of the scalar folded loads rely on the
6441     // SCALAR_TO_VECTOR pattern.
6442     if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6443         (Size % V.getValueType().getVectorNumElements()) == 0) {
6444       int Scale = Size / V.getValueType().getVectorNumElements();
6445       int Idx = M / Scale;
6446       if (Idx != 0 && !VT.isFloatingPoint())
6447         Mask[i] = SM_SentinelUndef;
6448       else if (Idx == 0 && X86::isZeroNode(V.getOperand(0)))
6449         Mask[i] = SM_SentinelZero;
6450       continue;
6451     }
6452 
6453     // Attempt to extract from the source's constant bits.
6454     if (IsSrcConstant[SrcIdx]) {
6455       if (UndefSrcElts[SrcIdx][M])
6456         Mask[i] = SM_SentinelUndef;
6457       else if (SrcEltBits[SrcIdx][M] == 0)
6458         Mask[i] = SM_SentinelZero;
6459     }
6460   }
6461 
6462   assert(VT.getVectorNumElements() == Mask.size() &&
6463          "Different mask size from vector size!");
6464   return true;
6465 }
6466 
6467 // Forward declaration (for getFauxShuffleMask recursive check).
6468 static bool resolveTargetShuffleInputs(SDValue Op,
6469                                        SmallVectorImpl<SDValue> &Inputs,
6470                                        SmallVectorImpl<int> &Mask,
6471                                        const SelectionDAG &DAG);
6472 
6473 // Attempt to decode ops that could be represented as a shuffle mask.
6474 // The decoded shuffle mask may contain a different number of elements to the
6475 // destination value type.
getFauxShuffleMask(SDValue N,SmallVectorImpl<int> & Mask,SmallVectorImpl<SDValue> & Ops,const SelectionDAG & DAG)6476 static bool getFauxShuffleMask(SDValue N, SmallVectorImpl<int> &Mask,
6477                                SmallVectorImpl<SDValue> &Ops,
6478                                const SelectionDAG &DAG) {
6479   Mask.clear();
6480   Ops.clear();
6481 
6482   MVT VT = N.getSimpleValueType();
6483   unsigned NumElts = VT.getVectorNumElements();
6484   unsigned NumSizeInBits = VT.getSizeInBits();
6485   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
6486   assert((NumBitsPerElt % 8) == 0 && (NumSizeInBits % 8) == 0 &&
6487          "Expected byte aligned value types");
6488 
6489   unsigned Opcode = N.getOpcode();
6490   switch (Opcode) {
6491   case ISD::VECTOR_SHUFFLE: {
6492     // Don't treat ISD::VECTOR_SHUFFLE as a target shuffle so decode it here.
6493     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(N)->getMask();
6494     if (isUndefOrInRange(ShuffleMask, 0, 2 * NumElts)) {
6495       Mask.append(ShuffleMask.begin(), ShuffleMask.end());
6496       Ops.push_back(N.getOperand(0));
6497       Ops.push_back(N.getOperand(1));
6498       return true;
6499     }
6500     return false;
6501   }
6502   case ISD::AND:
6503   case X86ISD::ANDNP: {
6504     // Attempt to decode as a per-byte mask.
6505     APInt UndefElts;
6506     SmallVector<APInt, 32> EltBits;
6507     SDValue N0 = N.getOperand(0);
6508     SDValue N1 = N.getOperand(1);
6509     bool IsAndN = (X86ISD::ANDNP == Opcode);
6510     uint64_t ZeroMask = IsAndN ? 255 : 0;
6511     if (!getTargetConstantBitsFromNode(IsAndN ? N0 : N1, 8, UndefElts, EltBits))
6512       return false;
6513     for (int i = 0, e = (int)EltBits.size(); i != e; ++i) {
6514       if (UndefElts[i]) {
6515         Mask.push_back(SM_SentinelUndef);
6516         continue;
6517       }
6518       uint64_t ByteBits = EltBits[i].getZExtValue();
6519       if (ByteBits != 0 && ByteBits != 255)
6520         return false;
6521       Mask.push_back(ByteBits == ZeroMask ? SM_SentinelZero : i);
6522     }
6523     Ops.push_back(IsAndN ? N1 : N0);
6524     return true;
6525   }
6526   case ISD::OR: {
6527     // Handle OR(SHUFFLE,SHUFFLE) case where one source is zero and the other
6528     // is a valid shuffle index.
6529     SDValue N0 = peekThroughOneUseBitcasts(N.getOperand(0));
6530     SDValue N1 = peekThroughOneUseBitcasts(N.getOperand(1));
6531     if (!N0.getValueType().isVector() || !N1.getValueType().isVector())
6532       return false;
6533     SmallVector<int, 64> SrcMask0, SrcMask1;
6534     SmallVector<SDValue, 2> SrcInputs0, SrcInputs1;
6535     if (!resolveTargetShuffleInputs(N0, SrcInputs0, SrcMask0, DAG) ||
6536         !resolveTargetShuffleInputs(N1, SrcInputs1, SrcMask1, DAG))
6537       return false;
6538     int MaskSize = std::max(SrcMask0.size(), SrcMask1.size());
6539     SmallVector<int, 64> Mask0, Mask1;
6540     scaleShuffleMask<int>(MaskSize / SrcMask0.size(), SrcMask0, Mask0);
6541     scaleShuffleMask<int>(MaskSize / SrcMask1.size(), SrcMask1, Mask1);
6542     for (int i = 0; i != MaskSize; ++i) {
6543       if (Mask0[i] == SM_SentinelUndef && Mask1[i] == SM_SentinelUndef)
6544         Mask.push_back(SM_SentinelUndef);
6545       else if (Mask0[i] == SM_SentinelZero && Mask1[i] == SM_SentinelZero)
6546         Mask.push_back(SM_SentinelZero);
6547       else if (Mask1[i] == SM_SentinelZero)
6548         Mask.push_back(Mask0[i]);
6549       else if (Mask0[i] == SM_SentinelZero)
6550         Mask.push_back(Mask1[i] + (MaskSize * SrcInputs0.size()));
6551       else
6552         return false;
6553     }
6554     for (SDValue &Op : SrcInputs0)
6555       Ops.push_back(Op);
6556     for (SDValue &Op : SrcInputs1)
6557       Ops.push_back(Op);
6558     return true;
6559   }
6560   case ISD::INSERT_SUBVECTOR: {
6561     // Handle INSERT_SUBVECTOR(SRC0, SHUFFLE(EXTRACT_SUBVECTOR(SRC1)) where
6562     // SRC0/SRC1 are both of the same valuetype VT.
6563     // TODO - add peekThroughOneUseBitcasts support.
6564     SDValue Src = N.getOperand(0);
6565     SDValue Sub = N.getOperand(1);
6566     EVT SubVT = Sub.getValueType();
6567     unsigned NumSubElts = SubVT.getVectorNumElements();
6568     if (!isa<ConstantSDNode>(N.getOperand(2)) ||
6569         !N->isOnlyUserOf(Sub.getNode()))
6570       return false;
6571     SmallVector<int, 64> SubMask;
6572     SmallVector<SDValue, 2> SubInputs;
6573     if (!resolveTargetShuffleInputs(Sub, SubInputs, SubMask, DAG) ||
6574         SubMask.size() != NumSubElts)
6575       return false;
6576     Ops.push_back(Src);
6577     for (SDValue &SubInput : SubInputs) {
6578       if (SubInput.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
6579           SubInput.getOperand(0).getValueType() != VT ||
6580           !isa<ConstantSDNode>(SubInput.getOperand(1)))
6581         return false;
6582       Ops.push_back(SubInput.getOperand(0));
6583     }
6584     int InsertIdx = N.getConstantOperandVal(2);
6585     for (int i = 0; i != (int)NumElts; ++i)
6586       Mask.push_back(i);
6587     for (int i = 0; i != (int)NumSubElts; ++i) {
6588       int M = SubMask[i];
6589       if (0 <= M) {
6590         int InputIdx = M / NumSubElts;
6591         int ExtractIdx = SubInputs[InputIdx].getConstantOperandVal(1);
6592         M = (NumElts * (1 + InputIdx)) + ExtractIdx + (M % NumSubElts);
6593       }
6594       Mask[i + InsertIdx] = M;
6595     }
6596     return true;
6597   }
6598   case ISD::SCALAR_TO_VECTOR: {
6599     // Match against a scalar_to_vector of an extract from a vector,
6600     // for PEXTRW/PEXTRB we must handle the implicit zext of the scalar.
6601     SDValue N0 = N.getOperand(0);
6602     SDValue SrcExtract;
6603 
6604     if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6605          N0.getOperand(0).getValueType() == VT) ||
6606         (N0.getOpcode() == X86ISD::PEXTRW &&
6607          N0.getOperand(0).getValueType() == MVT::v8i16) ||
6608         (N0.getOpcode() == X86ISD::PEXTRB &&
6609          N0.getOperand(0).getValueType() == MVT::v16i8)) {
6610       SrcExtract = N0;
6611     }
6612 
6613     if (!SrcExtract || !isa<ConstantSDNode>(SrcExtract.getOperand(1)))
6614       return false;
6615 
6616     SDValue SrcVec = SrcExtract.getOperand(0);
6617     EVT SrcVT = SrcVec.getValueType();
6618     unsigned NumSrcElts = SrcVT.getVectorNumElements();
6619     unsigned NumZeros = (NumBitsPerElt / SrcVT.getScalarSizeInBits()) - 1;
6620 
6621     unsigned SrcIdx = SrcExtract.getConstantOperandVal(1);
6622     if (NumSrcElts <= SrcIdx)
6623       return false;
6624 
6625     Ops.push_back(SrcVec);
6626     Mask.push_back(SrcIdx);
6627     Mask.append(NumZeros, SM_SentinelZero);
6628     Mask.append(NumSrcElts - Mask.size(), SM_SentinelUndef);
6629     return true;
6630   }
6631   case X86ISD::PINSRB:
6632   case X86ISD::PINSRW: {
6633     SDValue InVec = N.getOperand(0);
6634     SDValue InScl = N.getOperand(1);
6635     SDValue InIndex = N.getOperand(2);
6636     if (!isa<ConstantSDNode>(InIndex) ||
6637         cast<ConstantSDNode>(InIndex)->getAPIntValue().uge(NumElts))
6638       return false;
6639     uint64_t InIdx = N.getConstantOperandVal(2);
6640 
6641     // Attempt to recognise a PINSR*(VEC, 0, Idx) shuffle pattern.
6642     if (X86::isZeroNode(InScl)) {
6643       Ops.push_back(InVec);
6644       for (unsigned i = 0; i != NumElts; ++i)
6645         Mask.push_back(i == InIdx ? SM_SentinelZero : (int)i);
6646       return true;
6647     }
6648 
6649     // Attempt to recognise a PINSR*(PEXTR*) shuffle pattern.
6650     // TODO: Expand this to support INSERT_VECTOR_ELT/etc.
6651     unsigned ExOp =
6652         (X86ISD::PINSRB == Opcode ? X86ISD::PEXTRB : X86ISD::PEXTRW);
6653     if (InScl.getOpcode() != ExOp)
6654       return false;
6655 
6656     SDValue ExVec = InScl.getOperand(0);
6657     SDValue ExIndex = InScl.getOperand(1);
6658     if (!isa<ConstantSDNode>(ExIndex) ||
6659         cast<ConstantSDNode>(ExIndex)->getAPIntValue().uge(NumElts))
6660       return false;
6661     uint64_t ExIdx = InScl.getConstantOperandVal(1);
6662 
6663     Ops.push_back(InVec);
6664     Ops.push_back(ExVec);
6665     for (unsigned i = 0; i != NumElts; ++i)
6666       Mask.push_back(i == InIdx ? NumElts + ExIdx : i);
6667     return true;
6668   }
6669   case X86ISD::PACKSS:
6670   case X86ISD::PACKUS: {
6671     SDValue N0 = N.getOperand(0);
6672     SDValue N1 = N.getOperand(1);
6673     assert(N0.getValueType().getVectorNumElements() == (NumElts / 2) &&
6674            N1.getValueType().getVectorNumElements() == (NumElts / 2) &&
6675            "Unexpected input value type");
6676 
6677     // If we know input saturation won't happen we can treat this
6678     // as a truncation shuffle.
6679     if (Opcode == X86ISD::PACKSS) {
6680       if ((!N0.isUndef() && DAG.ComputeNumSignBits(N0) <= NumBitsPerElt) ||
6681           (!N1.isUndef() && DAG.ComputeNumSignBits(N1) <= NumBitsPerElt))
6682         return false;
6683     } else {
6684       APInt ZeroMask = APInt::getHighBitsSet(2 * NumBitsPerElt, NumBitsPerElt);
6685       if ((!N0.isUndef() && !DAG.MaskedValueIsZero(N0, ZeroMask)) ||
6686           (!N1.isUndef() && !DAG.MaskedValueIsZero(N1, ZeroMask)))
6687         return false;
6688     }
6689 
6690     bool IsUnary = (N0 == N1);
6691 
6692     Ops.push_back(N0);
6693     if (!IsUnary)
6694       Ops.push_back(N1);
6695 
6696     createPackShuffleMask(VT, Mask, IsUnary);
6697     return true;
6698   }
6699   case X86ISD::VSHLI:
6700   case X86ISD::VSRLI: {
6701     uint64_t ShiftVal = N.getConstantOperandVal(1);
6702     // Out of range bit shifts are guaranteed to be zero.
6703     if (NumBitsPerElt <= ShiftVal) {
6704       Mask.append(NumElts, SM_SentinelZero);
6705       return true;
6706     }
6707 
6708     // We can only decode 'whole byte' bit shifts as shuffles.
6709     if ((ShiftVal % 8) != 0)
6710       break;
6711 
6712     uint64_t ByteShift = ShiftVal / 8;
6713     unsigned NumBytes = NumSizeInBits / 8;
6714     unsigned NumBytesPerElt = NumBitsPerElt / 8;
6715     Ops.push_back(N.getOperand(0));
6716 
6717     // Clear mask to all zeros and insert the shifted byte indices.
6718     Mask.append(NumBytes, SM_SentinelZero);
6719 
6720     if (X86ISD::VSHLI == Opcode) {
6721       for (unsigned i = 0; i != NumBytes; i += NumBytesPerElt)
6722         for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
6723           Mask[i + j] = i + j - ByteShift;
6724     } else {
6725       for (unsigned i = 0; i != NumBytes; i += NumBytesPerElt)
6726         for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
6727           Mask[i + j - ByteShift] = i + j;
6728     }
6729     return true;
6730   }
6731   case ISD::ZERO_EXTEND_VECTOR_INREG:
6732   case ISD::ZERO_EXTEND: {
6733     // TODO - add support for VPMOVZX with smaller input vector types.
6734     SDValue Src = N.getOperand(0);
6735     MVT SrcVT = Src.getSimpleValueType();
6736     if (NumSizeInBits != SrcVT.getSizeInBits())
6737       break;
6738     DecodeZeroExtendMask(SrcVT.getScalarSizeInBits(), NumBitsPerElt, NumElts,
6739                          Mask);
6740     Ops.push_back(Src);
6741     return true;
6742   }
6743   }
6744 
6745   return false;
6746 }
6747 
6748 /// Removes unused shuffle source inputs and adjusts the shuffle mask accordingly.
resolveTargetShuffleInputsAndMask(SmallVectorImpl<SDValue> & Inputs,SmallVectorImpl<int> & Mask)6749 static void resolveTargetShuffleInputsAndMask(SmallVectorImpl<SDValue> &Inputs,
6750                                               SmallVectorImpl<int> &Mask) {
6751   int MaskWidth = Mask.size();
6752   SmallVector<SDValue, 16> UsedInputs;
6753   for (int i = 0, e = Inputs.size(); i < e; ++i) {
6754     int lo = UsedInputs.size() * MaskWidth;
6755     int hi = lo + MaskWidth;
6756 
6757     // Strip UNDEF input usage.
6758     if (Inputs[i].isUndef())
6759       for (int &M : Mask)
6760         if ((lo <= M) && (M < hi))
6761           M = SM_SentinelUndef;
6762 
6763     // Check for unused inputs.
6764     if (any_of(Mask, [lo, hi](int i) { return (lo <= i) && (i < hi); })) {
6765       UsedInputs.push_back(Inputs[i]);
6766       continue;
6767     }
6768     for (int &M : Mask)
6769       if (lo <= M)
6770         M -= MaskWidth;
6771   }
6772   Inputs = UsedInputs;
6773 }
6774 
6775 /// Calls setTargetShuffleZeroElements to resolve a target shuffle mask's inputs
6776 /// and set the SM_SentinelUndef and SM_SentinelZero values. Then check the
6777 /// remaining input indices in case we now have a unary shuffle and adjust the
6778 /// inputs accordingly.
6779 /// Returns true if the target shuffle mask was decoded.
resolveTargetShuffleInputs(SDValue Op,SmallVectorImpl<SDValue> & Inputs,SmallVectorImpl<int> & Mask,const SelectionDAG & DAG)6780 static bool resolveTargetShuffleInputs(SDValue Op,
6781                                        SmallVectorImpl<SDValue> &Inputs,
6782                                        SmallVectorImpl<int> &Mask,
6783                                        const SelectionDAG &DAG) {
6784   if (!setTargetShuffleZeroElements(Op, Mask, Inputs))
6785     if (!getFauxShuffleMask(Op, Mask, Inputs, DAG))
6786       return false;
6787 
6788   resolveTargetShuffleInputsAndMask(Inputs, Mask);
6789   return true;
6790 }
6791 
6792 /// Returns the scalar element that will make up the ith
6793 /// element of the result of the vector shuffle.
getShuffleScalarElt(SDNode * N,unsigned Index,SelectionDAG & DAG,unsigned Depth)6794 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
6795                                    unsigned Depth) {
6796   if (Depth == 6)
6797     return SDValue();  // Limit search depth.
6798 
6799   SDValue V = SDValue(N, 0);
6800   EVT VT = V.getValueType();
6801   unsigned Opcode = V.getOpcode();
6802 
6803   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
6804   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
6805     int Elt = SV->getMaskElt(Index);
6806 
6807     if (Elt < 0)
6808       return DAG.getUNDEF(VT.getVectorElementType());
6809 
6810     unsigned NumElems = VT.getVectorNumElements();
6811     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
6812                                          : SV->getOperand(1);
6813     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
6814   }
6815 
6816   // Recurse into target specific vector shuffles to find scalars.
6817   if (isTargetShuffle(Opcode)) {
6818     MVT ShufVT = V.getSimpleValueType();
6819     MVT ShufSVT = ShufVT.getVectorElementType();
6820     int NumElems = (int)ShufVT.getVectorNumElements();
6821     SmallVector<int, 16> ShuffleMask;
6822     SmallVector<SDValue, 16> ShuffleOps;
6823     bool IsUnary;
6824 
6825     if (!getTargetShuffleMask(N, ShufVT, true, ShuffleOps, ShuffleMask, IsUnary))
6826       return SDValue();
6827 
6828     int Elt = ShuffleMask[Index];
6829     if (Elt == SM_SentinelZero)
6830       return ShufSVT.isInteger() ? DAG.getConstant(0, SDLoc(N), ShufSVT)
6831                                  : DAG.getConstantFP(+0.0, SDLoc(N), ShufSVT);
6832     if (Elt == SM_SentinelUndef)
6833       return DAG.getUNDEF(ShufSVT);
6834 
6835     assert(0 <= Elt && Elt < (2*NumElems) && "Shuffle index out of range");
6836     SDValue NewV = (Elt < NumElems) ? ShuffleOps[0] : ShuffleOps[1];
6837     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
6838                                Depth+1);
6839   }
6840 
6841   // Actual nodes that may contain scalar elements
6842   if (Opcode == ISD::BITCAST) {
6843     V = V.getOperand(0);
6844     EVT SrcVT = V.getValueType();
6845     unsigned NumElems = VT.getVectorNumElements();
6846 
6847     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
6848       return SDValue();
6849   }
6850 
6851   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6852     return (Index == 0) ? V.getOperand(0)
6853                         : DAG.getUNDEF(VT.getVectorElementType());
6854 
6855   if (V.getOpcode() == ISD::BUILD_VECTOR)
6856     return V.getOperand(Index);
6857 
6858   return SDValue();
6859 }
6860 
6861 // Use PINSRB/PINSRW/PINSRD to create a build vector.
LowerBuildVectorAsInsert(SDValue Op,unsigned NonZeros,unsigned NumNonZero,unsigned NumZero,SelectionDAG & DAG,const X86Subtarget & Subtarget)6862 static SDValue LowerBuildVectorAsInsert(SDValue Op, unsigned NonZeros,
6863                                         unsigned NumNonZero, unsigned NumZero,
6864                                         SelectionDAG &DAG,
6865                                         const X86Subtarget &Subtarget) {
6866   MVT VT = Op.getSimpleValueType();
6867   unsigned NumElts = VT.getVectorNumElements();
6868   assert(((VT == MVT::v8i16 && Subtarget.hasSSE2()) ||
6869           ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) &&
6870          "Illegal vector insertion");
6871 
6872   SDLoc dl(Op);
6873   SDValue V;
6874   bool First = true;
6875 
6876   for (unsigned i = 0; i < NumElts; ++i) {
6877     bool IsNonZero = (NonZeros & (1 << i)) != 0;
6878     if (!IsNonZero)
6879       continue;
6880 
6881     // If the build vector contains zeros or our first insertion is not the
6882     // first index then insert into zero vector to break any register
6883     // dependency else use SCALAR_TO_VECTOR/VZEXT_MOVL.
6884     if (First) {
6885       First = false;
6886       if (NumZero || 0 != i)
6887         V = getZeroVector(VT, Subtarget, DAG, dl);
6888       else {
6889         assert(0 == i && "Expected insertion into zero-index");
6890         V = DAG.getAnyExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
6891         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, V);
6892         V = DAG.getNode(X86ISD::VZEXT_MOVL, dl, MVT::v4i32, V);
6893         V = DAG.getBitcast(VT, V);
6894         continue;
6895       }
6896     }
6897     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V, Op.getOperand(i),
6898                     DAG.getIntPtrConstant(i, dl));
6899   }
6900 
6901   return V;
6902 }
6903 
6904 /// Custom lower build_vector of v16i8.
LowerBuildVectorv16i8(SDValue Op,unsigned NonZeros,unsigned NumNonZero,unsigned NumZero,SelectionDAG & DAG,const X86Subtarget & Subtarget)6905 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
6906                                      unsigned NumNonZero, unsigned NumZero,
6907                                      SelectionDAG &DAG,
6908                                      const X86Subtarget &Subtarget) {
6909   if (NumNonZero > 8 && !Subtarget.hasSSE41())
6910     return SDValue();
6911 
6912   // SSE4.1 - use PINSRB to insert each byte directly.
6913   if (Subtarget.hasSSE41())
6914     return LowerBuildVectorAsInsert(Op, NonZeros, NumNonZero, NumZero, DAG,
6915                                     Subtarget);
6916 
6917   SDLoc dl(Op);
6918   SDValue V;
6919   bool First = true;
6920 
6921   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
6922   for (unsigned i = 0; i < 16; ++i) {
6923     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
6924     if (ThisIsNonZero && First) {
6925       if (NumZero)
6926         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
6927       else
6928         V = DAG.getUNDEF(MVT::v8i16);
6929       First = false;
6930     }
6931 
6932     if ((i & 1) != 0) {
6933       // FIXME: Investigate extending to i32 instead of just i16.
6934       // FIXME: Investigate combining the first 4 bytes as a i32 instead.
6935       SDValue ThisElt, LastElt;
6936       bool LastIsNonZero = (NonZeros & (1 << (i - 1))) != 0;
6937       if (LastIsNonZero) {
6938         LastElt =
6939             DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i - 1));
6940       }
6941       if (ThisIsNonZero) {
6942         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
6943         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16, ThisElt,
6944                               DAG.getConstant(8, dl, MVT::i8));
6945         if (LastIsNonZero)
6946           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
6947       } else
6948         ThisElt = LastElt;
6949 
6950       if (ThisElt) {
6951         if (1 == i) {
6952           V = NumZero ? DAG.getZExtOrTrunc(ThisElt, dl, MVT::i32)
6953                       : DAG.getAnyExtOrTrunc(ThisElt, dl, MVT::i32);
6954           V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, V);
6955           V = DAG.getNode(X86ISD::VZEXT_MOVL, dl, MVT::v4i32, V);
6956           V = DAG.getBitcast(MVT::v8i16, V);
6957         } else {
6958           V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
6959                           DAG.getIntPtrConstant(i / 2, dl));
6960         }
6961       }
6962     }
6963   }
6964 
6965   return DAG.getBitcast(MVT::v16i8, V);
6966 }
6967 
6968 /// Custom lower build_vector of v8i16.
LowerBuildVectorv8i16(SDValue Op,unsigned NonZeros,unsigned NumNonZero,unsigned NumZero,SelectionDAG & DAG,const X86Subtarget & Subtarget)6969 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
6970                                      unsigned NumNonZero, unsigned NumZero,
6971                                      SelectionDAG &DAG,
6972                                      const X86Subtarget &Subtarget) {
6973   if (NumNonZero > 4 && !Subtarget.hasSSE41())
6974     return SDValue();
6975 
6976   // Use PINSRW to insert each byte directly.
6977   return LowerBuildVectorAsInsert(Op, NonZeros, NumNonZero, NumZero, DAG,
6978                                   Subtarget);
6979 }
6980 
6981 /// Custom lower build_vector of v4i32 or v4f32.
LowerBuildVectorv4x32(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)6982 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
6983                                      const X86Subtarget &Subtarget) {
6984   // If this is a splat of a pair of elements, use MOVDDUP (unless the target
6985   // has XOP; in that case defer lowering to potentially use VPERMIL2PS).
6986   // Because we're creating a less complicated build vector here, we may enable
6987   // further folding of the MOVDDUP via shuffle transforms.
6988   if (Subtarget.hasSSE3() && !Subtarget.hasXOP() &&
6989       Op.getOperand(0) == Op.getOperand(2) &&
6990       Op.getOperand(1) == Op.getOperand(3) &&
6991       Op.getOperand(0) != Op.getOperand(1)) {
6992     SDLoc DL(Op);
6993     MVT VT = Op.getSimpleValueType();
6994     MVT EltVT = VT.getVectorElementType();
6995     // Create a new build vector with the first 2 elements followed by undef
6996     // padding, bitcast to v2f64, duplicate, and bitcast back.
6997     SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
6998                        DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
6999     SDValue NewBV = DAG.getBitcast(MVT::v2f64, DAG.getBuildVector(VT, DL, Ops));
7000     SDValue Dup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, NewBV);
7001     return DAG.getBitcast(VT, Dup);
7002   }
7003 
7004   // Find all zeroable elements.
7005   std::bitset<4> Zeroable;
7006   for (int i=0; i < 4; ++i) {
7007     SDValue Elt = Op->getOperand(i);
7008     Zeroable[i] = (Elt.isUndef() || X86::isZeroNode(Elt));
7009   }
7010   assert(Zeroable.size() - Zeroable.count() > 1 &&
7011          "We expect at least two non-zero elements!");
7012 
7013   // We only know how to deal with build_vector nodes where elements are either
7014   // zeroable or extract_vector_elt with constant index.
7015   SDValue FirstNonZero;
7016   unsigned FirstNonZeroIdx;
7017   for (unsigned i=0; i < 4; ++i) {
7018     if (Zeroable[i])
7019       continue;
7020     SDValue Elt = Op->getOperand(i);
7021     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7022         !isa<ConstantSDNode>(Elt.getOperand(1)))
7023       return SDValue();
7024     // Make sure that this node is extracting from a 128-bit vector.
7025     MVT VT = Elt.getOperand(0).getSimpleValueType();
7026     if (!VT.is128BitVector())
7027       return SDValue();
7028     if (!FirstNonZero.getNode()) {
7029       FirstNonZero = Elt;
7030       FirstNonZeroIdx = i;
7031     }
7032   }
7033 
7034   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
7035   SDValue V1 = FirstNonZero.getOperand(0);
7036   MVT VT = V1.getSimpleValueType();
7037 
7038   // See if this build_vector can be lowered as a blend with zero.
7039   SDValue Elt;
7040   unsigned EltMaskIdx, EltIdx;
7041   int Mask[4];
7042   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
7043     if (Zeroable[EltIdx]) {
7044       // The zero vector will be on the right hand side.
7045       Mask[EltIdx] = EltIdx+4;
7046       continue;
7047     }
7048 
7049     Elt = Op->getOperand(EltIdx);
7050     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
7051     EltMaskIdx = Elt.getConstantOperandVal(1);
7052     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
7053       break;
7054     Mask[EltIdx] = EltIdx;
7055   }
7056 
7057   if (EltIdx == 4) {
7058     // Let the shuffle legalizer deal with blend operations.
7059     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
7060     if (V1.getSimpleValueType() != VT)
7061       V1 = DAG.getBitcast(VT, V1);
7062     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, Mask);
7063   }
7064 
7065   // See if we can lower this build_vector to a INSERTPS.
7066   if (!Subtarget.hasSSE41())
7067     return SDValue();
7068 
7069   SDValue V2 = Elt.getOperand(0);
7070   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
7071     V1 = SDValue();
7072 
7073   bool CanFold = true;
7074   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
7075     if (Zeroable[i])
7076       continue;
7077 
7078     SDValue Current = Op->getOperand(i);
7079     SDValue SrcVector = Current->getOperand(0);
7080     if (!V1.getNode())
7081       V1 = SrcVector;
7082     CanFold = (SrcVector == V1) && (Current.getConstantOperandVal(1) == i);
7083   }
7084 
7085   if (!CanFold)
7086     return SDValue();
7087 
7088   assert(V1.getNode() && "Expected at least two non-zero elements!");
7089   if (V1.getSimpleValueType() != MVT::v4f32)
7090     V1 = DAG.getBitcast(MVT::v4f32, V1);
7091   if (V2.getSimpleValueType() != MVT::v4f32)
7092     V2 = DAG.getBitcast(MVT::v4f32, V2);
7093 
7094   // Ok, we can emit an INSERTPS instruction.
7095   unsigned ZMask = Zeroable.to_ulong();
7096 
7097   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
7098   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7099   SDLoc DL(Op);
7100   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7101                                DAG.getIntPtrConstant(InsertPSMask, DL));
7102   return DAG.getBitcast(VT, Result);
7103 }
7104 
7105 /// Return a vector logical shift node.
getVShift(bool isLeft,EVT VT,SDValue SrcOp,unsigned NumBits,SelectionDAG & DAG,const TargetLowering & TLI,const SDLoc & dl)7106 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, unsigned NumBits,
7107                          SelectionDAG &DAG, const TargetLowering &TLI,
7108                          const SDLoc &dl) {
7109   assert(VT.is128BitVector() && "Unknown type for VShift");
7110   MVT ShVT = MVT::v16i8;
7111   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
7112   SrcOp = DAG.getBitcast(ShVT, SrcOp);
7113   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
7114   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, MVT::i8);
7115   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
7116 }
7117 
LowerAsSplatVectorLoad(SDValue SrcOp,MVT VT,const SDLoc & dl,SelectionDAG & DAG)7118 static SDValue LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, const SDLoc &dl,
7119                                       SelectionDAG &DAG) {
7120 
7121   // Check if the scalar load can be widened into a vector load. And if
7122   // the address is "base + cst" see if the cst can be "absorbed" into
7123   // the shuffle mask.
7124   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
7125     SDValue Ptr = LD->getBasePtr();
7126     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
7127       return SDValue();
7128     EVT PVT = LD->getValueType(0);
7129     if (PVT != MVT::i32 && PVT != MVT::f32)
7130       return SDValue();
7131 
7132     int FI = -1;
7133     int64_t Offset = 0;
7134     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
7135       FI = FINode->getIndex();
7136       Offset = 0;
7137     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
7138                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
7139       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7140       Offset = Ptr.getConstantOperandVal(1);
7141       Ptr = Ptr.getOperand(0);
7142     } else {
7143       return SDValue();
7144     }
7145 
7146     // FIXME: 256-bit vector instructions don't require a strict alignment,
7147     // improve this code to support it better.
7148     unsigned RequiredAlign = VT.getSizeInBits()/8;
7149     SDValue Chain = LD->getChain();
7150     // Make sure the stack object alignment is at least 16 or 32.
7151     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7152     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
7153       if (MFI.isFixedObjectIndex(FI)) {
7154         // Can't change the alignment. FIXME: It's possible to compute
7155         // the exact stack offset and reference FI + adjust offset instead.
7156         // If someone *really* cares about this. That's the way to implement it.
7157         return SDValue();
7158       } else {
7159         MFI.setObjectAlignment(FI, RequiredAlign);
7160       }
7161     }
7162 
7163     // (Offset % 16 or 32) must be multiple of 4. Then address is then
7164     // Ptr + (Offset & ~15).
7165     if (Offset < 0)
7166       return SDValue();
7167     if ((Offset % RequiredAlign) & 3)
7168       return SDValue();
7169     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
7170     if (StartOffset) {
7171       SDLoc DL(Ptr);
7172       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
7173                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
7174     }
7175 
7176     int EltNo = (Offset - StartOffset) >> 2;
7177     unsigned NumElems = VT.getVectorNumElements();
7178 
7179     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
7180     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
7181                              LD->getPointerInfo().getWithOffset(StartOffset));
7182 
7183     SmallVector<int, 8> Mask(NumElems, EltNo);
7184 
7185     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), Mask);
7186   }
7187 
7188   return SDValue();
7189 }
7190 
7191 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
7192 /// elements can be replaced by a single large load which has the same value as
7193 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
7194 ///
7195 /// Example: <load i32 *a, load i32 *a+4, zero, undef> -> zextload a
EltsFromConsecutiveLoads(EVT VT,ArrayRef<SDValue> Elts,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget,bool isAfterLegalize)7196 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
7197                                         const SDLoc &DL, SelectionDAG &DAG,
7198                                         const X86Subtarget &Subtarget,
7199                                         bool isAfterLegalize) {
7200   unsigned NumElems = Elts.size();
7201 
7202   int LastLoadedElt = -1;
7203   SmallBitVector LoadMask(NumElems, false);
7204   SmallBitVector ZeroMask(NumElems, false);
7205   SmallBitVector UndefMask(NumElems, false);
7206 
7207   // For each element in the initializer, see if we've found a load, zero or an
7208   // undef.
7209   for (unsigned i = 0; i < NumElems; ++i) {
7210     SDValue Elt = peekThroughBitcasts(Elts[i]);
7211     if (!Elt.getNode())
7212       return SDValue();
7213 
7214     if (Elt.isUndef())
7215       UndefMask[i] = true;
7216     else if (X86::isZeroNode(Elt) || ISD::isBuildVectorAllZeros(Elt.getNode()))
7217       ZeroMask[i] = true;
7218     else if (ISD::isNON_EXTLoad(Elt.getNode())) {
7219       LoadMask[i] = true;
7220       LastLoadedElt = i;
7221       // Each loaded element must be the correct fractional portion of the
7222       // requested vector load.
7223       if ((NumElems * Elt.getValueSizeInBits()) != VT.getSizeInBits())
7224         return SDValue();
7225     } else
7226       return SDValue();
7227   }
7228   assert((ZeroMask | UndefMask | LoadMask).count() == NumElems &&
7229          "Incomplete element masks");
7230 
7231   // Handle Special Cases - all undef or undef/zero.
7232   if (UndefMask.count() == NumElems)
7233     return DAG.getUNDEF(VT);
7234 
7235   // FIXME: Should we return this as a BUILD_VECTOR instead?
7236   if ((ZeroMask | UndefMask).count() == NumElems)
7237     return VT.isInteger() ? DAG.getConstant(0, DL, VT)
7238                           : DAG.getConstantFP(0.0, DL, VT);
7239 
7240   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7241   int FirstLoadedElt = LoadMask.find_first();
7242   SDValue EltBase = peekThroughBitcasts(Elts[FirstLoadedElt]);
7243   LoadSDNode *LDBase = cast<LoadSDNode>(EltBase);
7244   EVT LDBaseVT = EltBase.getValueType();
7245 
7246   // Consecutive loads can contain UNDEFS but not ZERO elements.
7247   // Consecutive loads with UNDEFs and ZEROs elements require a
7248   // an additional shuffle stage to clear the ZERO elements.
7249   bool IsConsecutiveLoad = true;
7250   bool IsConsecutiveLoadWithZeros = true;
7251   for (int i = FirstLoadedElt + 1; i <= LastLoadedElt; ++i) {
7252     if (LoadMask[i]) {
7253       SDValue Elt = peekThroughBitcasts(Elts[i]);
7254       LoadSDNode *LD = cast<LoadSDNode>(Elt);
7255       if (!DAG.areNonVolatileConsecutiveLoads(
7256               LD, LDBase, Elt.getValueType().getStoreSizeInBits() / 8,
7257               i - FirstLoadedElt)) {
7258         IsConsecutiveLoad = false;
7259         IsConsecutiveLoadWithZeros = false;
7260         break;
7261       }
7262     } else if (ZeroMask[i]) {
7263       IsConsecutiveLoad = false;
7264     }
7265   }
7266 
7267   SmallVector<LoadSDNode *, 8> Loads;
7268   for (int i = FirstLoadedElt; i <= LastLoadedElt; ++i)
7269     if (LoadMask[i])
7270       Loads.push_back(cast<LoadSDNode>(peekThroughBitcasts(Elts[i])));
7271 
7272   auto CreateLoad = [&DAG, &DL, &Loads](EVT VT, LoadSDNode *LDBase) {
7273     auto MMOFlags = LDBase->getMemOperand()->getFlags();
7274     assert(!(MMOFlags & MachineMemOperand::MOVolatile) &&
7275            "Cannot merge volatile loads.");
7276     SDValue NewLd =
7277         DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
7278                     LDBase->getPointerInfo(), LDBase->getAlignment(), MMOFlags);
7279     for (auto *LD : Loads)
7280       DAG.makeEquivalentMemoryOrdering(LD, NewLd);
7281     return NewLd;
7282   };
7283 
7284   // LOAD - all consecutive load/undefs (must start/end with a load).
7285   // If we have found an entire vector of loads and undefs, then return a large
7286   // load of the entire vector width starting at the base pointer.
7287   // If the vector contains zeros, then attempt to shuffle those elements.
7288   if (FirstLoadedElt == 0 && LastLoadedElt == (int)(NumElems - 1) &&
7289       (IsConsecutiveLoad || IsConsecutiveLoadWithZeros)) {
7290     assert(LDBase && "Did not find base load for merging consecutive loads");
7291     EVT EltVT = LDBase->getValueType(0);
7292     // Ensure that the input vector size for the merged loads matches the
7293     // cumulative size of the input elements.
7294     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
7295       return SDValue();
7296 
7297     if (isAfterLegalize && !TLI.isOperationLegal(ISD::LOAD, VT))
7298       return SDValue();
7299 
7300     // Don't create 256-bit non-temporal aligned loads without AVX2 as these
7301     // will lower to regular temporal loads and use the cache.
7302     if (LDBase->isNonTemporal() && LDBase->getAlignment() >= 32 &&
7303         VT.is256BitVector() && !Subtarget.hasInt256())
7304       return SDValue();
7305 
7306     if (IsConsecutiveLoad)
7307       return CreateLoad(VT, LDBase);
7308 
7309     // IsConsecutiveLoadWithZeros - we need to create a shuffle of the loaded
7310     // vector and a zero vector to clear out the zero elements.
7311     if (!isAfterLegalize && NumElems == VT.getVectorNumElements()) {
7312       SmallVector<int, 4> ClearMask(NumElems, -1);
7313       for (unsigned i = 0; i < NumElems; ++i) {
7314         if (ZeroMask[i])
7315           ClearMask[i] = i + NumElems;
7316         else if (LoadMask[i])
7317           ClearMask[i] = i;
7318       }
7319       SDValue V = CreateLoad(VT, LDBase);
7320       SDValue Z = VT.isInteger() ? DAG.getConstant(0, DL, VT)
7321                                  : DAG.getConstantFP(0.0, DL, VT);
7322       return DAG.getVectorShuffle(VT, DL, V, Z, ClearMask);
7323     }
7324   }
7325 
7326   int LoadSize =
7327       (1 + LastLoadedElt - FirstLoadedElt) * LDBaseVT.getStoreSizeInBits();
7328 
7329   // VZEXT_LOAD - consecutive 32/64-bit load/undefs followed by zeros/undefs.
7330   if (IsConsecutiveLoad && FirstLoadedElt == 0 &&
7331       (LoadSize == 32 || LoadSize == 64) &&
7332       ((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))) {
7333     MVT VecSVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(LoadSize)
7334                                       : MVT::getIntegerVT(LoadSize);
7335     MVT VecVT = MVT::getVectorVT(VecSVT, VT.getSizeInBits() / LoadSize);
7336     if (TLI.isTypeLegal(VecVT)) {
7337       SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
7338       SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
7339       SDValue ResNode =
7340           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, VecSVT,
7341                                   LDBase->getPointerInfo(),
7342                                   LDBase->getAlignment(),
7343                                   MachineMemOperand::MOLoad);
7344       for (auto *LD : Loads)
7345         DAG.makeEquivalentMemoryOrdering(LD, ResNode);
7346       return DAG.getBitcast(VT, ResNode);
7347     }
7348   }
7349 
7350   return SDValue();
7351 }
7352 
getConstantVector(MVT VT,const APInt & SplatValue,unsigned SplatBitSize,LLVMContext & C)7353 static Constant *getConstantVector(MVT VT, const APInt &SplatValue,
7354                                    unsigned SplatBitSize, LLVMContext &C) {
7355   unsigned ScalarSize = VT.getScalarSizeInBits();
7356   unsigned NumElm = SplatBitSize / ScalarSize;
7357 
7358   SmallVector<Constant *, 32> ConstantVec;
7359   for (unsigned i = 0; i < NumElm; i++) {
7360     APInt Val = SplatValue.extractBits(ScalarSize, ScalarSize * i);
7361     Constant *Const;
7362     if (VT.isFloatingPoint()) {
7363       if (ScalarSize == 32) {
7364         Const = ConstantFP::get(C, APFloat(APFloat::IEEEsingle(), Val));
7365       } else {
7366         assert(ScalarSize == 64 && "Unsupported floating point scalar size");
7367         Const = ConstantFP::get(C, APFloat(APFloat::IEEEdouble(), Val));
7368       }
7369     } else
7370       Const = Constant::getIntegerValue(Type::getIntNTy(C, ScalarSize), Val);
7371     ConstantVec.push_back(Const);
7372   }
7373   return ConstantVector::get(ArrayRef<Constant *>(ConstantVec));
7374 }
7375 
isUseOfShuffle(SDNode * N)7376 static bool isUseOfShuffle(SDNode *N) {
7377   for (auto *U : N->uses()) {
7378     if (isTargetShuffle(U->getOpcode()))
7379       return true;
7380     if (U->getOpcode() == ISD::BITCAST) // Ignore bitcasts
7381       return isUseOfShuffle(U);
7382   }
7383   return false;
7384 }
7385 
7386 // Check if the current node of build vector is a zero extended vector.
7387 // // If so, return the value extended.
7388 // // For example: (0,0,0,a,0,0,0,a,0,0,0,a,0,0,0,a) returns a.
7389 // // NumElt - return the number of zero extended identical values.
7390 // // EltType - return the type of the value include the zero extend.
isSplatZeroExtended(const BuildVectorSDNode * Op,unsigned & NumElt,MVT & EltType)7391 static SDValue isSplatZeroExtended(const BuildVectorSDNode *Op,
7392                                    unsigned &NumElt, MVT &EltType) {
7393   SDValue ExtValue = Op->getOperand(0);
7394   unsigned NumElts = Op->getNumOperands();
7395   unsigned Delta = NumElts;
7396 
7397   for (unsigned i = 1; i < NumElts; i++) {
7398     if (Op->getOperand(i) == ExtValue) {
7399       Delta = i;
7400       break;
7401     }
7402     if (!(Op->getOperand(i).isUndef() || isNullConstant(Op->getOperand(i))))
7403       return SDValue();
7404   }
7405   if (!isPowerOf2_32(Delta) || Delta == 1)
7406     return SDValue();
7407 
7408   for (unsigned i = Delta; i < NumElts; i++) {
7409     if (i % Delta == 0) {
7410       if (Op->getOperand(i) != ExtValue)
7411         return SDValue();
7412     } else if (!(isNullConstant(Op->getOperand(i)) ||
7413                  Op->getOperand(i).isUndef()))
7414       return SDValue();
7415   }
7416   unsigned EltSize = Op->getSimpleValueType(0).getScalarSizeInBits();
7417   unsigned ExtVTSize = EltSize * Delta;
7418   EltType = MVT::getIntegerVT(ExtVTSize);
7419   NumElt = NumElts / Delta;
7420   return ExtValue;
7421 }
7422 
7423 /// Attempt to use the vbroadcast instruction to generate a splat value
7424 /// from a splat BUILD_VECTOR which uses:
7425 ///  a. A single scalar load, or a constant.
7426 ///  b. Repeated pattern of constants (e.g. <0,1,0,1> or <0,1,2,3,0,1,2,3>).
7427 ///
7428 /// The VBROADCAST node is returned when a pattern is found,
7429 /// or SDValue() otherwise.
lowerBuildVectorAsBroadcast(BuildVectorSDNode * BVOp,const X86Subtarget & Subtarget,SelectionDAG & DAG)7430 static SDValue lowerBuildVectorAsBroadcast(BuildVectorSDNode *BVOp,
7431                                            const X86Subtarget &Subtarget,
7432                                            SelectionDAG &DAG) {
7433   // VBROADCAST requires AVX.
7434   // TODO: Splats could be generated for non-AVX CPUs using SSE
7435   // instructions, but there's less potential gain for only 128-bit vectors.
7436   if (!Subtarget.hasAVX())
7437     return SDValue();
7438 
7439   MVT VT = BVOp->getSimpleValueType(0);
7440   SDLoc dl(BVOp);
7441 
7442   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
7443          "Unsupported vector type for broadcast.");
7444 
7445   BitVector UndefElements;
7446   SDValue Ld = BVOp->getSplatValue(&UndefElements);
7447 
7448   // Attempt to use VBROADCASTM
7449   // From this paterrn:
7450   // a. t0 = (zext_i64 (bitcast_i8 v2i1 X))
7451   // b. t1 = (build_vector t0 t0)
7452   //
7453   // Create (VBROADCASTM v2i1 X)
7454   if (Subtarget.hasCDI() && (VT.is512BitVector() || Subtarget.hasVLX())) {
7455     MVT EltType = VT.getScalarType();
7456     unsigned NumElts = VT.getVectorNumElements();
7457     SDValue BOperand;
7458     SDValue ZeroExtended = isSplatZeroExtended(BVOp, NumElts, EltType);
7459     if ((ZeroExtended && ZeroExtended.getOpcode() == ISD::BITCAST) ||
7460         (Ld && Ld.getOpcode() == ISD::ZERO_EXTEND &&
7461          Ld.getOperand(0).getOpcode() == ISD::BITCAST)) {
7462       if (ZeroExtended)
7463         BOperand = ZeroExtended.getOperand(0);
7464       else
7465         BOperand = Ld.getOperand(0).getOperand(0);
7466       MVT MaskVT = BOperand.getSimpleValueType();
7467       if ((EltType == MVT::i64 && MaskVT == MVT::v8i1) || // for broadcastmb2q
7468           (EltType == MVT::i32 && MaskVT == MVT::v16i1)) { // for broadcastmw2d
7469         SDValue Brdcst =
7470             DAG.getNode(X86ISD::VBROADCASTM, dl,
7471                         MVT::getVectorVT(EltType, NumElts), BOperand);
7472         return DAG.getBitcast(VT, Brdcst);
7473       }
7474     }
7475   }
7476 
7477   unsigned NumElts = VT.getVectorNumElements();
7478   unsigned NumUndefElts = UndefElements.count();
7479   if (!Ld || (NumElts - NumUndefElts) <= 1) {
7480     APInt SplatValue, Undef;
7481     unsigned SplatBitSize;
7482     bool HasUndef;
7483     // Check if this is a repeated constant pattern suitable for broadcasting.
7484     if (BVOp->isConstantSplat(SplatValue, Undef, SplatBitSize, HasUndef) &&
7485         SplatBitSize > VT.getScalarSizeInBits() &&
7486         SplatBitSize < VT.getSizeInBits()) {
7487       // Avoid replacing with broadcast when it's a use of a shuffle
7488       // instruction to preserve the present custom lowering of shuffles.
7489       if (isUseOfShuffle(BVOp) || BVOp->hasOneUse())
7490         return SDValue();
7491       // replace BUILD_VECTOR with broadcast of the repeated constants.
7492       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7493       LLVMContext *Ctx = DAG.getContext();
7494       MVT PVT = TLI.getPointerTy(DAG.getDataLayout());
7495       if (Subtarget.hasAVX()) {
7496         if (SplatBitSize <= 64 && Subtarget.hasAVX2() &&
7497             !(SplatBitSize == 64 && Subtarget.is32Bit())) {
7498           // Splatted value can fit in one INTEGER constant in constant pool.
7499           // Load the constant and broadcast it.
7500           MVT CVT = MVT::getIntegerVT(SplatBitSize);
7501           Type *ScalarTy = Type::getIntNTy(*Ctx, SplatBitSize);
7502           Constant *C = Constant::getIntegerValue(ScalarTy, SplatValue);
7503           SDValue CP = DAG.getConstantPool(C, PVT);
7504           unsigned Repeat = VT.getSizeInBits() / SplatBitSize;
7505 
7506           unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
7507           Ld = DAG.getLoad(
7508               CVT, dl, DAG.getEntryNode(), CP,
7509               MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
7510               Alignment);
7511           SDValue Brdcst = DAG.getNode(X86ISD::VBROADCAST, dl,
7512                                        MVT::getVectorVT(CVT, Repeat), Ld);
7513           return DAG.getBitcast(VT, Brdcst);
7514         } else if (SplatBitSize == 32 || SplatBitSize == 64) {
7515           // Splatted value can fit in one FLOAT constant in constant pool.
7516           // Load the constant and broadcast it.
7517           // AVX have support for 32 and 64 bit broadcast for floats only.
7518           // No 64bit integer in 32bit subtarget.
7519           MVT CVT = MVT::getFloatingPointVT(SplatBitSize);
7520           // Lower the splat via APFloat directly, to avoid any conversion.
7521           Constant *C =
7522               SplatBitSize == 32
7523                   ? ConstantFP::get(*Ctx,
7524                                     APFloat(APFloat::IEEEsingle(), SplatValue))
7525                   : ConstantFP::get(*Ctx,
7526                                     APFloat(APFloat::IEEEdouble(), SplatValue));
7527           SDValue CP = DAG.getConstantPool(C, PVT);
7528           unsigned Repeat = VT.getSizeInBits() / SplatBitSize;
7529 
7530           unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
7531           Ld = DAG.getLoad(
7532               CVT, dl, DAG.getEntryNode(), CP,
7533               MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
7534               Alignment);
7535           SDValue Brdcst = DAG.getNode(X86ISD::VBROADCAST, dl,
7536                                        MVT::getVectorVT(CVT, Repeat), Ld);
7537           return DAG.getBitcast(VT, Brdcst);
7538         } else if (SplatBitSize > 64) {
7539           // Load the vector of constants and broadcast it.
7540           MVT CVT = VT.getScalarType();
7541           Constant *VecC = getConstantVector(VT, SplatValue, SplatBitSize,
7542                                              *Ctx);
7543           SDValue VCP = DAG.getConstantPool(VecC, PVT);
7544           unsigned NumElm = SplatBitSize / VT.getScalarSizeInBits();
7545           unsigned Alignment = cast<ConstantPoolSDNode>(VCP)->getAlignment();
7546           Ld = DAG.getLoad(
7547               MVT::getVectorVT(CVT, NumElm), dl, DAG.getEntryNode(), VCP,
7548               MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
7549               Alignment);
7550           SDValue Brdcst = DAG.getNode(X86ISD::SUBV_BROADCAST, dl, VT, Ld);
7551           return DAG.getBitcast(VT, Brdcst);
7552         }
7553       }
7554     }
7555 
7556     // If we are moving a scalar into a vector (Ld must be set and all elements
7557     // but 1 are undef) and that operation is not obviously supported by
7558     // vmovd/vmovq/vmovss/vmovsd, then keep trying to form a broadcast.
7559     // That's better than general shuffling and may eliminate a load to GPR and
7560     // move from scalar to vector register.
7561     if (!Ld || NumElts - NumUndefElts != 1)
7562       return SDValue();
7563     unsigned ScalarSize = Ld.getValueSizeInBits();
7564     if (!(UndefElements[0] || (ScalarSize != 32 && ScalarSize != 64)))
7565       return SDValue();
7566   }
7567 
7568   bool ConstSplatVal =
7569       (Ld.getOpcode() == ISD::Constant || Ld.getOpcode() == ISD::ConstantFP);
7570 
7571   // Make sure that all of the users of a non-constant load are from the
7572   // BUILD_VECTOR node.
7573   if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
7574     return SDValue();
7575 
7576   unsigned ScalarSize = Ld.getValueSizeInBits();
7577   bool IsGE256 = (VT.getSizeInBits() >= 256);
7578 
7579   // When optimizing for size, generate up to 5 extra bytes for a broadcast
7580   // instruction to save 8 or more bytes of constant pool data.
7581   // TODO: If multiple splats are generated to load the same constant,
7582   // it may be detrimental to overall size. There needs to be a way to detect
7583   // that condition to know if this is truly a size win.
7584   bool OptForSize = DAG.getMachineFunction().getFunction().optForSize();
7585 
7586   // Handle broadcasting a single constant scalar from the constant pool
7587   // into a vector.
7588   // On Sandybridge (no AVX2), it is still better to load a constant vector
7589   // from the constant pool and not to broadcast it from a scalar.
7590   // But override that restriction when optimizing for size.
7591   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
7592   if (ConstSplatVal && (Subtarget.hasAVX2() || OptForSize)) {
7593     EVT CVT = Ld.getValueType();
7594     assert(!CVT.isVector() && "Must not broadcast a vector type");
7595 
7596     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
7597     // For size optimization, also splat v2f64 and v2i64, and for size opt
7598     // with AVX2, also splat i8 and i16.
7599     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
7600     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
7601         (OptForSize && (ScalarSize == 64 || Subtarget.hasAVX2()))) {
7602       const Constant *C = nullptr;
7603       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
7604         C = CI->getConstantIntValue();
7605       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
7606         C = CF->getConstantFPValue();
7607 
7608       assert(C && "Invalid constant type");
7609 
7610       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7611       SDValue CP =
7612           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
7613       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
7614       Ld = DAG.getLoad(
7615           CVT, dl, DAG.getEntryNode(), CP,
7616           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
7617           Alignment);
7618 
7619       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
7620     }
7621   }
7622 
7623   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
7624 
7625   // Handle AVX2 in-register broadcasts.
7626   if (!IsLoad && Subtarget.hasInt256() &&
7627       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
7628     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
7629 
7630   // The scalar source must be a normal load.
7631   if (!IsLoad)
7632     return SDValue();
7633 
7634   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
7635       (Subtarget.hasVLX() && ScalarSize == 64))
7636     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
7637 
7638   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
7639   // double since there is no vbroadcastsd xmm
7640   if (Subtarget.hasInt256() && Ld.getValueType().isInteger()) {
7641     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
7642       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
7643   }
7644 
7645   // Unsupported broadcast.
7646   return SDValue();
7647 }
7648 
7649 /// For an EXTRACT_VECTOR_ELT with a constant index return the real
7650 /// underlying vector and index.
7651 ///
7652 /// Modifies \p ExtractedFromVec to the real vector and returns the real
7653 /// index.
getUnderlyingExtractedFromVec(SDValue & ExtractedFromVec,SDValue ExtIdx)7654 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
7655                                          SDValue ExtIdx) {
7656   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
7657   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
7658     return Idx;
7659 
7660   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
7661   // lowered this:
7662   //   (extract_vector_elt (v8f32 %1), Constant<6>)
7663   // to:
7664   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
7665   //                           (extract_subvector (v8f32 %0), Constant<4>),
7666   //                           undef)
7667   //                       Constant<0>)
7668   // In this case the vector is the extract_subvector expression and the index
7669   // is 2, as specified by the shuffle.
7670   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
7671   SDValue ShuffleVec = SVOp->getOperand(0);
7672   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
7673   assert(ShuffleVecVT.getVectorElementType() ==
7674          ExtractedFromVec.getSimpleValueType().getVectorElementType());
7675 
7676   int ShuffleIdx = SVOp->getMaskElt(Idx);
7677   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
7678     ExtractedFromVec = ShuffleVec;
7679     return ShuffleIdx;
7680   }
7681   return Idx;
7682 }
7683 
buildFromShuffleMostly(SDValue Op,SelectionDAG & DAG)7684 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
7685   MVT VT = Op.getSimpleValueType();
7686 
7687   // Skip if insert_vec_elt is not supported.
7688   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7689   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
7690     return SDValue();
7691 
7692   SDLoc DL(Op);
7693   unsigned NumElems = Op.getNumOperands();
7694 
7695   SDValue VecIn1;
7696   SDValue VecIn2;
7697   SmallVector<unsigned, 4> InsertIndices;
7698   SmallVector<int, 8> Mask(NumElems, -1);
7699 
7700   for (unsigned i = 0; i != NumElems; ++i) {
7701     unsigned Opc = Op.getOperand(i).getOpcode();
7702 
7703     if (Opc == ISD::UNDEF)
7704       continue;
7705 
7706     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
7707       // Quit if more than 1 elements need inserting.
7708       if (InsertIndices.size() > 1)
7709         return SDValue();
7710 
7711       InsertIndices.push_back(i);
7712       continue;
7713     }
7714 
7715     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
7716     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
7717 
7718     // Quit if non-constant index.
7719     if (!isa<ConstantSDNode>(ExtIdx))
7720       return SDValue();
7721     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
7722 
7723     // Quit if extracted from vector of different type.
7724     if (ExtractedFromVec.getValueType() != VT)
7725       return SDValue();
7726 
7727     if (!VecIn1.getNode())
7728       VecIn1 = ExtractedFromVec;
7729     else if (VecIn1 != ExtractedFromVec) {
7730       if (!VecIn2.getNode())
7731         VecIn2 = ExtractedFromVec;
7732       else if (VecIn2 != ExtractedFromVec)
7733         // Quit if more than 2 vectors to shuffle
7734         return SDValue();
7735     }
7736 
7737     if (ExtractedFromVec == VecIn1)
7738       Mask[i] = Idx;
7739     else if (ExtractedFromVec == VecIn2)
7740       Mask[i] = Idx + NumElems;
7741   }
7742 
7743   if (!VecIn1.getNode())
7744     return SDValue();
7745 
7746   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
7747   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, Mask);
7748 
7749   for (unsigned Idx : InsertIndices)
7750     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
7751                      DAG.getIntPtrConstant(Idx, DL));
7752 
7753   return NV;
7754 }
7755 
ConvertI1VectorToInteger(SDValue Op,SelectionDAG & DAG)7756 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
7757   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
7758          Op.getScalarValueSizeInBits() == 1 &&
7759          "Can not convert non-constant vector");
7760   uint64_t Immediate = 0;
7761   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
7762     SDValue In = Op.getOperand(idx);
7763     if (!In.isUndef())
7764       Immediate |= (cast<ConstantSDNode>(In)->getZExtValue() & 0x1) << idx;
7765   }
7766   SDLoc dl(Op);
7767   MVT VT = MVT::getIntegerVT(std::max((int)Op.getValueSizeInBits(), 8));
7768   return DAG.getConstant(Immediate, dl, VT);
7769 }
7770 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
LowerBUILD_VECTORvXi1(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)7771 static SDValue LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG,
7772                                      const X86Subtarget &Subtarget) {
7773 
7774   MVT VT = Op.getSimpleValueType();
7775   assert((VT.getVectorElementType() == MVT::i1) &&
7776          "Unexpected type in LowerBUILD_VECTORvXi1!");
7777 
7778   SDLoc dl(Op);
7779   if (ISD::isBuildVectorAllZeros(Op.getNode()))
7780     return Op;
7781 
7782   if (ISD::isBuildVectorAllOnes(Op.getNode()))
7783     return Op;
7784 
7785   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
7786     if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
7787       // Split the pieces.
7788       SDValue Lower =
7789           DAG.getBuildVector(MVT::v32i1, dl, Op.getNode()->ops().slice(0, 32));
7790       SDValue Upper =
7791           DAG.getBuildVector(MVT::v32i1, dl, Op.getNode()->ops().slice(32, 32));
7792       // We have to manually lower both halves so getNode doesn't try to
7793       // reassemble the build_vector.
7794       Lower = LowerBUILD_VECTORvXi1(Lower, DAG, Subtarget);
7795       Upper = LowerBUILD_VECTORvXi1(Upper, DAG, Subtarget);
7796       return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lower, Upper);
7797     }
7798     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
7799     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
7800       return DAG.getBitcast(VT, Imm);
7801     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
7802     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
7803                         DAG.getIntPtrConstant(0, dl));
7804   }
7805 
7806   // Vector has one or more non-const elements
7807   uint64_t Immediate = 0;
7808   SmallVector<unsigned, 16> NonConstIdx;
7809   bool IsSplat = true;
7810   bool HasConstElts = false;
7811   int SplatIdx = -1;
7812   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
7813     SDValue In = Op.getOperand(idx);
7814     if (In.isUndef())
7815       continue;
7816     if (!isa<ConstantSDNode>(In))
7817       NonConstIdx.push_back(idx);
7818     else {
7819       Immediate |= (cast<ConstantSDNode>(In)->getZExtValue() & 0x1) << idx;
7820       HasConstElts = true;
7821     }
7822     if (SplatIdx < 0)
7823       SplatIdx = idx;
7824     else if (In != Op.getOperand(SplatIdx))
7825       IsSplat = false;
7826   }
7827 
7828   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
7829   if (IsSplat)
7830     return DAG.getSelect(dl, VT, Op.getOperand(SplatIdx),
7831                          DAG.getConstant(1, dl, VT),
7832                          DAG.getConstant(0, dl, VT));
7833 
7834   // insert elements one by one
7835   SDValue DstVec;
7836   SDValue Imm;
7837   if (Immediate) {
7838     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
7839     Imm = DAG.getConstant(Immediate, dl, ImmVT);
7840   }
7841   else if (HasConstElts)
7842     Imm = DAG.getConstant(0, dl, VT);
7843   else
7844     Imm = DAG.getUNDEF(VT);
7845   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
7846     DstVec = DAG.getBitcast(VT, Imm);
7847   else {
7848     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
7849     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
7850                          DAG.getIntPtrConstant(0, dl));
7851   }
7852 
7853   for (unsigned i = 0, e = NonConstIdx.size(); i != e; ++i) {
7854     unsigned InsertIdx = NonConstIdx[i];
7855     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
7856                          Op.getOperand(InsertIdx),
7857                          DAG.getIntPtrConstant(InsertIdx, dl));
7858   }
7859   return DstVec;
7860 }
7861 
7862 /// This is a helper function of LowerToHorizontalOp().
7863 /// This function checks that the build_vector \p N in input implements a
7864 /// 128-bit partial horizontal operation on a 256-bit vector, but that operation
7865 /// may not match the layout of an x86 256-bit horizontal instruction.
7866 /// In other words, if this returns true, then some extraction/insertion will
7867 /// be required to produce a valid horizontal instruction.
7868 ///
7869 /// Parameter \p Opcode defines the kind of horizontal operation to match.
7870 /// For example, if \p Opcode is equal to ISD::ADD, then this function
7871 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
7872 /// is equal to ISD::SUB, then this function checks if this is a horizontal
7873 /// arithmetic sub.
7874 ///
7875 /// This function only analyzes elements of \p N whose indices are
7876 /// in range [BaseIdx, LastIdx).
7877 ///
7878 /// TODO: This function was originally used to match both real and fake partial
7879 /// horizontal operations, but the index-matching logic is incorrect for that.
7880 /// See the corrected implementation in isHopBuildVector(). Can we reduce this
7881 /// code because it is only used for partial h-op matching now?
isHorizontalBinOpPart(const BuildVectorSDNode * N,unsigned Opcode,SelectionDAG & DAG,unsigned BaseIdx,unsigned LastIdx,SDValue & V0,SDValue & V1)7882 static bool isHorizontalBinOpPart(const BuildVectorSDNode *N, unsigned Opcode,
7883                                   SelectionDAG &DAG,
7884                                   unsigned BaseIdx, unsigned LastIdx,
7885                                   SDValue &V0, SDValue &V1) {
7886   EVT VT = N->getValueType(0);
7887   assert(VT.is256BitVector() && "Only use for matching partial 256-bit h-ops");
7888   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
7889   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
7890          "Invalid Vector in input!");
7891 
7892   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
7893   bool CanFold = true;
7894   unsigned ExpectedVExtractIdx = BaseIdx;
7895   unsigned NumElts = LastIdx - BaseIdx;
7896   V0 = DAG.getUNDEF(VT);
7897   V1 = DAG.getUNDEF(VT);
7898 
7899   // Check if N implements a horizontal binop.
7900   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
7901     SDValue Op = N->getOperand(i + BaseIdx);
7902 
7903     // Skip UNDEFs.
7904     if (Op->isUndef()) {
7905       // Update the expected vector extract index.
7906       if (i * 2 == NumElts)
7907         ExpectedVExtractIdx = BaseIdx;
7908       ExpectedVExtractIdx += 2;
7909       continue;
7910     }
7911 
7912     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
7913 
7914     if (!CanFold)
7915       break;
7916 
7917     SDValue Op0 = Op.getOperand(0);
7918     SDValue Op1 = Op.getOperand(1);
7919 
7920     // Try to match the following pattern:
7921     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
7922     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7923         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7924         Op0.getOperand(0) == Op1.getOperand(0) &&
7925         isa<ConstantSDNode>(Op0.getOperand(1)) &&
7926         isa<ConstantSDNode>(Op1.getOperand(1)));
7927     if (!CanFold)
7928       break;
7929 
7930     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
7931     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
7932 
7933     if (i * 2 < NumElts) {
7934       if (V0.isUndef()) {
7935         V0 = Op0.getOperand(0);
7936         if (V0.getValueType() != VT)
7937           return false;
7938       }
7939     } else {
7940       if (V1.isUndef()) {
7941         V1 = Op0.getOperand(0);
7942         if (V1.getValueType() != VT)
7943           return false;
7944       }
7945       if (i * 2 == NumElts)
7946         ExpectedVExtractIdx = BaseIdx;
7947     }
7948 
7949     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
7950     if (I0 == ExpectedVExtractIdx)
7951       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
7952     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
7953       // Try to match the following dag sequence:
7954       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
7955       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
7956     } else
7957       CanFold = false;
7958 
7959     ExpectedVExtractIdx += 2;
7960   }
7961 
7962   return CanFold;
7963 }
7964 
7965 /// Emit a sequence of two 128-bit horizontal add/sub followed by
7966 /// a concat_vector.
7967 ///
7968 /// This is a helper function of LowerToHorizontalOp().
7969 /// This function expects two 256-bit vectors called V0 and V1.
7970 /// At first, each vector is split into two separate 128-bit vectors.
7971 /// Then, the resulting 128-bit vectors are used to implement two
7972 /// horizontal binary operations.
7973 ///
7974 /// The kind of horizontal binary operation is defined by \p X86Opcode.
7975 ///
7976 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
7977 /// the two new horizontal binop.
7978 /// When Mode is set, the first horizontal binop dag node would take as input
7979 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
7980 /// horizontal binop dag node would take as input the lower 128-bit of V1
7981 /// and the upper 128-bit of V1.
7982 ///   Example:
7983 ///     HADD V0_LO, V0_HI
7984 ///     HADD V1_LO, V1_HI
7985 ///
7986 /// Otherwise, the first horizontal binop dag node takes as input the lower
7987 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
7988 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
7989 ///   Example:
7990 ///     HADD V0_LO, V1_LO
7991 ///     HADD V0_HI, V1_HI
7992 ///
7993 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
7994 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
7995 /// the upper 128-bits of the result.
ExpandHorizontalBinOp(const SDValue & V0,const SDValue & V1,const SDLoc & DL,SelectionDAG & DAG,unsigned X86Opcode,bool Mode,bool isUndefLO,bool isUndefHI)7996 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
7997                                      const SDLoc &DL, SelectionDAG &DAG,
7998                                      unsigned X86Opcode, bool Mode,
7999                                      bool isUndefLO, bool isUndefHI) {
8000   MVT VT = V0.getSimpleValueType();
8001   assert(VT.is256BitVector() && VT == V1.getSimpleValueType() &&
8002          "Invalid nodes in input!");
8003 
8004   unsigned NumElts = VT.getVectorNumElements();
8005   SDValue V0_LO = extract128BitVector(V0, 0, DAG, DL);
8006   SDValue V0_HI = extract128BitVector(V0, NumElts/2, DAG, DL);
8007   SDValue V1_LO = extract128BitVector(V1, 0, DAG, DL);
8008   SDValue V1_HI = extract128BitVector(V1, NumElts/2, DAG, DL);
8009   MVT NewVT = V0_LO.getSimpleValueType();
8010 
8011   SDValue LO = DAG.getUNDEF(NewVT);
8012   SDValue HI = DAG.getUNDEF(NewVT);
8013 
8014   if (Mode) {
8015     // Don't emit a horizontal binop if the result is expected to be UNDEF.
8016     if (!isUndefLO && !V0->isUndef())
8017       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
8018     if (!isUndefHI && !V1->isUndef())
8019       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
8020   } else {
8021     // Don't emit a horizontal binop if the result is expected to be UNDEF.
8022     if (!isUndefLO && (!V0_LO->isUndef() || !V1_LO->isUndef()))
8023       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
8024 
8025     if (!isUndefHI && (!V0_HI->isUndef() || !V1_HI->isUndef()))
8026       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
8027   }
8028 
8029   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
8030 }
8031 
8032 /// Returns true iff \p BV builds a vector with the result equivalent to
8033 /// the result of ADDSUB/SUBADD operation.
8034 /// If true is returned then the operands of ADDSUB = Opnd0 +- Opnd1
8035 /// (SUBADD = Opnd0 -+ Opnd1) operation are written to the parameters
8036 /// \p Opnd0 and \p Opnd1.
isAddSubOrSubAdd(const BuildVectorSDNode * BV,const X86Subtarget & Subtarget,SelectionDAG & DAG,SDValue & Opnd0,SDValue & Opnd1,unsigned & NumExtracts,bool & IsSubAdd)8037 static bool isAddSubOrSubAdd(const BuildVectorSDNode *BV,
8038                              const X86Subtarget &Subtarget, SelectionDAG &DAG,
8039                              SDValue &Opnd0, SDValue &Opnd1,
8040                              unsigned &NumExtracts,
8041                              bool &IsSubAdd) {
8042 
8043   MVT VT = BV->getSimpleValueType(0);
8044   if (!Subtarget.hasSSE3() || !VT.isFloatingPoint())
8045     return false;
8046 
8047   unsigned NumElts = VT.getVectorNumElements();
8048   SDValue InVec0 = DAG.getUNDEF(VT);
8049   SDValue InVec1 = DAG.getUNDEF(VT);
8050 
8051   NumExtracts = 0;
8052 
8053   // Odd-numbered elements in the input build vector are obtained from
8054   // adding/subtracting two integer/float elements.
8055   // Even-numbered elements in the input build vector are obtained from
8056   // subtracting/adding two integer/float elements.
8057   unsigned Opc[2] = {0, 0};
8058   for (unsigned i = 0, e = NumElts; i != e; ++i) {
8059     SDValue Op = BV->getOperand(i);
8060 
8061     // Skip 'undef' values.
8062     unsigned Opcode = Op.getOpcode();
8063     if (Opcode == ISD::UNDEF)
8064       continue;
8065 
8066     // Early exit if we found an unexpected opcode.
8067     if (Opcode != ISD::FADD && Opcode != ISD::FSUB)
8068       return false;
8069 
8070     SDValue Op0 = Op.getOperand(0);
8071     SDValue Op1 = Op.getOperand(1);
8072 
8073     // Try to match the following pattern:
8074     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
8075     // Early exit if we cannot match that sequence.
8076     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8077         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8078         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
8079         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
8080         Op0.getOperand(1) != Op1.getOperand(1))
8081       return false;
8082 
8083     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
8084     if (I0 != i)
8085       return false;
8086 
8087     // We found a valid add/sub node, make sure its the same opcode as previous
8088     // elements for this parity.
8089     if (Opc[i % 2] != 0 && Opc[i % 2] != Opcode)
8090       return false;
8091     Opc[i % 2] = Opcode;
8092 
8093     // Update InVec0 and InVec1.
8094     if (InVec0.isUndef()) {
8095       InVec0 = Op0.getOperand(0);
8096       if (InVec0.getSimpleValueType() != VT)
8097         return false;
8098     }
8099     if (InVec1.isUndef()) {
8100       InVec1 = Op1.getOperand(0);
8101       if (InVec1.getSimpleValueType() != VT)
8102         return false;
8103     }
8104 
8105     // Make sure that operands in input to each add/sub node always
8106     // come from a same pair of vectors.
8107     if (InVec0 != Op0.getOperand(0)) {
8108       if (Opcode == ISD::FSUB)
8109         return false;
8110 
8111       // FADD is commutable. Try to commute the operands
8112       // and then test again.
8113       std::swap(Op0, Op1);
8114       if (InVec0 != Op0.getOperand(0))
8115         return false;
8116     }
8117 
8118     if (InVec1 != Op1.getOperand(0))
8119       return false;
8120 
8121     // Increment the number of extractions done.
8122     ++NumExtracts;
8123   }
8124 
8125   // Ensure we have found an opcode for both parities and that they are
8126   // different. Don't try to fold this build_vector into an ADDSUB/SUBADD if the
8127   // inputs are undef.
8128   if (!Opc[0] || !Opc[1] || Opc[0] == Opc[1] ||
8129       InVec0.isUndef() || InVec1.isUndef())
8130     return false;
8131 
8132   IsSubAdd = Opc[0] == ISD::FADD;
8133 
8134   Opnd0 = InVec0;
8135   Opnd1 = InVec1;
8136   return true;
8137 }
8138 
8139 /// Returns true if is possible to fold MUL and an idiom that has already been
8140 /// recognized as ADDSUB/SUBADD(\p Opnd0, \p Opnd1) into
8141 /// FMADDSUB/FMSUBADD(x, y, \p Opnd1). If (and only if) true is returned, the
8142 /// operands of FMADDSUB/FMSUBADD are written to parameters \p Opnd0, \p Opnd1, \p Opnd2.
8143 ///
8144 /// Prior to calling this function it should be known that there is some
8145 /// SDNode that potentially can be replaced with an X86ISD::ADDSUB operation
8146 /// using \p Opnd0 and \p Opnd1 as operands. Also, this method is called
8147 /// before replacement of such SDNode with ADDSUB operation. Thus the number
8148 /// of \p Opnd0 uses is expected to be equal to 2.
8149 /// For example, this function may be called for the following IR:
8150 ///    %AB = fmul fast <2 x double> %A, %B
8151 ///    %Sub = fsub fast <2 x double> %AB, %C
8152 ///    %Add = fadd fast <2 x double> %AB, %C
8153 ///    %Addsub = shufflevector <2 x double> %Sub, <2 x double> %Add,
8154 ///                            <2 x i32> <i32 0, i32 3>
8155 /// There is a def for %Addsub here, which potentially can be replaced by
8156 /// X86ISD::ADDSUB operation:
8157 ///    %Addsub = X86ISD::ADDSUB %AB, %C
8158 /// and such ADDSUB can further be replaced with FMADDSUB:
8159 ///    %Addsub = FMADDSUB %A, %B, %C.
8160 ///
8161 /// The main reason why this method is called before the replacement of the
8162 /// recognized ADDSUB idiom with ADDSUB operation is that such replacement
8163 /// is illegal sometimes. E.g. 512-bit ADDSUB is not available, while 512-bit
8164 /// FMADDSUB is.
isFMAddSubOrFMSubAdd(const X86Subtarget & Subtarget,SelectionDAG & DAG,SDValue & Opnd0,SDValue & Opnd1,SDValue & Opnd2,unsigned ExpectedUses)8165 static bool isFMAddSubOrFMSubAdd(const X86Subtarget &Subtarget,
8166                                  SelectionDAG &DAG,
8167                                  SDValue &Opnd0, SDValue &Opnd1, SDValue &Opnd2,
8168                                  unsigned ExpectedUses) {
8169   if (Opnd0.getOpcode() != ISD::FMUL ||
8170       !Opnd0->hasNUsesOfValue(ExpectedUses, 0) || !Subtarget.hasAnyFMA())
8171     return false;
8172 
8173   // FIXME: These checks must match the similar ones in
8174   // DAGCombiner::visitFADDForFMACombine. It would be good to have one
8175   // function that would answer if it is Ok to fuse MUL + ADD to FMADD
8176   // or MUL + ADDSUB to FMADDSUB.
8177   const TargetOptions &Options = DAG.getTarget().Options;
8178   bool AllowFusion =
8179       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8180   if (!AllowFusion)
8181     return false;
8182 
8183   Opnd2 = Opnd1;
8184   Opnd1 = Opnd0.getOperand(1);
8185   Opnd0 = Opnd0.getOperand(0);
8186 
8187   return true;
8188 }
8189 
8190 /// Try to fold a build_vector that performs an 'addsub' or 'fmaddsub' or
8191 /// 'fsubadd' operation accordingly to X86ISD::ADDSUB or X86ISD::FMADDSUB or
8192 /// X86ISD::FMSUBADD node.
lowerToAddSubOrFMAddSub(const BuildVectorSDNode * BV,const X86Subtarget & Subtarget,SelectionDAG & DAG)8193 static SDValue lowerToAddSubOrFMAddSub(const BuildVectorSDNode *BV,
8194                                        const X86Subtarget &Subtarget,
8195                                        SelectionDAG &DAG) {
8196   SDValue Opnd0, Opnd1;
8197   unsigned NumExtracts;
8198   bool IsSubAdd;
8199   if (!isAddSubOrSubAdd(BV, Subtarget, DAG, Opnd0, Opnd1, NumExtracts,
8200                         IsSubAdd))
8201     return SDValue();
8202 
8203   MVT VT = BV->getSimpleValueType(0);
8204   SDLoc DL(BV);
8205 
8206   // Try to generate X86ISD::FMADDSUB node here.
8207   SDValue Opnd2;
8208   if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, NumExtracts)) {
8209     unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
8210     return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
8211   }
8212 
8213   // We only support ADDSUB.
8214   if (IsSubAdd)
8215     return SDValue();
8216 
8217   // Do not generate X86ISD::ADDSUB node for 512-bit types even though
8218   // the ADDSUB idiom has been successfully recognized. There are no known
8219   // X86 targets with 512-bit ADDSUB instructions!
8220   // 512-bit ADDSUB idiom recognition was needed only as part of FMADDSUB idiom
8221   // recognition.
8222   if (VT.is512BitVector())
8223     return SDValue();
8224 
8225   return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
8226 }
8227 
isHopBuildVector(const BuildVectorSDNode * BV,SelectionDAG & DAG,unsigned & HOpcode,SDValue & V0,SDValue & V1)8228 static bool isHopBuildVector(const BuildVectorSDNode *BV, SelectionDAG &DAG,
8229                              unsigned &HOpcode, SDValue &V0, SDValue &V1) {
8230   // Initialize outputs to known values.
8231   MVT VT = BV->getSimpleValueType(0);
8232   HOpcode = ISD::DELETED_NODE;
8233   V0 = DAG.getUNDEF(VT);
8234   V1 = DAG.getUNDEF(VT);
8235 
8236   // x86 256-bit horizontal ops are defined in a non-obvious way. Each 128-bit
8237   // half of the result is calculated independently from the 128-bit halves of
8238   // the inputs, so that makes the index-checking logic below more complicated.
8239   unsigned NumElts = VT.getVectorNumElements();
8240   unsigned GenericOpcode = ISD::DELETED_NODE;
8241   unsigned Num128BitChunks = VT.is256BitVector() ? 2 : 1;
8242   unsigned NumEltsIn128Bits = NumElts / Num128BitChunks;
8243   unsigned NumEltsIn64Bits = NumEltsIn128Bits / 2;
8244   for (unsigned i = 0; i != Num128BitChunks; ++i) {
8245     for (unsigned j = 0; j != NumEltsIn128Bits; ++j) {
8246       // Ignore undef elements.
8247       SDValue Op = BV->getOperand(i * NumEltsIn128Bits + j);
8248       if (Op.isUndef())
8249         continue;
8250 
8251       // If there's an opcode mismatch, we're done.
8252       if (HOpcode != ISD::DELETED_NODE && Op.getOpcode() != GenericOpcode)
8253         return false;
8254 
8255       // Initialize horizontal opcode.
8256       if (HOpcode == ISD::DELETED_NODE) {
8257         GenericOpcode = Op.getOpcode();
8258         switch (GenericOpcode) {
8259         case ISD::ADD: HOpcode = X86ISD::HADD; break;
8260         case ISD::SUB: HOpcode = X86ISD::HSUB; break;
8261         case ISD::FADD: HOpcode = X86ISD::FHADD; break;
8262         case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
8263         default: return false;
8264         }
8265       }
8266 
8267       SDValue Op0 = Op.getOperand(0);
8268       SDValue Op1 = Op.getOperand(1);
8269       if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8270           Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8271           Op0.getOperand(0) != Op1.getOperand(0) ||
8272           !isa<ConstantSDNode>(Op0.getOperand(1)) ||
8273           !isa<ConstantSDNode>(Op1.getOperand(1)) || !Op.hasOneUse())
8274         return false;
8275 
8276       // The source vector is chosen based on which 64-bit half of the
8277       // destination vector is being calculated.
8278       if (j < NumEltsIn64Bits) {
8279         if (V0.isUndef())
8280           V0 = Op0.getOperand(0);
8281       } else {
8282         if (V1.isUndef())
8283           V1 = Op0.getOperand(0);
8284       }
8285 
8286       SDValue SourceVec = (j < NumEltsIn64Bits) ? V0 : V1;
8287       if (SourceVec != Op0.getOperand(0))
8288         return false;
8289 
8290       // op (extract_vector_elt A, I), (extract_vector_elt A, I+1)
8291       unsigned ExtIndex0 = Op0.getConstantOperandVal(1);
8292       unsigned ExtIndex1 = Op1.getConstantOperandVal(1);
8293       unsigned ExpectedIndex = i * NumEltsIn128Bits +
8294                                (j % NumEltsIn64Bits) * 2;
8295       if (ExpectedIndex == ExtIndex0 && ExtIndex1 == ExtIndex0 + 1)
8296         continue;
8297 
8298       // If this is not a commutative op, this does not match.
8299       if (GenericOpcode != ISD::ADD && GenericOpcode != ISD::FADD)
8300         return false;
8301 
8302       // Addition is commutative, so try swapping the extract indexes.
8303       // op (extract_vector_elt A, I+1), (extract_vector_elt A, I)
8304       if (ExpectedIndex == ExtIndex1 && ExtIndex0 == ExtIndex1 + 1)
8305         continue;
8306 
8307       // Extract indexes do not match horizontal requirement.
8308       return false;
8309     }
8310   }
8311   // We matched. Opcode and operands are returned by reference as arguments.
8312   return true;
8313 }
8314 
getHopForBuildVector(const BuildVectorSDNode * BV,SelectionDAG & DAG,unsigned HOpcode,SDValue V0,SDValue V1)8315 static SDValue getHopForBuildVector(const BuildVectorSDNode *BV,
8316                                     SelectionDAG &DAG, unsigned HOpcode,
8317                                     SDValue V0, SDValue V1) {
8318   // If either input vector is not the same size as the build vector,
8319   // extract/insert the low bits to the correct size.
8320   // This is free (examples: zmm --> xmm, xmm --> ymm).
8321   MVT VT = BV->getSimpleValueType(0);
8322   unsigned Width = VT.getSizeInBits();
8323   if (V0.getValueSizeInBits() > Width)
8324     V0 = extractSubVector(V0, 0, DAG, SDLoc(BV), Width);
8325   else if (V0.getValueSizeInBits() < Width)
8326     V0 = insertSubVector(DAG.getUNDEF(VT), V0, 0, DAG, SDLoc(BV), Width);
8327 
8328   if (V1.getValueSizeInBits() > Width)
8329     V1 = extractSubVector(V1, 0, DAG, SDLoc(BV), Width);
8330   else if (V1.getValueSizeInBits() < Width)
8331     V1 = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, SDLoc(BV), Width);
8332 
8333   return DAG.getNode(HOpcode, SDLoc(BV), VT, V0, V1);
8334 }
8335 
8336 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
LowerToHorizontalOp(const BuildVectorSDNode * BV,const X86Subtarget & Subtarget,SelectionDAG & DAG)8337 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
8338                                    const X86Subtarget &Subtarget,
8339                                    SelectionDAG &DAG) {
8340   // We need at least 2 non-undef elements to make this worthwhile by default.
8341   unsigned NumNonUndefs = 0;
8342   for (const SDValue &V : BV->op_values())
8343     if (!V.isUndef())
8344       ++NumNonUndefs;
8345 
8346   if (NumNonUndefs < 2)
8347     return SDValue();
8348 
8349   // There are 4 sets of horizontal math operations distinguished by type:
8350   // int/FP at 128-bit/256-bit. Each type was introduced with a different
8351   // subtarget feature. Try to match those "native" patterns first.
8352   MVT VT = BV->getSimpleValueType(0);
8353   unsigned HOpcode;
8354   SDValue V0, V1;
8355   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget.hasSSE3())
8356     if (isHopBuildVector(BV, DAG, HOpcode, V0, V1))
8357       return getHopForBuildVector(BV, DAG, HOpcode, V0, V1);
8358 
8359   if ((VT == MVT::v8i16 || VT == MVT::v4i32) && Subtarget.hasSSSE3())
8360     if (isHopBuildVector(BV, DAG, HOpcode, V0, V1))
8361       return getHopForBuildVector(BV, DAG, HOpcode, V0, V1);
8362 
8363   if ((VT == MVT::v8f32 || VT == MVT::v4f64) && Subtarget.hasAVX())
8364     if (isHopBuildVector(BV, DAG, HOpcode, V0, V1))
8365       return getHopForBuildVector(BV, DAG, HOpcode, V0, V1);
8366 
8367   if ((VT == MVT::v16i16 || VT == MVT::v8i32) && Subtarget.hasAVX2())
8368     if (isHopBuildVector(BV, DAG, HOpcode, V0, V1))
8369       return getHopForBuildVector(BV, DAG, HOpcode, V0, V1);
8370 
8371   // Try harder to match 256-bit ops by using extract/concat.
8372   if (!Subtarget.hasAVX() || !VT.is256BitVector())
8373     return SDValue();
8374 
8375   // Count the number of UNDEF operands in the build_vector in input.
8376   unsigned NumElts = VT.getVectorNumElements();
8377   unsigned Half = NumElts / 2;
8378   unsigned NumUndefsLO = 0;
8379   unsigned NumUndefsHI = 0;
8380   for (unsigned i = 0, e = Half; i != e; ++i)
8381     if (BV->getOperand(i)->isUndef())
8382       NumUndefsLO++;
8383 
8384   for (unsigned i = Half, e = NumElts; i != e; ++i)
8385     if (BV->getOperand(i)->isUndef())
8386       NumUndefsHI++;
8387 
8388   SDLoc DL(BV);
8389   SDValue InVec0, InVec1;
8390   if (VT == MVT::v8i32 || VT == MVT::v16i16) {
8391     SDValue InVec2, InVec3;
8392     unsigned X86Opcode;
8393     bool CanFold = true;
8394 
8395     if (isHorizontalBinOpPart(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
8396         isHorizontalBinOpPart(BV, ISD::ADD, DAG, Half, NumElts, InVec2,
8397                               InVec3) &&
8398         ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
8399         ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
8400       X86Opcode = X86ISD::HADD;
8401     else if (isHorizontalBinOpPart(BV, ISD::SUB, DAG, 0, Half, InVec0,
8402                                    InVec1) &&
8403              isHorizontalBinOpPart(BV, ISD::SUB, DAG, Half, NumElts, InVec2,
8404                                    InVec3) &&
8405              ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
8406              ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
8407       X86Opcode = X86ISD::HSUB;
8408     else
8409       CanFold = false;
8410 
8411     if (CanFold) {
8412       // Do not try to expand this build_vector into a pair of horizontal
8413       // add/sub if we can emit a pair of scalar add/sub.
8414       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
8415         return SDValue();
8416 
8417       // Convert this build_vector into a pair of horizontal binops followed by
8418       // a concat vector. We must adjust the outputs from the partial horizontal
8419       // matching calls above to account for undefined vector halves.
8420       SDValue V0 = InVec0.isUndef() ? InVec2 : InVec0;
8421       SDValue V1 = InVec1.isUndef() ? InVec3 : InVec1;
8422       assert((!V0.isUndef() || !V1.isUndef()) && "Horizontal-op of undefs?");
8423       bool isUndefLO = NumUndefsLO == Half;
8424       bool isUndefHI = NumUndefsHI == Half;
8425       return ExpandHorizontalBinOp(V0, V1, DL, DAG, X86Opcode, false, isUndefLO,
8426                                    isUndefHI);
8427     }
8428   }
8429 
8430   if (VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
8431       VT == MVT::v16i16) {
8432     unsigned X86Opcode;
8433     if (isHorizontalBinOpPart(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
8434       X86Opcode = X86ISD::HADD;
8435     else if (isHorizontalBinOpPart(BV, ISD::SUB, DAG, 0, NumElts, InVec0,
8436                                    InVec1))
8437       X86Opcode = X86ISD::HSUB;
8438     else if (isHorizontalBinOpPart(BV, ISD::FADD, DAG, 0, NumElts, InVec0,
8439                                    InVec1))
8440       X86Opcode = X86ISD::FHADD;
8441     else if (isHorizontalBinOpPart(BV, ISD::FSUB, DAG, 0, NumElts, InVec0,
8442                                    InVec1))
8443       X86Opcode = X86ISD::FHSUB;
8444     else
8445       return SDValue();
8446 
8447     // Don't try to expand this build_vector into a pair of horizontal add/sub
8448     // if we can simply emit a pair of scalar add/sub.
8449     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
8450       return SDValue();
8451 
8452     // Convert this build_vector into two horizontal add/sub followed by
8453     // a concat vector.
8454     bool isUndefLO = NumUndefsLO == Half;
8455     bool isUndefHI = NumUndefsHI == Half;
8456     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
8457                                  isUndefLO, isUndefHI);
8458   }
8459 
8460   return SDValue();
8461 }
8462 
8463 /// If a BUILD_VECTOR's source elements all apply the same bit operation and
8464 /// one of their operands is constant, lower to a pair of BUILD_VECTOR and
8465 /// just apply the bit to the vectors.
8466 /// NOTE: Its not in our interest to start make a general purpose vectorizer
8467 /// from this, but enough scalar bit operations are created from the later
8468 /// legalization + scalarization stages to need basic support.
lowerBuildVectorToBitOp(BuildVectorSDNode * Op,SelectionDAG & DAG)8469 static SDValue lowerBuildVectorToBitOp(BuildVectorSDNode *Op,
8470                                        SelectionDAG &DAG) {
8471   SDLoc DL(Op);
8472   MVT VT = Op->getSimpleValueType(0);
8473   unsigned NumElems = VT.getVectorNumElements();
8474   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8475 
8476   // Check that all elements have the same opcode.
8477   // TODO: Should we allow UNDEFS and if so how many?
8478   unsigned Opcode = Op->getOperand(0).getOpcode();
8479   for (unsigned i = 1; i < NumElems; ++i)
8480     if (Opcode != Op->getOperand(i).getOpcode())
8481       return SDValue();
8482 
8483   // TODO: We may be able to add support for other Ops (ADD/SUB + shifts).
8484   switch (Opcode) {
8485   default:
8486     return SDValue();
8487   case ISD::AND:
8488   case ISD::XOR:
8489   case ISD::OR:
8490     // Don't do this if the buildvector is a splat - we'd replace one
8491     // constant with an entire vector.
8492     if (Op->getSplatValue())
8493       return SDValue();
8494     if (!TLI.isOperationLegalOrPromote(Opcode, VT))
8495       return SDValue();
8496     break;
8497   }
8498 
8499   SmallVector<SDValue, 4> LHSElts, RHSElts;
8500   for (SDValue Elt : Op->ops()) {
8501     SDValue LHS = Elt.getOperand(0);
8502     SDValue RHS = Elt.getOperand(1);
8503 
8504     // We expect the canonicalized RHS operand to be the constant.
8505     if (!isa<ConstantSDNode>(RHS))
8506       return SDValue();
8507     LHSElts.push_back(LHS);
8508     RHSElts.push_back(RHS);
8509   }
8510 
8511   SDValue LHS = DAG.getBuildVector(VT, DL, LHSElts);
8512   SDValue RHS = DAG.getBuildVector(VT, DL, RHSElts);
8513   return DAG.getNode(Opcode, DL, VT, LHS, RHS);
8514 }
8515 
8516 /// Create a vector constant without a load. SSE/AVX provide the bare minimum
8517 /// functionality to do this, so it's all zeros, all ones, or some derivation
8518 /// that is cheap to calculate.
materializeVectorConstant(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)8519 static SDValue materializeVectorConstant(SDValue Op, SelectionDAG &DAG,
8520                                          const X86Subtarget &Subtarget) {
8521   SDLoc DL(Op);
8522   MVT VT = Op.getSimpleValueType();
8523 
8524   // Vectors containing all zeros can be matched by pxor and xorps.
8525   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
8526     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
8527     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
8528     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
8529       return Op;
8530 
8531     return getZeroVector(VT, Subtarget, DAG, DL);
8532   }
8533 
8534   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
8535   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
8536   // vpcmpeqd on 256-bit vectors.
8537   if (Subtarget.hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
8538     if (VT == MVT::v4i32 || VT == MVT::v16i32 ||
8539         (VT == MVT::v8i32 && Subtarget.hasInt256()))
8540       return Op;
8541 
8542     return getOnesVector(VT, DAG, DL);
8543   }
8544 
8545   return SDValue();
8546 }
8547 
8548 /// Look for opportunities to create a VPERMV/VPERMILPV/PSHUFB variable permute
8549 /// from a vector of source values and a vector of extraction indices.
8550 /// The vectors might be manipulated to match the type of the permute op.
createVariablePermute(MVT VT,SDValue SrcVec,SDValue IndicesVec,SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)8551 static SDValue createVariablePermute(MVT VT, SDValue SrcVec, SDValue IndicesVec,
8552                                      SDLoc &DL, SelectionDAG &DAG,
8553                                      const X86Subtarget &Subtarget) {
8554   MVT ShuffleVT = VT;
8555   EVT IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
8556   unsigned NumElts = VT.getVectorNumElements();
8557   unsigned SizeInBits = VT.getSizeInBits();
8558 
8559   // Adjust IndicesVec to match VT size.
8560   assert(IndicesVec.getValueType().getVectorNumElements() >= NumElts &&
8561          "Illegal variable permute mask size");
8562   if (IndicesVec.getValueType().getVectorNumElements() > NumElts)
8563     IndicesVec = extractSubVector(IndicesVec, 0, DAG, SDLoc(IndicesVec),
8564                                   NumElts * VT.getScalarSizeInBits());
8565   IndicesVec = DAG.getZExtOrTrunc(IndicesVec, SDLoc(IndicesVec), IndicesVT);
8566 
8567   // Handle SrcVec that don't match VT type.
8568   if (SrcVec.getValueSizeInBits() != SizeInBits) {
8569     if ((SrcVec.getValueSizeInBits() % SizeInBits) == 0) {
8570       // Handle larger SrcVec by treating it as a larger permute.
8571       unsigned Scale = SrcVec.getValueSizeInBits() / SizeInBits;
8572       VT = MVT::getVectorVT(VT.getScalarType(), Scale * NumElts);
8573       IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
8574       IndicesVec = widenSubVector(IndicesVT.getSimpleVT(), IndicesVec, false,
8575                                   Subtarget, DAG, SDLoc(IndicesVec));
8576       return extractSubVector(
8577           createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget), 0,
8578           DAG, DL, SizeInBits);
8579     } else if (SrcVec.getValueSizeInBits() < SizeInBits) {
8580       // Widen smaller SrcVec to match VT.
8581       SrcVec = widenSubVector(VT, SrcVec, false, Subtarget, DAG, SDLoc(SrcVec));
8582     } else
8583       return SDValue();
8584   }
8585 
8586   auto ScaleIndices = [&DAG](SDValue Idx, uint64_t Scale) {
8587     assert(isPowerOf2_64(Scale) && "Illegal variable permute shuffle scale");
8588     EVT SrcVT = Idx.getValueType();
8589     unsigned NumDstBits = SrcVT.getScalarSizeInBits() / Scale;
8590     uint64_t IndexScale = 0;
8591     uint64_t IndexOffset = 0;
8592 
8593     // If we're scaling a smaller permute op, then we need to repeat the
8594     // indices, scaling and offsetting them as well.
8595     // e.g. v4i32 -> v16i8 (Scale = 4)
8596     // IndexScale = v4i32 Splat(4 << 24 | 4 << 16 | 4 << 8 | 4)
8597     // IndexOffset = v4i32 Splat(3 << 24 | 2 << 16 | 1 << 8 | 0)
8598     for (uint64_t i = 0; i != Scale; ++i) {
8599       IndexScale |= Scale << (i * NumDstBits);
8600       IndexOffset |= i << (i * NumDstBits);
8601     }
8602 
8603     Idx = DAG.getNode(ISD::MUL, SDLoc(Idx), SrcVT, Idx,
8604                       DAG.getConstant(IndexScale, SDLoc(Idx), SrcVT));
8605     Idx = DAG.getNode(ISD::ADD, SDLoc(Idx), SrcVT, Idx,
8606                       DAG.getConstant(IndexOffset, SDLoc(Idx), SrcVT));
8607     return Idx;
8608   };
8609 
8610   unsigned Opcode = 0;
8611   switch (VT.SimpleTy) {
8612   default:
8613     break;
8614   case MVT::v16i8:
8615     if (Subtarget.hasSSSE3())
8616       Opcode = X86ISD::PSHUFB;
8617     break;
8618   case MVT::v8i16:
8619     if (Subtarget.hasVLX() && Subtarget.hasBWI())
8620       Opcode = X86ISD::VPERMV;
8621     else if (Subtarget.hasSSSE3()) {
8622       Opcode = X86ISD::PSHUFB;
8623       ShuffleVT = MVT::v16i8;
8624     }
8625     break;
8626   case MVT::v4f32:
8627   case MVT::v4i32:
8628     if (Subtarget.hasAVX()) {
8629       Opcode = X86ISD::VPERMILPV;
8630       ShuffleVT = MVT::v4f32;
8631     } else if (Subtarget.hasSSSE3()) {
8632       Opcode = X86ISD::PSHUFB;
8633       ShuffleVT = MVT::v16i8;
8634     }
8635     break;
8636   case MVT::v2f64:
8637   case MVT::v2i64:
8638     if (Subtarget.hasAVX()) {
8639       // VPERMILPD selects using bit#1 of the index vector, so scale IndicesVec.
8640       IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
8641       Opcode = X86ISD::VPERMILPV;
8642       ShuffleVT = MVT::v2f64;
8643     } else if (Subtarget.hasSSE41()) {
8644       // SSE41 can compare v2i64 - select between indices 0 and 1.
8645       return DAG.getSelectCC(
8646           DL, IndicesVec,
8647           getZeroVector(IndicesVT.getSimpleVT(), Subtarget, DAG, DL),
8648           DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {0, 0}),
8649           DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {1, 1}),
8650           ISD::CondCode::SETEQ);
8651     }
8652     break;
8653   case MVT::v32i8:
8654     if (Subtarget.hasVLX() && Subtarget.hasVBMI())
8655       Opcode = X86ISD::VPERMV;
8656     else if (Subtarget.hasXOP()) {
8657       SDValue LoSrc = extract128BitVector(SrcVec, 0, DAG, DL);
8658       SDValue HiSrc = extract128BitVector(SrcVec, 16, DAG, DL);
8659       SDValue LoIdx = extract128BitVector(IndicesVec, 0, DAG, DL);
8660       SDValue HiIdx = extract128BitVector(IndicesVec, 16, DAG, DL);
8661       return DAG.getNode(
8662           ISD::CONCAT_VECTORS, DL, VT,
8663           DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, LoIdx),
8664           DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, HiIdx));
8665     } else if (Subtarget.hasAVX()) {
8666       SDValue Lo = extract128BitVector(SrcVec, 0, DAG, DL);
8667       SDValue Hi = extract128BitVector(SrcVec, 16, DAG, DL);
8668       SDValue LoLo = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Lo);
8669       SDValue HiHi = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Hi, Hi);
8670       auto PSHUFBBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
8671                               ArrayRef<SDValue> Ops) {
8672         // Permute Lo and Hi and then select based on index range.
8673         // This works as SHUFB uses bits[3:0] to permute elements and we don't
8674         // care about the bit[7] as its just an index vector.
8675         SDValue Idx = Ops[2];
8676         EVT VT = Idx.getValueType();
8677         return DAG.getSelectCC(DL, Idx, DAG.getConstant(15, DL, VT),
8678                                DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[1], Idx),
8679                                DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[0], Idx),
8680                                ISD::CondCode::SETGT);
8681       };
8682       SDValue Ops[] = {LoLo, HiHi, IndicesVec};
8683       return SplitOpsAndApply(DAG, Subtarget, DL, MVT::v32i8, Ops,
8684                               PSHUFBBuilder);
8685     }
8686     break;
8687   case MVT::v16i16:
8688     if (Subtarget.hasVLX() && Subtarget.hasBWI())
8689       Opcode = X86ISD::VPERMV;
8690     else if (Subtarget.hasAVX()) {
8691       // Scale to v32i8 and perform as v32i8.
8692       IndicesVec = ScaleIndices(IndicesVec, 2);
8693       return DAG.getBitcast(
8694           VT, createVariablePermute(
8695                   MVT::v32i8, DAG.getBitcast(MVT::v32i8, SrcVec),
8696                   DAG.getBitcast(MVT::v32i8, IndicesVec), DL, DAG, Subtarget));
8697     }
8698     break;
8699   case MVT::v8f32:
8700   case MVT::v8i32:
8701     if (Subtarget.hasAVX2())
8702       Opcode = X86ISD::VPERMV;
8703     else if (Subtarget.hasAVX()) {
8704       SrcVec = DAG.getBitcast(MVT::v8f32, SrcVec);
8705       SDValue LoLo = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
8706                                           {0, 1, 2, 3, 0, 1, 2, 3});
8707       SDValue HiHi = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
8708                                           {4, 5, 6, 7, 4, 5, 6, 7});
8709       if (Subtarget.hasXOP())
8710         return DAG.getBitcast(VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v8f32,
8711                                               LoLo, HiHi, IndicesVec,
8712                                               DAG.getConstant(0, DL, MVT::i8)));
8713       // Permute Lo and Hi and then select based on index range.
8714       // This works as VPERMILPS only uses index bits[0:1] to permute elements.
8715       SDValue Res = DAG.getSelectCC(
8716           DL, IndicesVec, DAG.getConstant(3, DL, MVT::v8i32),
8717           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, HiHi, IndicesVec),
8718           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, LoLo, IndicesVec),
8719           ISD::CondCode::SETGT);
8720       return DAG.getBitcast(VT, Res);
8721     }
8722     break;
8723   case MVT::v4i64:
8724   case MVT::v4f64:
8725     if (Subtarget.hasAVX512()) {
8726       if (!Subtarget.hasVLX()) {
8727         MVT WidenSrcVT = MVT::getVectorVT(VT.getScalarType(), 8);
8728         SrcVec = widenSubVector(WidenSrcVT, SrcVec, false, Subtarget, DAG,
8729                                 SDLoc(SrcVec));
8730         IndicesVec = widenSubVector(MVT::v8i64, IndicesVec, false, Subtarget,
8731                                     DAG, SDLoc(IndicesVec));
8732         SDValue Res = createVariablePermute(WidenSrcVT, SrcVec, IndicesVec, DL,
8733                                             DAG, Subtarget);
8734         return extract256BitVector(Res, 0, DAG, DL);
8735       }
8736       Opcode = X86ISD::VPERMV;
8737     } else if (Subtarget.hasAVX()) {
8738       SrcVec = DAG.getBitcast(MVT::v4f64, SrcVec);
8739       SDValue LoLo =
8740           DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {0, 1, 0, 1});
8741       SDValue HiHi =
8742           DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {2, 3, 2, 3});
8743       // VPERMIL2PD selects with bit#1 of the index vector, so scale IndicesVec.
8744       IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
8745       if (Subtarget.hasXOP())
8746         return DAG.getBitcast(VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v4f64,
8747                                               LoLo, HiHi, IndicesVec,
8748                                               DAG.getConstant(0, DL, MVT::i8)));
8749       // Permute Lo and Hi and then select based on index range.
8750       // This works as VPERMILPD only uses index bit[1] to permute elements.
8751       SDValue Res = DAG.getSelectCC(
8752           DL, IndicesVec, DAG.getConstant(2, DL, MVT::v4i64),
8753           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, HiHi, IndicesVec),
8754           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, LoLo, IndicesVec),
8755           ISD::CondCode::SETGT);
8756       return DAG.getBitcast(VT, Res);
8757     }
8758     break;
8759   case MVT::v64i8:
8760     if (Subtarget.hasVBMI())
8761       Opcode = X86ISD::VPERMV;
8762     break;
8763   case MVT::v32i16:
8764     if (Subtarget.hasBWI())
8765       Opcode = X86ISD::VPERMV;
8766     break;
8767   case MVT::v16f32:
8768   case MVT::v16i32:
8769   case MVT::v8f64:
8770   case MVT::v8i64:
8771     if (Subtarget.hasAVX512())
8772       Opcode = X86ISD::VPERMV;
8773     break;
8774   }
8775   if (!Opcode)
8776     return SDValue();
8777 
8778   assert((VT.getSizeInBits() == ShuffleVT.getSizeInBits()) &&
8779          (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits()) == 0 &&
8780          "Illegal variable permute shuffle type");
8781 
8782   uint64_t Scale = VT.getScalarSizeInBits() / ShuffleVT.getScalarSizeInBits();
8783   if (Scale > 1)
8784     IndicesVec = ScaleIndices(IndicesVec, Scale);
8785 
8786   EVT ShuffleIdxVT = EVT(ShuffleVT).changeVectorElementTypeToInteger();
8787   IndicesVec = DAG.getBitcast(ShuffleIdxVT, IndicesVec);
8788 
8789   SrcVec = DAG.getBitcast(ShuffleVT, SrcVec);
8790   SDValue Res = Opcode == X86ISD::VPERMV
8791                     ? DAG.getNode(Opcode, DL, ShuffleVT, IndicesVec, SrcVec)
8792                     : DAG.getNode(Opcode, DL, ShuffleVT, SrcVec, IndicesVec);
8793   return DAG.getBitcast(VT, Res);
8794 }
8795 
8796 // Tries to lower a BUILD_VECTOR composed of extract-extract chains that can be
8797 // reasoned to be a permutation of a vector by indices in a non-constant vector.
8798 // (build_vector (extract_elt V, (extract_elt I, 0)),
8799 //               (extract_elt V, (extract_elt I, 1)),
8800 //                    ...
8801 // ->
8802 // (vpermv I, V)
8803 //
8804 // TODO: Handle undefs
8805 // TODO: Utilize pshufb and zero mask blending to support more efficient
8806 // construction of vectors with constant-0 elements.
8807 static SDValue
LowerBUILD_VECTORAsVariablePermute(SDValue V,SelectionDAG & DAG,const X86Subtarget & Subtarget)8808 LowerBUILD_VECTORAsVariablePermute(SDValue V, SelectionDAG &DAG,
8809                                    const X86Subtarget &Subtarget) {
8810   SDValue SrcVec, IndicesVec;
8811   // Check for a match of the permute source vector and permute index elements.
8812   // This is done by checking that the i-th build_vector operand is of the form:
8813   // (extract_elt SrcVec, (extract_elt IndicesVec, i)).
8814   for (unsigned Idx = 0, E = V.getNumOperands(); Idx != E; ++Idx) {
8815     SDValue Op = V.getOperand(Idx);
8816     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8817       return SDValue();
8818 
8819     // If this is the first extract encountered in V, set the source vector,
8820     // otherwise verify the extract is from the previously defined source
8821     // vector.
8822     if (!SrcVec)
8823       SrcVec = Op.getOperand(0);
8824     else if (SrcVec != Op.getOperand(0))
8825       return SDValue();
8826     SDValue ExtractedIndex = Op->getOperand(1);
8827     // Peek through extends.
8828     if (ExtractedIndex.getOpcode() == ISD::ZERO_EXTEND ||
8829         ExtractedIndex.getOpcode() == ISD::SIGN_EXTEND)
8830       ExtractedIndex = ExtractedIndex.getOperand(0);
8831     if (ExtractedIndex.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8832       return SDValue();
8833 
8834     // If this is the first extract from the index vector candidate, set the
8835     // indices vector, otherwise verify the extract is from the previously
8836     // defined indices vector.
8837     if (!IndicesVec)
8838       IndicesVec = ExtractedIndex.getOperand(0);
8839     else if (IndicesVec != ExtractedIndex.getOperand(0))
8840       return SDValue();
8841 
8842     auto *PermIdx = dyn_cast<ConstantSDNode>(ExtractedIndex.getOperand(1));
8843     if (!PermIdx || PermIdx->getZExtValue() != Idx)
8844       return SDValue();
8845   }
8846 
8847   SDLoc DL(V);
8848   MVT VT = V.getSimpleValueType();
8849   return createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
8850 }
8851 
8852 SDValue
LowerBUILD_VECTOR(SDValue Op,SelectionDAG & DAG) const8853 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
8854   SDLoc dl(Op);
8855 
8856   MVT VT = Op.getSimpleValueType();
8857   MVT EltVT = VT.getVectorElementType();
8858   unsigned NumElems = Op.getNumOperands();
8859 
8860   // Generate vectors for predicate vectors.
8861   if (VT.getVectorElementType() == MVT::i1 && Subtarget.hasAVX512())
8862     return LowerBUILD_VECTORvXi1(Op, DAG, Subtarget);
8863 
8864   if (SDValue VectorConstant = materializeVectorConstant(Op, DAG, Subtarget))
8865     return VectorConstant;
8866 
8867   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
8868   if (SDValue AddSub = lowerToAddSubOrFMAddSub(BV, Subtarget, DAG))
8869     return AddSub;
8870   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
8871     return HorizontalOp;
8872   if (SDValue Broadcast = lowerBuildVectorAsBroadcast(BV, Subtarget, DAG))
8873     return Broadcast;
8874   if (SDValue BitOp = lowerBuildVectorToBitOp(BV, DAG))
8875     return BitOp;
8876 
8877   unsigned EVTBits = EltVT.getSizeInBits();
8878 
8879   unsigned NumZero  = 0;
8880   unsigned NumNonZero = 0;
8881   uint64_t NonZeros = 0;
8882   bool IsAllConstants = true;
8883   SmallSet<SDValue, 8> Values;
8884   unsigned NumConstants = NumElems;
8885   for (unsigned i = 0; i < NumElems; ++i) {
8886     SDValue Elt = Op.getOperand(i);
8887     if (Elt.isUndef())
8888       continue;
8889     Values.insert(Elt);
8890     if (!isa<ConstantSDNode>(Elt) && !isa<ConstantFPSDNode>(Elt)) {
8891       IsAllConstants = false;
8892       NumConstants--;
8893     }
8894     if (X86::isZeroNode(Elt))
8895       NumZero++;
8896     else {
8897       assert(i < sizeof(NonZeros) * 8); // Make sure the shift is within range.
8898       NonZeros |= ((uint64_t)1 << i);
8899       NumNonZero++;
8900     }
8901   }
8902 
8903   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
8904   if (NumNonZero == 0)
8905     return DAG.getUNDEF(VT);
8906 
8907   // If we are inserting one variable into a vector of non-zero constants, try
8908   // to avoid loading each constant element as a scalar. Load the constants as a
8909   // vector and then insert the variable scalar element. If insertion is not
8910   // supported, fall back to a shuffle to get the scalar blended with the
8911   // constants. Insertion into a zero vector is handled as a special-case
8912   // somewhere below here.
8913   if (NumConstants == NumElems - 1 && NumNonZero != 1 &&
8914       (isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT) ||
8915        isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))) {
8916     // Create an all-constant vector. The variable element in the old
8917     // build vector is replaced by undef in the constant vector. Save the
8918     // variable scalar element and its index for use in the insertelement.
8919     LLVMContext &Context = *DAG.getContext();
8920     Type *EltType = Op.getValueType().getScalarType().getTypeForEVT(Context);
8921     SmallVector<Constant *, 16> ConstVecOps(NumElems, UndefValue::get(EltType));
8922     SDValue VarElt;
8923     SDValue InsIndex;
8924     for (unsigned i = 0; i != NumElems; ++i) {
8925       SDValue Elt = Op.getOperand(i);
8926       if (auto *C = dyn_cast<ConstantSDNode>(Elt))
8927         ConstVecOps[i] = ConstantInt::get(Context, C->getAPIntValue());
8928       else if (auto *C = dyn_cast<ConstantFPSDNode>(Elt))
8929         ConstVecOps[i] = ConstantFP::get(Context, C->getValueAPF());
8930       else if (!Elt.isUndef()) {
8931         assert(!VarElt.getNode() && !InsIndex.getNode() &&
8932                "Expected one variable element in this vector");
8933         VarElt = Elt;
8934         InsIndex = DAG.getConstant(i, dl, getVectorIdxTy(DAG.getDataLayout()));
8935       }
8936     }
8937     Constant *CV = ConstantVector::get(ConstVecOps);
8938     SDValue DAGConstVec = DAG.getConstantPool(CV, VT);
8939 
8940     // The constants we just created may not be legal (eg, floating point). We
8941     // must lower the vector right here because we can not guarantee that we'll
8942     // legalize it before loading it. This is also why we could not just create
8943     // a new build vector here. If the build vector contains illegal constants,
8944     // it could get split back up into a series of insert elements.
8945     // TODO: Improve this by using shorter loads with broadcast/VZEXT_LOAD.
8946     SDValue LegalDAGConstVec = LowerConstantPool(DAGConstVec, DAG);
8947     MachineFunction &MF = DAG.getMachineFunction();
8948     MachinePointerInfo MPI = MachinePointerInfo::getConstantPool(MF);
8949     SDValue Ld = DAG.getLoad(VT, dl, DAG.getEntryNode(), LegalDAGConstVec, MPI);
8950     unsigned InsertC = cast<ConstantSDNode>(InsIndex)->getZExtValue();
8951     unsigned NumEltsInLow128Bits = 128 / VT.getScalarSizeInBits();
8952     if (InsertC < NumEltsInLow128Bits)
8953       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ld, VarElt, InsIndex);
8954 
8955     // There's no good way to insert into the high elements of a >128-bit
8956     // vector, so use shuffles to avoid an extract/insert sequence.
8957     assert(VT.getSizeInBits() > 128 && "Invalid insertion index?");
8958     assert(Subtarget.hasAVX() && "Must have AVX with >16-byte vector");
8959     SmallVector<int, 8> ShuffleMask;
8960     unsigned NumElts = VT.getVectorNumElements();
8961     for (unsigned i = 0; i != NumElts; ++i)
8962       ShuffleMask.push_back(i == InsertC ? NumElts : i);
8963     SDValue S2V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, VarElt);
8964     return DAG.getVectorShuffle(VT, dl, Ld, S2V, ShuffleMask);
8965   }
8966 
8967   // Special case for single non-zero, non-undef, element.
8968   if (NumNonZero == 1) {
8969     unsigned Idx = countTrailingZeros(NonZeros);
8970     SDValue Item = Op.getOperand(Idx);
8971 
8972     // If we have a constant or non-constant insertion into the low element of
8973     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
8974     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
8975     // depending on what the source datatype is.
8976     if (Idx == 0) {
8977       if (NumZero == 0)
8978         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
8979 
8980       if (EltVT == MVT::i32 || EltVT == MVT::f32 || EltVT == MVT::f64 ||
8981           (EltVT == MVT::i64 && Subtarget.is64Bit())) {
8982         assert((VT.is128BitVector() || VT.is256BitVector() ||
8983                 VT.is512BitVector()) &&
8984                "Expected an SSE value type!");
8985         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
8986         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
8987         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
8988       }
8989 
8990       // We can't directly insert an i8 or i16 into a vector, so zero extend
8991       // it to i32 first.
8992       if (EltVT == MVT::i16 || EltVT == MVT::i8) {
8993         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
8994         if (VT.getSizeInBits() >= 256) {
8995           MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits()/32);
8996           if (Subtarget.hasAVX()) {
8997             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, Item);
8998             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
8999           } else {
9000             // Without AVX, we need to extend to a 128-bit vector and then
9001             // insert into the 256-bit vector.
9002             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
9003             SDValue ZeroVec = getZeroVector(ShufVT, Subtarget, DAG, dl);
9004             Item = insert128BitVector(ZeroVec, Item, 0, DAG, dl);
9005           }
9006         } else {
9007           assert(VT.is128BitVector() && "Expected an SSE value type!");
9008           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
9009           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
9010         }
9011         return DAG.getBitcast(VT, Item);
9012       }
9013     }
9014 
9015     // Is it a vector logical left shift?
9016     if (NumElems == 2 && Idx == 1 &&
9017         X86::isZeroNode(Op.getOperand(0)) &&
9018         !X86::isZeroNode(Op.getOperand(1))) {
9019       unsigned NumBits = VT.getSizeInBits();
9020       return getVShift(true, VT,
9021                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9022                                    VT, Op.getOperand(1)),
9023                        NumBits/2, DAG, *this, dl);
9024     }
9025 
9026     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
9027       return SDValue();
9028 
9029     // Otherwise, if this is a vector with i32 or f32 elements, and the element
9030     // is a non-constant being inserted into an element other than the low one,
9031     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
9032     // movd/movss) to move this into the low element, then shuffle it into
9033     // place.
9034     if (EVTBits == 32) {
9035       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
9036       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
9037     }
9038   }
9039 
9040   // Splat is obviously ok. Let legalizer expand it to a shuffle.
9041   if (Values.size() == 1) {
9042     if (EVTBits == 32) {
9043       // Instead of a shuffle like this:
9044       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
9045       // Check if it's possible to issue this instead.
9046       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
9047       unsigned Idx = countTrailingZeros(NonZeros);
9048       SDValue Item = Op.getOperand(Idx);
9049       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
9050         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
9051     }
9052     return SDValue();
9053   }
9054 
9055   // A vector full of immediates; various special cases are already
9056   // handled, so this is best done with a single constant-pool load.
9057   if (IsAllConstants)
9058     return SDValue();
9059 
9060   if (SDValue V = LowerBUILD_VECTORAsVariablePermute(Op, DAG, Subtarget))
9061       return V;
9062 
9063   // See if we can use a vector load to get all of the elements.
9064   {
9065     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElems);
9066     if (SDValue LD =
9067             EltsFromConsecutiveLoads(VT, Ops, dl, DAG, Subtarget, false))
9068       return LD;
9069   }
9070 
9071   // If this is a splat of pairs of 32-bit elements, we can use a narrower
9072   // build_vector and broadcast it.
9073   // TODO: We could probably generalize this more.
9074   if (Subtarget.hasAVX2() && EVTBits == 32 && Values.size() == 2) {
9075     SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
9076                        DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
9077     auto CanSplat = [](SDValue Op, unsigned NumElems, ArrayRef<SDValue> Ops) {
9078       // Make sure all the even/odd operands match.
9079       for (unsigned i = 2; i != NumElems; ++i)
9080         if (Ops[i % 2] != Op.getOperand(i))
9081           return false;
9082       return true;
9083     };
9084     if (CanSplat(Op, NumElems, Ops)) {
9085       MVT WideEltVT = VT.isFloatingPoint() ? MVT::f64 : MVT::i64;
9086       MVT NarrowVT = MVT::getVectorVT(EltVT, 4);
9087       // Create a new build vector and cast to v2i64/v2f64.
9088       SDValue NewBV = DAG.getBitcast(MVT::getVectorVT(WideEltVT, 2),
9089                                      DAG.getBuildVector(NarrowVT, dl, Ops));
9090       // Broadcast from v2i64/v2f64 and cast to final VT.
9091       MVT BcastVT = MVT::getVectorVT(WideEltVT, NumElems/2);
9092       return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, dl, BcastVT,
9093                                             NewBV));
9094     }
9095   }
9096 
9097   // For AVX-length vectors, build the individual 128-bit pieces and use
9098   // shuffles to put them in place.
9099   if (VT.getSizeInBits() > 128) {
9100     MVT HVT = MVT::getVectorVT(EltVT, NumElems/2);
9101 
9102     // Build both the lower and upper subvector.
9103     SDValue Lower =
9104         DAG.getBuildVector(HVT, dl, Op->ops().slice(0, NumElems / 2));
9105     SDValue Upper = DAG.getBuildVector(
9106         HVT, dl, Op->ops().slice(NumElems / 2, NumElems /2));
9107 
9108     // Recreate the wider vector with the lower and upper part.
9109     return concatSubVectors(Lower, Upper, VT, NumElems, DAG, dl,
9110                             VT.getSizeInBits() / 2);
9111   }
9112 
9113   // Let legalizer expand 2-wide build_vectors.
9114   if (EVTBits == 64) {
9115     if (NumNonZero == 1) {
9116       // One half is zero or undef.
9117       unsigned Idx = countTrailingZeros(NonZeros);
9118       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
9119                                Op.getOperand(Idx));
9120       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
9121     }
9122     return SDValue();
9123   }
9124 
9125   // If element VT is < 32 bits, convert it to inserts into a zero vector.
9126   if (EVTBits == 8 && NumElems == 16)
9127     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
9128                                           DAG, Subtarget))
9129       return V;
9130 
9131   if (EVTBits == 16 && NumElems == 8)
9132     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
9133                                           DAG, Subtarget))
9134       return V;
9135 
9136   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
9137   if (EVTBits == 32 && NumElems == 4)
9138     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget))
9139       return V;
9140 
9141   // If element VT is == 32 bits, turn it into a number of shuffles.
9142   if (NumElems == 4 && NumZero > 0) {
9143     SmallVector<SDValue, 8> Ops(NumElems);
9144     for (unsigned i = 0; i < 4; ++i) {
9145       bool isZero = !(NonZeros & (1ULL << i));
9146       if (isZero)
9147         Ops[i] = getZeroVector(VT, Subtarget, DAG, dl);
9148       else
9149         Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
9150     }
9151 
9152     for (unsigned i = 0; i < 2; ++i) {
9153       switch ((NonZeros >> (i*2)) & 0x3) {
9154         default: llvm_unreachable("Unexpected NonZero count");
9155         case 0:
9156           Ops[i] = Ops[i*2];  // Must be a zero vector.
9157           break;
9158         case 1:
9159           Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2+1], Ops[i*2]);
9160           break;
9161         case 2:
9162           Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
9163           break;
9164         case 3:
9165           Ops[i] = getUnpackl(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
9166           break;
9167       }
9168     }
9169 
9170     bool Reverse1 = (NonZeros & 0x3) == 2;
9171     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
9172     int MaskVec[] = {
9173       Reverse1 ? 1 : 0,
9174       Reverse1 ? 0 : 1,
9175       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
9176       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
9177     };
9178     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], MaskVec);
9179   }
9180 
9181   assert(Values.size() > 1 && "Expected non-undef and non-splat vector");
9182 
9183   // Check for a build vector from mostly shuffle plus few inserting.
9184   if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
9185     return Sh;
9186 
9187   // For SSE 4.1, use insertps to put the high elements into the low element.
9188   if (Subtarget.hasSSE41()) {
9189     SDValue Result;
9190     if (!Op.getOperand(0).isUndef())
9191       Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
9192     else
9193       Result = DAG.getUNDEF(VT);
9194 
9195     for (unsigned i = 1; i < NumElems; ++i) {
9196       if (Op.getOperand(i).isUndef()) continue;
9197       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
9198                            Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
9199     }
9200     return Result;
9201   }
9202 
9203   // Otherwise, expand into a number of unpckl*, start by extending each of
9204   // our (non-undef) elements to the full vector width with the element in the
9205   // bottom slot of the vector (which generates no code for SSE).
9206   SmallVector<SDValue, 8> Ops(NumElems);
9207   for (unsigned i = 0; i < NumElems; ++i) {
9208     if (!Op.getOperand(i).isUndef())
9209       Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
9210     else
9211       Ops[i] = DAG.getUNDEF(VT);
9212   }
9213 
9214   // Next, we iteratively mix elements, e.g. for v4f32:
9215   //   Step 1: unpcklps 0, 1 ==> X: <?, ?, 1, 0>
9216   //         : unpcklps 2, 3 ==> Y: <?, ?, 3, 2>
9217   //   Step 2: unpcklpd X, Y ==>    <3, 2, 1, 0>
9218   for (unsigned Scale = 1; Scale < NumElems; Scale *= 2) {
9219     // Generate scaled UNPCKL shuffle mask.
9220     SmallVector<int, 16> Mask;
9221     for(unsigned i = 0; i != Scale; ++i)
9222       Mask.push_back(i);
9223     for (unsigned i = 0; i != Scale; ++i)
9224       Mask.push_back(NumElems+i);
9225     Mask.append(NumElems - Mask.size(), SM_SentinelUndef);
9226 
9227     for (unsigned i = 0, e = NumElems / (2 * Scale); i != e; ++i)
9228       Ops[i] = DAG.getVectorShuffle(VT, dl, Ops[2*i], Ops[(2*i)+1], Mask);
9229   }
9230   return Ops[0];
9231 }
9232 
9233 // 256-bit AVX can use the vinsertf128 instruction
9234 // to create 256-bit vectors from two other 128-bit ones.
9235 // TODO: Detect subvector broadcast here instead of DAG combine?
LowerAVXCONCAT_VECTORS(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)9236 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
9237                                       const X86Subtarget &Subtarget) {
9238   SDLoc dl(Op);
9239   MVT ResVT = Op.getSimpleValueType();
9240 
9241   assert((ResVT.is256BitVector() ||
9242           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
9243 
9244   unsigned NumOperands = Op.getNumOperands();
9245   unsigned NumZero = 0;
9246   unsigned NumNonZero = 0;
9247   unsigned NonZeros = 0;
9248   for (unsigned i = 0; i != NumOperands; ++i) {
9249     SDValue SubVec = Op.getOperand(i);
9250     if (SubVec.isUndef())
9251       continue;
9252     if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
9253       ++NumZero;
9254     else {
9255       assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
9256       NonZeros |= 1 << i;
9257       ++NumNonZero;
9258     }
9259   }
9260 
9261   // If we have more than 2 non-zeros, build each half separately.
9262   if (NumNonZero > 2) {
9263     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
9264                                   ResVT.getVectorNumElements()/2);
9265     ArrayRef<SDUse> Ops = Op->ops();
9266     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9267                              Ops.slice(0, NumOperands/2));
9268     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9269                              Ops.slice(NumOperands/2));
9270     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
9271   }
9272 
9273   // Otherwise, build it up through insert_subvectors.
9274   SDValue Vec = NumZero ? getZeroVector(ResVT, Subtarget, DAG, dl)
9275                         : DAG.getUNDEF(ResVT);
9276 
9277   MVT SubVT = Op.getOperand(0).getSimpleValueType();
9278   unsigned NumSubElems = SubVT.getVectorNumElements();
9279   for (unsigned i = 0; i != NumOperands; ++i) {
9280     if ((NonZeros & (1 << i)) == 0)
9281       continue;
9282 
9283     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec,
9284                       Op.getOperand(i),
9285                       DAG.getIntPtrConstant(i * NumSubElems, dl));
9286   }
9287 
9288   return Vec;
9289 }
9290 
9291 // Return true if all the operands of the given CONCAT_VECTORS node are zeros
9292 // except for the first one. (CONCAT_VECTORS Op, 0, 0,...,0)
isExpandWithZeros(const SDValue & Op)9293 static bool isExpandWithZeros(const SDValue &Op) {
9294   assert(Op.getOpcode() == ISD::CONCAT_VECTORS &&
9295          "Expand with zeros only possible in CONCAT_VECTORS nodes!");
9296 
9297   for (unsigned i = 1; i < Op.getNumOperands(); i++)
9298     if (!ISD::isBuildVectorAllZeros(Op.getOperand(i).getNode()))
9299       return false;
9300 
9301   return true;
9302 }
9303 
9304 // Returns true if the given node is a type promotion (by concatenating i1
9305 // zeros) of the result of a node that already zeros all upper bits of
9306 // k-register.
isTypePromotionOfi1ZeroUpBits(SDValue Op)9307 static SDValue isTypePromotionOfi1ZeroUpBits(SDValue Op) {
9308   unsigned Opc = Op.getOpcode();
9309 
9310   assert(Opc == ISD::CONCAT_VECTORS &&
9311          Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
9312          "Unexpected node to check for type promotion!");
9313 
9314   // As long as we are concatenating zeros to the upper part of a previous node
9315   // result, climb up the tree until a node with different opcode is
9316   // encountered
9317   while (Opc == ISD::INSERT_SUBVECTOR || Opc == ISD::CONCAT_VECTORS) {
9318     if (Opc == ISD::INSERT_SUBVECTOR) {
9319       if (ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()) &&
9320           Op.getConstantOperandVal(2) == 0)
9321         Op = Op.getOperand(1);
9322       else
9323         return SDValue();
9324     } else { // Opc == ISD::CONCAT_VECTORS
9325       if (isExpandWithZeros(Op))
9326         Op = Op.getOperand(0);
9327       else
9328         return SDValue();
9329     }
9330     Opc = Op.getOpcode();
9331   }
9332 
9333   // Check if the first inserted node zeroes the upper bits, or an 'and' result
9334   // of a node that zeros the upper bits (its masked version).
9335   if (isMaskedZeroUpperBitsvXi1(Op.getOpcode()) ||
9336       (Op.getOpcode() == ISD::AND &&
9337        (isMaskedZeroUpperBitsvXi1(Op.getOperand(0).getOpcode()) ||
9338         isMaskedZeroUpperBitsvXi1(Op.getOperand(1).getOpcode())))) {
9339     return Op;
9340   }
9341 
9342   return SDValue();
9343 }
9344 
9345 // TODO: Merge this with LowerAVXCONCAT_VECTORS?
LowerCONCAT_VECTORSvXi1(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)9346 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
9347                                        const X86Subtarget &Subtarget,
9348                                        SelectionDAG & DAG) {
9349   SDLoc dl(Op);
9350   MVT ResVT = Op.getSimpleValueType();
9351   unsigned NumOperands = Op.getNumOperands();
9352 
9353   assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
9354          "Unexpected number of operands in CONCAT_VECTORS");
9355 
9356   // If this node promotes - by concatenating zeroes - the type of the result
9357   // of a node with instruction that zeroes all upper (irrelevant) bits of the
9358   // output register, mark it as legal and catch the pattern in instruction
9359   // selection to avoid emitting extra instructions (for zeroing upper bits).
9360   if (SDValue Promoted = isTypePromotionOfi1ZeroUpBits(Op))
9361     return widenSubVector(ResVT, Promoted, true, Subtarget, DAG, dl);
9362 
9363   unsigned NumZero = 0;
9364   unsigned NumNonZero = 0;
9365   uint64_t NonZeros = 0;
9366   for (unsigned i = 0; i != NumOperands; ++i) {
9367     SDValue SubVec = Op.getOperand(i);
9368     if (SubVec.isUndef())
9369       continue;
9370     if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
9371       ++NumZero;
9372     else {
9373       assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
9374       NonZeros |= (uint64_t)1 << i;
9375       ++NumNonZero;
9376     }
9377   }
9378 
9379 
9380   // If there are zero or one non-zeros we can handle this very simply.
9381   if (NumNonZero <= 1) {
9382     SDValue Vec = NumZero ? getZeroVector(ResVT, Subtarget, DAG, dl)
9383                           : DAG.getUNDEF(ResVT);
9384     if (!NumNonZero)
9385       return Vec;
9386     unsigned Idx = countTrailingZeros(NonZeros);
9387     SDValue SubVec = Op.getOperand(Idx);
9388     unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
9389     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, SubVec,
9390                        DAG.getIntPtrConstant(Idx * SubVecNumElts, dl));
9391   }
9392 
9393   if (NumOperands > 2) {
9394     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
9395                                   ResVT.getVectorNumElements()/2);
9396     ArrayRef<SDUse> Ops = Op->ops();
9397     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9398                              Ops.slice(0, NumOperands/2));
9399     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9400                              Ops.slice(NumOperands/2));
9401     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
9402   }
9403 
9404   assert(NumNonZero == 2 && "Simple cases not handled?");
9405 
9406   if (ResVT.getVectorNumElements() >= 16)
9407     return Op; // The operation is legal with KUNPCK
9408 
9409   SDValue Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT,
9410                             DAG.getUNDEF(ResVT), Op.getOperand(0),
9411                             DAG.getIntPtrConstant(0, dl));
9412   unsigned NumElems = ResVT.getVectorNumElements();
9413   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, Op.getOperand(1),
9414                      DAG.getIntPtrConstant(NumElems/2, dl));
9415 }
9416 
LowerCONCAT_VECTORS(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)9417 static SDValue LowerCONCAT_VECTORS(SDValue Op,
9418                                    const X86Subtarget &Subtarget,
9419                                    SelectionDAG &DAG) {
9420   MVT VT = Op.getSimpleValueType();
9421   if (VT.getVectorElementType() == MVT::i1)
9422     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
9423 
9424   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
9425          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
9426           Op.getNumOperands() == 4)));
9427 
9428   // AVX can use the vinsertf128 instruction to create 256-bit vectors
9429   // from two other 128-bit ones.
9430 
9431   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
9432   return LowerAVXCONCAT_VECTORS(Op, DAG, Subtarget);
9433 }
9434 
9435 //===----------------------------------------------------------------------===//
9436 // Vector shuffle lowering
9437 //
9438 // This is an experimental code path for lowering vector shuffles on x86. It is
9439 // designed to handle arbitrary vector shuffles and blends, gracefully
9440 // degrading performance as necessary. It works hard to recognize idiomatic
9441 // shuffles and lower them to optimal instruction patterns without leaving
9442 // a framework that allows reasonably efficient handling of all vector shuffle
9443 // patterns.
9444 //===----------------------------------------------------------------------===//
9445 
9446 /// Tiny helper function to identify a no-op mask.
9447 ///
9448 /// This is a somewhat boring predicate function. It checks whether the mask
9449 /// array input, which is assumed to be a single-input shuffle mask of the kind
9450 /// used by the X86 shuffle instructions (not a fully general
9451 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
9452 /// in-place shuffle are 'no-op's.
isNoopShuffleMask(ArrayRef<int> Mask)9453 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
9454   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
9455     assert(Mask[i] >= -1 && "Out of bound mask element!");
9456     if (Mask[i] >= 0 && Mask[i] != i)
9457       return false;
9458   }
9459   return true;
9460 }
9461 
9462 /// Test whether there are elements crossing 128-bit lanes in this
9463 /// shuffle mask.
9464 ///
9465 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
9466 /// and we routinely test for these.
is128BitLaneCrossingShuffleMask(MVT VT,ArrayRef<int> Mask)9467 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
9468   int LaneSize = 128 / VT.getScalarSizeInBits();
9469   int Size = Mask.size();
9470   for (int i = 0; i < Size; ++i)
9471     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9472       return true;
9473   return false;
9474 }
9475 
9476 /// Test whether a shuffle mask is equivalent within each sub-lane.
9477 ///
9478 /// This checks a shuffle mask to see if it is performing the same
9479 /// lane-relative shuffle in each sub-lane. This trivially implies
9480 /// that it is also not lane-crossing. It may however involve a blend from the
9481 /// same lane of a second vector.
9482 ///
9483 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
9484 /// non-trivial to compute in the face of undef lanes. The representation is
9485 /// suitable for use with existing 128-bit shuffles as entries from the second
9486 /// vector have been remapped to [LaneSize, 2*LaneSize).
isRepeatedShuffleMask(unsigned LaneSizeInBits,MVT VT,ArrayRef<int> Mask,SmallVectorImpl<int> & RepeatedMask)9487 static bool isRepeatedShuffleMask(unsigned LaneSizeInBits, MVT VT,
9488                                   ArrayRef<int> Mask,
9489                                   SmallVectorImpl<int> &RepeatedMask) {
9490   auto LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
9491   RepeatedMask.assign(LaneSize, -1);
9492   int Size = Mask.size();
9493   for (int i = 0; i < Size; ++i) {
9494     assert(Mask[i] == SM_SentinelUndef || Mask[i] >= 0);
9495     if (Mask[i] < 0)
9496       continue;
9497     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
9498       // This entry crosses lanes, so there is no way to model this shuffle.
9499       return false;
9500 
9501     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
9502     // Adjust second vector indices to start at LaneSize instead of Size.
9503     int LocalM = Mask[i] < Size ? Mask[i] % LaneSize
9504                                 : Mask[i] % LaneSize + LaneSize;
9505     if (RepeatedMask[i % LaneSize] < 0)
9506       // This is the first non-undef entry in this slot of a 128-bit lane.
9507       RepeatedMask[i % LaneSize] = LocalM;
9508     else if (RepeatedMask[i % LaneSize] != LocalM)
9509       // Found a mismatch with the repeated mask.
9510       return false;
9511   }
9512   return true;
9513 }
9514 
9515 /// Test whether a shuffle mask is equivalent within each 128-bit lane.
9516 static bool
is128BitLaneRepeatedShuffleMask(MVT VT,ArrayRef<int> Mask,SmallVectorImpl<int> & RepeatedMask)9517 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
9518                                 SmallVectorImpl<int> &RepeatedMask) {
9519   return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
9520 }
9521 
9522 static bool
is128BitLaneRepeatedShuffleMask(MVT VT,ArrayRef<int> Mask)9523 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask) {
9524   SmallVector<int, 32> RepeatedMask;
9525   return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
9526 }
9527 
9528 /// Test whether a shuffle mask is equivalent within each 256-bit lane.
9529 static bool
is256BitLaneRepeatedShuffleMask(MVT VT,ArrayRef<int> Mask,SmallVectorImpl<int> & RepeatedMask)9530 is256BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
9531                                 SmallVectorImpl<int> &RepeatedMask) {
9532   return isRepeatedShuffleMask(256, VT, Mask, RepeatedMask);
9533 }
9534 
9535 /// Test whether a target shuffle mask is equivalent within each sub-lane.
9536 /// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
isRepeatedTargetShuffleMask(unsigned LaneSizeInBits,MVT VT,ArrayRef<int> Mask,SmallVectorImpl<int> & RepeatedMask)9537 static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits, MVT VT,
9538                                         ArrayRef<int> Mask,
9539                                         SmallVectorImpl<int> &RepeatedMask) {
9540   int LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
9541   RepeatedMask.assign(LaneSize, SM_SentinelUndef);
9542   int Size = Mask.size();
9543   for (int i = 0; i < Size; ++i) {
9544     assert(isUndefOrZero(Mask[i]) || (Mask[i] >= 0));
9545     if (Mask[i] == SM_SentinelUndef)
9546       continue;
9547     if (Mask[i] == SM_SentinelZero) {
9548       if (!isUndefOrZero(RepeatedMask[i % LaneSize]))
9549         return false;
9550       RepeatedMask[i % LaneSize] = SM_SentinelZero;
9551       continue;
9552     }
9553     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
9554       // This entry crosses lanes, so there is no way to model this shuffle.
9555       return false;
9556 
9557     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
9558     // Adjust second vector indices to start at LaneSize instead of Size.
9559     int LocalM =
9560         Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + LaneSize;
9561     if (RepeatedMask[i % LaneSize] == SM_SentinelUndef)
9562       // This is the first non-undef entry in this slot of a 128-bit lane.
9563       RepeatedMask[i % LaneSize] = LocalM;
9564     else if (RepeatedMask[i % LaneSize] != LocalM)
9565       // Found a mismatch with the repeated mask.
9566       return false;
9567   }
9568   return true;
9569 }
9570 
9571 /// Checks whether a shuffle mask is equivalent to an explicit list of
9572 /// arguments.
9573 ///
9574 /// This is a fast way to test a shuffle mask against a fixed pattern:
9575 ///
9576 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
9577 ///
9578 /// It returns true if the mask is exactly as wide as the argument list, and
9579 /// each element of the mask is either -1 (signifying undef) or the value given
9580 /// in the argument.
isShuffleEquivalent(SDValue V1,SDValue V2,ArrayRef<int> Mask,ArrayRef<int> ExpectedMask)9581 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
9582                                 ArrayRef<int> ExpectedMask) {
9583   if (Mask.size() != ExpectedMask.size())
9584     return false;
9585 
9586   int Size = Mask.size();
9587 
9588   // If the values are build vectors, we can look through them to find
9589   // equivalent inputs that make the shuffles equivalent.
9590   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
9591   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
9592 
9593   for (int i = 0; i < Size; ++i) {
9594     assert(Mask[i] >= -1 && "Out of bound mask element!");
9595     if (Mask[i] >= 0 && Mask[i] != ExpectedMask[i]) {
9596       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
9597       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
9598       if (!MaskBV || !ExpectedBV ||
9599           MaskBV->getOperand(Mask[i] % Size) !=
9600               ExpectedBV->getOperand(ExpectedMask[i] % Size))
9601         return false;
9602     }
9603   }
9604 
9605   return true;
9606 }
9607 
9608 /// Checks whether a target shuffle mask is equivalent to an explicit pattern.
9609 ///
9610 /// The masks must be exactly the same width.
9611 ///
9612 /// If an element in Mask matches SM_SentinelUndef (-1) then the corresponding
9613 /// value in ExpectedMask is always accepted. Otherwise the indices must match.
9614 ///
9615 /// SM_SentinelZero is accepted as a valid negative index but must match in both.
isTargetShuffleEquivalent(ArrayRef<int> Mask,ArrayRef<int> ExpectedMask)9616 static bool isTargetShuffleEquivalent(ArrayRef<int> Mask,
9617                                       ArrayRef<int> ExpectedMask) {
9618   int Size = Mask.size();
9619   if (Size != (int)ExpectedMask.size())
9620     return false;
9621 
9622   for (int i = 0; i < Size; ++i)
9623     if (Mask[i] == SM_SentinelUndef)
9624       continue;
9625     else if (Mask[i] < 0 && Mask[i] != SM_SentinelZero)
9626       return false;
9627     else if (Mask[i] != ExpectedMask[i])
9628       return false;
9629 
9630   return true;
9631 }
9632 
9633 // Merges a general DAG shuffle mask and zeroable bit mask into a target shuffle
9634 // mask.
createTargetShuffleMask(ArrayRef<int> Mask,const APInt & Zeroable)9635 static SmallVector<int, 64> createTargetShuffleMask(ArrayRef<int> Mask,
9636                                                     const APInt &Zeroable) {
9637   int NumElts = Mask.size();
9638   assert(NumElts == (int)Zeroable.getBitWidth() && "Mismatch mask sizes");
9639 
9640   SmallVector<int, 64> TargetMask(NumElts, SM_SentinelUndef);
9641   for (int i = 0; i != NumElts; ++i) {
9642     int M = Mask[i];
9643     if (M == SM_SentinelUndef)
9644       continue;
9645     assert(0 <= M && M < (2 * NumElts) && "Out of range shuffle index");
9646     TargetMask[i] = (Zeroable[i] ? SM_SentinelZero : M);
9647   }
9648   return TargetMask;
9649 }
9650 
9651 // Attempt to create a shuffle mask from a VSELECT condition mask.
createShuffleMaskFromVSELECT(SmallVectorImpl<int> & Mask,SDValue Cond)9652 static bool createShuffleMaskFromVSELECT(SmallVectorImpl<int> &Mask,
9653                                          SDValue Cond) {
9654   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9655     return false;
9656 
9657   unsigned Size = Cond.getValueType().getVectorNumElements();
9658   Mask.resize(Size, SM_SentinelUndef);
9659 
9660   for (int i = 0; i != (int)Size; ++i) {
9661     SDValue CondElt = Cond.getOperand(i);
9662     Mask[i] = i;
9663     // Arbitrarily choose from the 2nd operand if the select condition element
9664     // is undef.
9665     // TODO: Can we do better by matching patterns such as even/odd?
9666     if (CondElt.isUndef() || isNullConstant(CondElt))
9667       Mask[i] += Size;
9668   }
9669 
9670   return true;
9671 }
9672 
9673 // Check if the shuffle mask is suitable for the AVX vpunpcklwd or vpunpckhwd
9674 // instructions.
isUnpackWdShuffleMask(ArrayRef<int> Mask,MVT VT)9675 static bool isUnpackWdShuffleMask(ArrayRef<int> Mask, MVT VT) {
9676   if (VT != MVT::v8i32 && VT != MVT::v8f32)
9677     return false;
9678 
9679   SmallVector<int, 8> Unpcklwd;
9680   createUnpackShuffleMask(MVT::v8i16, Unpcklwd, /* Lo = */ true,
9681                           /* Unary = */ false);
9682   SmallVector<int, 8> Unpckhwd;
9683   createUnpackShuffleMask(MVT::v8i16, Unpckhwd, /* Lo = */ false,
9684                           /* Unary = */ false);
9685   bool IsUnpackwdMask = (isTargetShuffleEquivalent(Mask, Unpcklwd) ||
9686                          isTargetShuffleEquivalent(Mask, Unpckhwd));
9687   return IsUnpackwdMask;
9688 }
9689 
9690 /// Get a 4-lane 8-bit shuffle immediate for a mask.
9691 ///
9692 /// This helper function produces an 8-bit shuffle immediate corresponding to
9693 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
9694 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
9695 /// example.
9696 ///
9697 /// NB: We rely heavily on "undef" masks preserving the input lane.
getV4X86ShuffleImm(ArrayRef<int> Mask)9698 static unsigned getV4X86ShuffleImm(ArrayRef<int> Mask) {
9699   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
9700   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
9701   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
9702   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
9703   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
9704 
9705   unsigned Imm = 0;
9706   Imm |= (Mask[0] < 0 ? 0 : Mask[0]) << 0;
9707   Imm |= (Mask[1] < 0 ? 1 : Mask[1]) << 2;
9708   Imm |= (Mask[2] < 0 ? 2 : Mask[2]) << 4;
9709   Imm |= (Mask[3] < 0 ? 3 : Mask[3]) << 6;
9710   return Imm;
9711 }
9712 
getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,const SDLoc & DL,SelectionDAG & DAG)9713 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, const SDLoc &DL,
9714                                           SelectionDAG &DAG) {
9715   return DAG.getConstant(getV4X86ShuffleImm(Mask), DL, MVT::i8);
9716 }
9717 
9718 /// Compute whether each element of a shuffle is zeroable.
9719 ///
9720 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
9721 /// Either it is an undef element in the shuffle mask, the element of the input
9722 /// referenced is undef, or the element of the input referenced is known to be
9723 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
9724 /// as many lanes with this technique as possible to simplify the remaining
9725 /// shuffle.
computeZeroableShuffleElements(ArrayRef<int> Mask,SDValue V1,SDValue V2)9726 static APInt computeZeroableShuffleElements(ArrayRef<int> Mask,
9727                                             SDValue V1, SDValue V2) {
9728   APInt Zeroable(Mask.size(), 0);
9729   V1 = peekThroughBitcasts(V1);
9730   V2 = peekThroughBitcasts(V2);
9731 
9732   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
9733   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
9734 
9735   int VectorSizeInBits = V1.getValueSizeInBits();
9736   int ScalarSizeInBits = VectorSizeInBits / Mask.size();
9737   assert(!(VectorSizeInBits % ScalarSizeInBits) && "Illegal shuffle mask size");
9738 
9739   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
9740     int M = Mask[i];
9741     // Handle the easy cases.
9742     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
9743       Zeroable.setBit(i);
9744       continue;
9745     }
9746 
9747     // Determine shuffle input and normalize the mask.
9748     SDValue V = M < Size ? V1 : V2;
9749     M %= Size;
9750 
9751     // Currently we can only search BUILD_VECTOR for UNDEF/ZERO elements.
9752     if (V.getOpcode() != ISD::BUILD_VECTOR)
9753       continue;
9754 
9755     // If the BUILD_VECTOR has fewer elements then the bitcasted portion of
9756     // the (larger) source element must be UNDEF/ZERO.
9757     if ((Size % V.getNumOperands()) == 0) {
9758       int Scale = Size / V->getNumOperands();
9759       SDValue Op = V.getOperand(M / Scale);
9760       if (Op.isUndef() || X86::isZeroNode(Op))
9761         Zeroable.setBit(i);
9762       else if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
9763         APInt Val = Cst->getAPIntValue();
9764         Val.lshrInPlace((M % Scale) * ScalarSizeInBits);
9765         Val = Val.getLoBits(ScalarSizeInBits);
9766         if (Val == 0)
9767           Zeroable.setBit(i);
9768       } else if (ConstantFPSDNode *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
9769         APInt Val = Cst->getValueAPF().bitcastToAPInt();
9770         Val.lshrInPlace((M % Scale) * ScalarSizeInBits);
9771         Val = Val.getLoBits(ScalarSizeInBits);
9772         if (Val == 0)
9773           Zeroable.setBit(i);
9774       }
9775       continue;
9776     }
9777 
9778     // If the BUILD_VECTOR has more elements then all the (smaller) source
9779     // elements must be UNDEF or ZERO.
9780     if ((V.getNumOperands() % Size) == 0) {
9781       int Scale = V->getNumOperands() / Size;
9782       bool AllZeroable = true;
9783       for (int j = 0; j < Scale; ++j) {
9784         SDValue Op = V.getOperand((M * Scale) + j);
9785         AllZeroable &= (Op.isUndef() || X86::isZeroNode(Op));
9786       }
9787       if (AllZeroable)
9788         Zeroable.setBit(i);
9789       continue;
9790     }
9791   }
9792 
9793   return Zeroable;
9794 }
9795 
9796 // The Shuffle result is as follow:
9797 // 0*a[0]0*a[1]...0*a[n] , n >=0 where a[] elements in a ascending order.
9798 // Each Zeroable's element correspond to a particular Mask's element.
9799 // As described in computeZeroableShuffleElements function.
9800 //
9801 // The function looks for a sub-mask that the nonzero elements are in
9802 // increasing order. If such sub-mask exist. The function returns true.
isNonZeroElementsInOrder(const APInt & Zeroable,ArrayRef<int> Mask,const EVT & VectorType,bool & IsZeroSideLeft)9803 static bool isNonZeroElementsInOrder(const APInt &Zeroable,
9804                                      ArrayRef<int> Mask, const EVT &VectorType,
9805                                      bool &IsZeroSideLeft) {
9806   int NextElement = -1;
9807   // Check if the Mask's nonzero elements are in increasing order.
9808   for (int i = 0, e = Mask.size(); i < e; i++) {
9809     // Checks if the mask's zeros elements are built from only zeros.
9810     assert(Mask[i] >= -1 && "Out of bound mask element!");
9811     if (Mask[i] < 0)
9812       return false;
9813     if (Zeroable[i])
9814       continue;
9815     // Find the lowest non zero element
9816     if (NextElement < 0) {
9817       NextElement = Mask[i] != 0 ? VectorType.getVectorNumElements() : 0;
9818       IsZeroSideLeft = NextElement != 0;
9819     }
9820     // Exit if the mask's non zero elements are not in increasing order.
9821     if (NextElement != Mask[i])
9822       return false;
9823     NextElement++;
9824   }
9825   return true;
9826 }
9827 
9828 /// Try to lower a shuffle with a single PSHUFB of V1 or V2.
lowerVectorShuffleWithPSHUFB(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)9829 static SDValue lowerVectorShuffleWithPSHUFB(const SDLoc &DL, MVT VT,
9830                                             ArrayRef<int> Mask, SDValue V1,
9831                                             SDValue V2,
9832                                             const APInt &Zeroable,
9833                                             const X86Subtarget &Subtarget,
9834                                             SelectionDAG &DAG) {
9835   int Size = Mask.size();
9836   int LaneSize = 128 / VT.getScalarSizeInBits();
9837   const int NumBytes = VT.getSizeInBits() / 8;
9838   const int NumEltBytes = VT.getScalarSizeInBits() / 8;
9839 
9840   assert((Subtarget.hasSSSE3() && VT.is128BitVector()) ||
9841          (Subtarget.hasAVX2() && VT.is256BitVector()) ||
9842          (Subtarget.hasBWI() && VT.is512BitVector()));
9843 
9844   SmallVector<SDValue, 64> PSHUFBMask(NumBytes);
9845   // Sign bit set in i8 mask means zero element.
9846   SDValue ZeroMask = DAG.getConstant(0x80, DL, MVT::i8);
9847 
9848   SDValue V;
9849   for (int i = 0; i < NumBytes; ++i) {
9850     int M = Mask[i / NumEltBytes];
9851     if (M < 0) {
9852       PSHUFBMask[i] = DAG.getUNDEF(MVT::i8);
9853       continue;
9854     }
9855     if (Zeroable[i / NumEltBytes]) {
9856       PSHUFBMask[i] = ZeroMask;
9857       continue;
9858     }
9859 
9860     // We can only use a single input of V1 or V2.
9861     SDValue SrcV = (M >= Size ? V2 : V1);
9862     if (V && V != SrcV)
9863       return SDValue();
9864     V = SrcV;
9865     M %= Size;
9866 
9867     // PSHUFB can't cross lanes, ensure this doesn't happen.
9868     if ((M / LaneSize) != ((i / NumEltBytes) / LaneSize))
9869       return SDValue();
9870 
9871     M = M % LaneSize;
9872     M = M * NumEltBytes + (i % NumEltBytes);
9873     PSHUFBMask[i] = DAG.getConstant(M, DL, MVT::i8);
9874   }
9875   assert(V && "Failed to find a source input");
9876 
9877   MVT I8VT = MVT::getVectorVT(MVT::i8, NumBytes);
9878   return DAG.getBitcast(
9879       VT, DAG.getNode(X86ISD::PSHUFB, DL, I8VT, DAG.getBitcast(I8VT, V),
9880                       DAG.getBuildVector(I8VT, DL, PSHUFBMask)));
9881 }
9882 
9883 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
9884                            const X86Subtarget &Subtarget, SelectionDAG &DAG,
9885                            const SDLoc &dl);
9886 
9887 // X86 has dedicated shuffle that can be lowered to VEXPAND
lowerVectorShuffleToEXPAND(const SDLoc & DL,MVT VT,const APInt & Zeroable,ArrayRef<int> Mask,SDValue & V1,SDValue & V2,SelectionDAG & DAG,const X86Subtarget & Subtarget)9888 static SDValue lowerVectorShuffleToEXPAND(const SDLoc &DL, MVT VT,
9889                                           const APInt &Zeroable,
9890                                           ArrayRef<int> Mask, SDValue &V1,
9891                                           SDValue &V2, SelectionDAG &DAG,
9892                                           const X86Subtarget &Subtarget) {
9893   bool IsLeftZeroSide = true;
9894   if (!isNonZeroElementsInOrder(Zeroable, Mask, V1.getValueType(),
9895                                 IsLeftZeroSide))
9896     return SDValue();
9897   unsigned VEXPANDMask = (~Zeroable).getZExtValue();
9898   MVT IntegerType =
9899       MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
9900   SDValue MaskNode = DAG.getConstant(VEXPANDMask, DL, IntegerType);
9901   unsigned NumElts = VT.getVectorNumElements();
9902   assert((NumElts == 4 || NumElts == 8 || NumElts == 16) &&
9903          "Unexpected number of vector elements");
9904   SDValue VMask = getMaskNode(MaskNode, MVT::getVectorVT(MVT::i1, NumElts),
9905                               Subtarget, DAG, DL);
9906   SDValue ZeroVector = getZeroVector(VT, Subtarget, DAG, DL);
9907   SDValue ExpandedVector = IsLeftZeroSide ? V2 : V1;
9908   return DAG.getSelect(DL, VT, VMask,
9909                        DAG.getNode(X86ISD::EXPAND, DL, VT, ExpandedVector),
9910                        ZeroVector);
9911 }
9912 
matchVectorShuffleWithUNPCK(MVT VT,SDValue & V1,SDValue & V2,unsigned & UnpackOpcode,bool IsUnary,ArrayRef<int> TargetMask,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)9913 static bool matchVectorShuffleWithUNPCK(MVT VT, SDValue &V1, SDValue &V2,
9914                                         unsigned &UnpackOpcode, bool IsUnary,
9915                                         ArrayRef<int> TargetMask,
9916                                         const SDLoc &DL, SelectionDAG &DAG,
9917                                         const X86Subtarget &Subtarget) {
9918   int NumElts = VT.getVectorNumElements();
9919 
9920   bool Undef1 = true, Undef2 = true, Zero1 = true, Zero2 = true;
9921   for (int i = 0; i != NumElts; i += 2) {
9922     int M1 = TargetMask[i + 0];
9923     int M2 = TargetMask[i + 1];
9924     Undef1 &= (SM_SentinelUndef == M1);
9925     Undef2 &= (SM_SentinelUndef == M2);
9926     Zero1 &= isUndefOrZero(M1);
9927     Zero2 &= isUndefOrZero(M2);
9928   }
9929   assert(!((Undef1 || Zero1) && (Undef2 || Zero2)) &&
9930          "Zeroable shuffle detected");
9931 
9932   // Attempt to match the target mask against the unpack lo/hi mask patterns.
9933   SmallVector<int, 64> Unpckl, Unpckh;
9934   createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, IsUnary);
9935   if (isTargetShuffleEquivalent(TargetMask, Unpckl)) {
9936     UnpackOpcode = X86ISD::UNPCKL;
9937     V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
9938     V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
9939     return true;
9940   }
9941 
9942   createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, IsUnary);
9943   if (isTargetShuffleEquivalent(TargetMask, Unpckh)) {
9944     UnpackOpcode = X86ISD::UNPCKH;
9945     V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
9946     V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
9947     return true;
9948   }
9949 
9950   // If an unary shuffle, attempt to match as an unpack lo/hi with zero.
9951   if (IsUnary && (Zero1 || Zero2)) {
9952     // Don't bother if we can blend instead.
9953     if ((Subtarget.hasSSE41() || VT == MVT::v2i64 || VT == MVT::v2f64) &&
9954         isSequentialOrUndefOrZeroInRange(TargetMask, 0, NumElts, 0))
9955       return false;
9956 
9957     bool MatchLo = true, MatchHi = true;
9958     for (int i = 0; (i != NumElts) && (MatchLo || MatchHi); ++i) {
9959       int M = TargetMask[i];
9960 
9961       // Ignore if the input is known to be zero or the index is undef.
9962       if ((((i & 1) == 0) && Zero1) || (((i & 1) == 1) && Zero2) ||
9963           (M == SM_SentinelUndef))
9964         continue;
9965 
9966       MatchLo &= (M == Unpckl[i]);
9967       MatchHi &= (M == Unpckh[i]);
9968     }
9969 
9970     if (MatchLo || MatchHi) {
9971       UnpackOpcode = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
9972       V2 = Zero2 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
9973       V1 = Zero1 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
9974       return true;
9975     }
9976   }
9977 
9978   // If a binary shuffle, commute and try again.
9979   if (!IsUnary) {
9980     ShuffleVectorSDNode::commuteMask(Unpckl);
9981     if (isTargetShuffleEquivalent(TargetMask, Unpckl)) {
9982       UnpackOpcode = X86ISD::UNPCKL;
9983       std::swap(V1, V2);
9984       return true;
9985     }
9986 
9987     ShuffleVectorSDNode::commuteMask(Unpckh);
9988     if (isTargetShuffleEquivalent(TargetMask, Unpckh)) {
9989       UnpackOpcode = X86ISD::UNPCKH;
9990       std::swap(V1, V2);
9991       return true;
9992     }
9993   }
9994 
9995   return false;
9996 }
9997 
9998 // X86 has dedicated unpack instructions that can handle specific blend
9999 // operations: UNPCKH and UNPCKL.
lowerVectorShuffleWithUNPCK(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,SelectionDAG & DAG)10000 static SDValue lowerVectorShuffleWithUNPCK(const SDLoc &DL, MVT VT,
10001                                            ArrayRef<int> Mask, SDValue V1,
10002                                            SDValue V2, SelectionDAG &DAG) {
10003   SmallVector<int, 8> Unpckl;
10004   createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, /* Unary = */ false);
10005   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
10006     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
10007 
10008   SmallVector<int, 8> Unpckh;
10009   createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, /* Unary = */ false);
10010   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
10011     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
10012 
10013   // Commute and try again.
10014   ShuffleVectorSDNode::commuteMask(Unpckl);
10015   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
10016     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
10017 
10018   ShuffleVectorSDNode::commuteMask(Unpckh);
10019   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
10020     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
10021 
10022   return SDValue();
10023 }
10024 
matchVectorShuffleAsVPMOV(ArrayRef<int> Mask,bool SwappedOps,int Delta)10025 static bool matchVectorShuffleAsVPMOV(ArrayRef<int> Mask, bool SwappedOps,
10026                                          int Delta) {
10027   int Size = (int)Mask.size();
10028   int Split = Size / Delta;
10029   int TruncatedVectorStart = SwappedOps ? Size : 0;
10030 
10031   // Match for mask starting with e.g.: <8, 10, 12, 14,... or <0, 2, 4, 6,...
10032   if (!isSequentialOrUndefInRange(Mask, 0, Split, TruncatedVectorStart, Delta))
10033     return false;
10034 
10035   // The rest of the mask should not refer to the truncated vector's elements.
10036   if (isAnyInRange(Mask.slice(Split, Size - Split), TruncatedVectorStart,
10037                    TruncatedVectorStart + Size))
10038     return false;
10039 
10040   return true;
10041 }
10042 
10043 // Try to lower trunc+vector_shuffle to a vpmovdb or a vpmovdw instruction.
10044 //
10045 // An example is the following:
10046 //
10047 // t0: ch = EntryToken
10048 //           t2: v4i64,ch = CopyFromReg t0, Register:v4i64 %0
10049 //         t25: v4i32 = truncate t2
10050 //       t41: v8i16 = bitcast t25
10051 //       t21: v8i16 = BUILD_VECTOR undef:i16, undef:i16, undef:i16, undef:i16,
10052 //       Constant:i16<0>, Constant:i16<0>, Constant:i16<0>, Constant:i16<0>
10053 //     t51: v8i16 = vector_shuffle<0,2,4,6,12,13,14,15> t41, t21
10054 //   t18: v2i64 = bitcast t51
10055 //
10056 // Without avx512vl, this is lowered to:
10057 //
10058 // vpmovqd %zmm0, %ymm0
10059 // vpshufb {{.*#+}} xmm0 =
10060 // xmm0[0,1,4,5,8,9,12,13],zero,zero,zero,zero,zero,zero,zero,zero
10061 //
10062 // But when avx512vl is available, one can just use a single vpmovdw
10063 // instruction.
lowerVectorShuffleWithVPMOV(const SDLoc & DL,ArrayRef<int> Mask,MVT VT,SDValue V1,SDValue V2,SelectionDAG & DAG,const X86Subtarget & Subtarget)10064 static SDValue lowerVectorShuffleWithVPMOV(const SDLoc &DL, ArrayRef<int> Mask,
10065                                            MVT VT, SDValue V1, SDValue V2,
10066                                            SelectionDAG &DAG,
10067                                            const X86Subtarget &Subtarget) {
10068   if (VT != MVT::v16i8 && VT != MVT::v8i16)
10069     return SDValue();
10070 
10071   if (Mask.size() != VT.getVectorNumElements())
10072     return SDValue();
10073 
10074   bool SwappedOps = false;
10075 
10076   if (!ISD::isBuildVectorAllZeros(V2.getNode())) {
10077     if (!ISD::isBuildVectorAllZeros(V1.getNode()))
10078       return SDValue();
10079 
10080     std::swap(V1, V2);
10081     SwappedOps = true;
10082   }
10083 
10084   // Look for:
10085   //
10086   // bitcast (truncate <8 x i32> %vec to <8 x i16>) to <16 x i8>
10087   // bitcast (truncate <4 x i64> %vec to <4 x i32>) to <8 x i16>
10088   //
10089   // and similar ones.
10090   if (V1.getOpcode() != ISD::BITCAST)
10091     return SDValue();
10092   if (V1.getOperand(0).getOpcode() != ISD::TRUNCATE)
10093     return SDValue();
10094 
10095   SDValue Src = V1.getOperand(0).getOperand(0);
10096   MVT SrcVT = Src.getSimpleValueType();
10097 
10098   // The vptrunc** instructions truncating 128 bit and 256 bit vectors
10099   // are only available with avx512vl.
10100   if (!SrcVT.is512BitVector() && !Subtarget.hasVLX())
10101     return SDValue();
10102 
10103   // Down Convert Word to Byte is only available with avx512bw. The case with
10104   // 256-bit output doesn't contain a shuffle and is therefore not handled here.
10105   if (SrcVT.getVectorElementType() == MVT::i16 && VT == MVT::v16i8 &&
10106       !Subtarget.hasBWI())
10107     return SDValue();
10108 
10109   // The first half/quarter of the mask should refer to every second/fourth
10110   // element of the vector truncated and bitcasted.
10111   if (!matchVectorShuffleAsVPMOV(Mask, SwappedOps, 2) &&
10112       !matchVectorShuffleAsVPMOV(Mask, SwappedOps, 4))
10113     return SDValue();
10114 
10115   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Src);
10116 }
10117 
10118 // X86 has dedicated pack instructions that can handle specific truncation
10119 // operations: PACKSS and PACKUS.
matchVectorShuffleWithPACK(MVT VT,MVT & SrcVT,SDValue & V1,SDValue & V2,unsigned & PackOpcode,ArrayRef<int> TargetMask,SelectionDAG & DAG,const X86Subtarget & Subtarget)10120 static bool matchVectorShuffleWithPACK(MVT VT, MVT &SrcVT, SDValue &V1,
10121                                        SDValue &V2, unsigned &PackOpcode,
10122                                        ArrayRef<int> TargetMask,
10123                                        SelectionDAG &DAG,
10124                                        const X86Subtarget &Subtarget) {
10125   unsigned NumElts = VT.getVectorNumElements();
10126   unsigned BitSize = VT.getScalarSizeInBits();
10127   MVT PackSVT = MVT::getIntegerVT(BitSize * 2);
10128   MVT PackVT = MVT::getVectorVT(PackSVT, NumElts / 2);
10129 
10130   auto MatchPACK = [&](SDValue N1, SDValue N2) {
10131     SDValue VV1 = DAG.getBitcast(PackVT, N1);
10132     SDValue VV2 = DAG.getBitcast(PackVT, N2);
10133     if (Subtarget.hasSSE41() || PackSVT == MVT::i16) {
10134       APInt ZeroMask = APInt::getHighBitsSet(BitSize * 2, BitSize);
10135       if ((N1.isUndef() || DAG.MaskedValueIsZero(VV1, ZeroMask)) &&
10136           (N2.isUndef() || DAG.MaskedValueIsZero(VV2, ZeroMask))) {
10137         V1 = VV1;
10138         V2 = VV2;
10139         SrcVT = PackVT;
10140         PackOpcode = X86ISD::PACKUS;
10141         return true;
10142       }
10143     }
10144     if ((N1.isUndef() || DAG.ComputeNumSignBits(VV1) > BitSize) &&
10145         (N2.isUndef() || DAG.ComputeNumSignBits(VV2) > BitSize)) {
10146       V1 = VV1;
10147       V2 = VV2;
10148       SrcVT = PackVT;
10149       PackOpcode = X86ISD::PACKSS;
10150       return true;
10151     }
10152     return false;
10153   };
10154 
10155   // Try binary shuffle.
10156   SmallVector<int, 32> BinaryMask;
10157   createPackShuffleMask(VT, BinaryMask, false);
10158   if (isTargetShuffleEquivalent(TargetMask, BinaryMask))
10159     if (MatchPACK(V1, V2))
10160       return true;
10161 
10162   // Try unary shuffle.
10163   SmallVector<int, 32> UnaryMask;
10164   createPackShuffleMask(VT, UnaryMask, true);
10165   if (isTargetShuffleEquivalent(TargetMask, UnaryMask))
10166     if (MatchPACK(V1, V1))
10167       return true;
10168 
10169   return false;
10170 }
10171 
lowerVectorShuffleWithPACK(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,SelectionDAG & DAG,const X86Subtarget & Subtarget)10172 static SDValue lowerVectorShuffleWithPACK(const SDLoc &DL, MVT VT,
10173                                           ArrayRef<int> Mask, SDValue V1,
10174                                           SDValue V2, SelectionDAG &DAG,
10175                                           const X86Subtarget &Subtarget) {
10176   MVT PackVT;
10177   unsigned PackOpcode;
10178   if (matchVectorShuffleWithPACK(VT, PackVT, V1, V2, PackOpcode, Mask, DAG,
10179                                  Subtarget))
10180     return DAG.getNode(PackOpcode, DL, VT, DAG.getBitcast(PackVT, V1),
10181                        DAG.getBitcast(PackVT, V2));
10182 
10183   return SDValue();
10184 }
10185 
10186 /// Try to emit a bitmask instruction for a shuffle.
10187 ///
10188 /// This handles cases where we can model a blend exactly as a bitmask due to
10189 /// one of the inputs being zeroable.
lowerVectorShuffleAsBitMask(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,SelectionDAG & DAG)10190 static SDValue lowerVectorShuffleAsBitMask(const SDLoc &DL, MVT VT, SDValue V1,
10191                                            SDValue V2, ArrayRef<int> Mask,
10192                                            const APInt &Zeroable,
10193                                            SelectionDAG &DAG) {
10194   assert(!VT.isFloatingPoint() && "Floating point types are not supported");
10195   MVT EltVT = VT.getVectorElementType();
10196   SDValue Zero = DAG.getConstant(0, DL, EltVT);
10197   SDValue AllOnes = DAG.getAllOnesConstant(DL, EltVT);
10198   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
10199   SDValue V;
10200   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
10201     if (Zeroable[i])
10202       continue;
10203     if (Mask[i] % Size != i)
10204       return SDValue(); // Not a blend.
10205     if (!V)
10206       V = Mask[i] < Size ? V1 : V2;
10207     else if (V != (Mask[i] < Size ? V1 : V2))
10208       return SDValue(); // Can only let one input through the mask.
10209 
10210     VMaskOps[i] = AllOnes;
10211   }
10212   if (!V)
10213     return SDValue(); // No non-zeroable elements!
10214 
10215   SDValue VMask = DAG.getBuildVector(VT, DL, VMaskOps);
10216   return DAG.getNode(ISD::AND, DL, VT, V, VMask);
10217 }
10218 
10219 /// Try to emit a blend instruction for a shuffle using bit math.
10220 ///
10221 /// This is used as a fallback approach when first class blend instructions are
10222 /// unavailable. Currently it is only suitable for integer vectors, but could
10223 /// be generalized for floating point vectors if desirable.
lowerVectorShuffleAsBitBlend(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG)10224 static SDValue lowerVectorShuffleAsBitBlend(const SDLoc &DL, MVT VT, SDValue V1,
10225                                             SDValue V2, ArrayRef<int> Mask,
10226                                             SelectionDAG &DAG) {
10227   assert(VT.isInteger() && "Only supports integer vector types!");
10228   MVT EltVT = VT.getVectorElementType();
10229   SDValue Zero = DAG.getConstant(0, DL, EltVT);
10230   SDValue AllOnes = DAG.getAllOnesConstant(DL, EltVT);
10231   SmallVector<SDValue, 16> MaskOps;
10232   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
10233     if (Mask[i] >= 0 && Mask[i] != i && Mask[i] != i + Size)
10234       return SDValue(); // Shuffled input!
10235     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
10236   }
10237 
10238   SDValue V1Mask = DAG.getBuildVector(VT, DL, MaskOps);
10239   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
10240   V2 = DAG.getNode(X86ISD::ANDNP, DL, VT, V1Mask, V2);
10241   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
10242 }
10243 
10244 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
10245                                     SDValue PreservedSrc,
10246                                     const X86Subtarget &Subtarget,
10247                                     SelectionDAG &DAG);
10248 
matchVectorShuffleAsBlend(SDValue V1,SDValue V2,MutableArrayRef<int> TargetMask,bool & ForceV1Zero,bool & ForceV2Zero,uint64_t & BlendMask)10249 static bool matchVectorShuffleAsBlend(SDValue V1, SDValue V2,
10250                                       MutableArrayRef<int> TargetMask,
10251                                       bool &ForceV1Zero, bool &ForceV2Zero,
10252                                       uint64_t &BlendMask) {
10253   bool V1IsZeroOrUndef =
10254       V1.isUndef() || ISD::isBuildVectorAllZeros(V1.getNode());
10255   bool V2IsZeroOrUndef =
10256       V2.isUndef() || ISD::isBuildVectorAllZeros(V2.getNode());
10257 
10258   BlendMask = 0;
10259   ForceV1Zero = false, ForceV2Zero = false;
10260   assert(TargetMask.size() <= 64 && "Shuffle mask too big for blend mask");
10261 
10262   // Attempt to generate the binary blend mask. If an input is zero then
10263   // we can use any lane.
10264   // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
10265   for (int i = 0, Size = TargetMask.size(); i < Size; ++i) {
10266     int M = TargetMask[i];
10267     if (M == SM_SentinelUndef)
10268       continue;
10269     if (M == i)
10270       continue;
10271     if (M == i + Size) {
10272       BlendMask |= 1ull << i;
10273       continue;
10274     }
10275     if (M == SM_SentinelZero) {
10276       if (V1IsZeroOrUndef) {
10277         ForceV1Zero = true;
10278         TargetMask[i] = i;
10279         continue;
10280       }
10281       if (V2IsZeroOrUndef) {
10282         ForceV2Zero = true;
10283         BlendMask |= 1ull << i;
10284         TargetMask[i] = i + Size;
10285         continue;
10286       }
10287     }
10288     return false;
10289   }
10290   return true;
10291 }
10292 
scaleVectorShuffleBlendMask(uint64_t BlendMask,int Size,int Scale)10293 static uint64_t scaleVectorShuffleBlendMask(uint64_t BlendMask, int Size,
10294                                             int Scale) {
10295   uint64_t ScaledMask = 0;
10296   for (int i = 0; i != Size; ++i)
10297     if (BlendMask & (1ull << i))
10298       ScaledMask |= ((1ull << Scale) - 1) << (i * Scale);
10299   return ScaledMask;
10300 }
10301 
10302 /// Try to emit a blend instruction for a shuffle.
10303 ///
10304 /// This doesn't do any checks for the availability of instructions for blending
10305 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
10306 /// be matched in the backend with the type given. What it does check for is
10307 /// that the shuffle mask is a blend, or convertible into a blend with zero.
lowerVectorShuffleAsBlend(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Original,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)10308 static SDValue lowerVectorShuffleAsBlend(const SDLoc &DL, MVT VT, SDValue V1,
10309                                          SDValue V2, ArrayRef<int> Original,
10310                                          const APInt &Zeroable,
10311                                          const X86Subtarget &Subtarget,
10312                                          SelectionDAG &DAG) {
10313   SmallVector<int, 64> Mask = createTargetShuffleMask(Original, Zeroable);
10314 
10315   uint64_t BlendMask = 0;
10316   bool ForceV1Zero = false, ForceV2Zero = false;
10317   if (!matchVectorShuffleAsBlend(V1, V2, Mask, ForceV1Zero, ForceV2Zero,
10318                                  BlendMask))
10319     return SDValue();
10320 
10321   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
10322   if (ForceV1Zero)
10323     V1 = getZeroVector(VT, Subtarget, DAG, DL);
10324   if (ForceV2Zero)
10325     V2 = getZeroVector(VT, Subtarget, DAG, DL);
10326 
10327   switch (VT.SimpleTy) {
10328   case MVT::v2f64:
10329   case MVT::v4f32:
10330   case MVT::v4f64:
10331   case MVT::v8f32:
10332     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
10333                        DAG.getConstant(BlendMask, DL, MVT::i8));
10334   case MVT::v4i64:
10335   case MVT::v8i32:
10336     assert(Subtarget.hasAVX2() && "256-bit integer blends require AVX2!");
10337     LLVM_FALLTHROUGH;
10338   case MVT::v2i64:
10339   case MVT::v4i32:
10340     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
10341     // that instruction.
10342     if (Subtarget.hasAVX2()) {
10343       // Scale the blend by the number of 32-bit dwords per element.
10344       int Scale =  VT.getScalarSizeInBits() / 32;
10345       BlendMask = scaleVectorShuffleBlendMask(BlendMask, Mask.size(), Scale);
10346       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
10347       V1 = DAG.getBitcast(BlendVT, V1);
10348       V2 = DAG.getBitcast(BlendVT, V2);
10349       return DAG.getBitcast(
10350           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
10351                           DAG.getConstant(BlendMask, DL, MVT::i8)));
10352     }
10353     LLVM_FALLTHROUGH;
10354   case MVT::v8i16: {
10355     // For integer shuffles we need to expand the mask and cast the inputs to
10356     // v8i16s prior to blending.
10357     int Scale = 8 / VT.getVectorNumElements();
10358     BlendMask = scaleVectorShuffleBlendMask(BlendMask, Mask.size(), Scale);
10359     V1 = DAG.getBitcast(MVT::v8i16, V1);
10360     V2 = DAG.getBitcast(MVT::v8i16, V2);
10361     return DAG.getBitcast(VT,
10362                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
10363                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
10364   }
10365   case MVT::v16i16: {
10366     assert(Subtarget.hasAVX2() && "256-bit integer blends require AVX2!");
10367     SmallVector<int, 8> RepeatedMask;
10368     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10369       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
10370       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
10371       BlendMask = 0;
10372       for (int i = 0; i < 8; ++i)
10373         if (RepeatedMask[i] >= 8)
10374           BlendMask |= 1ull << i;
10375       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
10376                          DAG.getConstant(BlendMask, DL, MVT::i8));
10377     }
10378     // Use PBLENDW for lower/upper lanes and then blend lanes.
10379     // TODO - we should allow 2 PBLENDW here and leave shuffle combine to
10380     // merge to VSELECT where useful.
10381     uint64_t LoMask = BlendMask & 0xFF;
10382     uint64_t HiMask = (BlendMask >> 8) & 0xFF;
10383     if (LoMask == 0 || LoMask == 255 || HiMask == 0 || HiMask == 255) {
10384       SDValue Lo = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
10385                                DAG.getConstant(LoMask, DL, MVT::i8));
10386       SDValue Hi = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
10387                                DAG.getConstant(HiMask, DL, MVT::i8));
10388       return DAG.getVectorShuffle(
10389           MVT::v16i16, DL, Lo, Hi,
10390           {0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31});
10391     }
10392     LLVM_FALLTHROUGH;
10393   }
10394   case MVT::v16i8:
10395   case MVT::v32i8: {
10396     assert((VT.is128BitVector() || Subtarget.hasAVX2()) &&
10397            "256-bit byte-blends require AVX2 support!");
10398 
10399     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
10400     if (SDValue Masked =
10401             lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable, DAG))
10402       return Masked;
10403 
10404     if (Subtarget.hasBWI() && Subtarget.hasVLX()) {
10405       MVT IntegerType =
10406           MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
10407       SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
10408       return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
10409     }
10410 
10411     // Scale the blend by the number of bytes per element.
10412     int Scale = VT.getScalarSizeInBits() / 8;
10413 
10414     // This form of blend is always done on bytes. Compute the byte vector
10415     // type.
10416     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
10417 
10418     // x86 allows load folding with blendvb from the 2nd source operand. But
10419     // we are still using LLVM select here (see comment below), so that's V1.
10420     // If V2 can be load-folded and V1 cannot be load-folded, then commute to
10421     // allow that load-folding possibility.
10422     if (!ISD::isNormalLoad(V1.getNode()) && ISD::isNormalLoad(V2.getNode())) {
10423       ShuffleVectorSDNode::commuteMask(Mask);
10424       std::swap(V1, V2);
10425     }
10426 
10427     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
10428     // mix of LLVM's code generator and the x86 backend. We tell the code
10429     // generator that boolean values in the elements of an x86 vector register
10430     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
10431     // mapping a select to operand #1, and 'false' mapping to operand #2. The
10432     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
10433     // of the element (the remaining are ignored) and 0 in that high bit would
10434     // mean operand #1 while 1 in the high bit would mean operand #2. So while
10435     // the LLVM model for boolean values in vector elements gets the relevant
10436     // bit set, it is set backwards and over constrained relative to x86's
10437     // actual model.
10438     SmallVector<SDValue, 32> VSELECTMask;
10439     for (int i = 0, Size = Mask.size(); i < Size; ++i)
10440       for (int j = 0; j < Scale; ++j)
10441         VSELECTMask.push_back(
10442             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
10443                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
10444                                           MVT::i8));
10445 
10446     V1 = DAG.getBitcast(BlendVT, V1);
10447     V2 = DAG.getBitcast(BlendVT, V2);
10448     return DAG.getBitcast(
10449         VT,
10450         DAG.getSelect(DL, BlendVT, DAG.getBuildVector(BlendVT, DL, VSELECTMask),
10451                       V1, V2));
10452   }
10453   case MVT::v16f32:
10454   case MVT::v8f64:
10455   case MVT::v8i64:
10456   case MVT::v16i32:
10457   case MVT::v32i16:
10458   case MVT::v64i8: {
10459     MVT IntegerType =
10460         MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
10461     SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
10462     return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
10463   }
10464   default:
10465     llvm_unreachable("Not a supported integer vector type!");
10466   }
10467 }
10468 
10469 /// Try to lower as a blend of elements from two inputs followed by
10470 /// a single-input permutation.
10471 ///
10472 /// This matches the pattern where we can blend elements from two inputs and
10473 /// then reduce the shuffle to a single-input permutation.
lowerVectorShuffleAsBlendAndPermute(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG,bool ImmBlends=false)10474 static SDValue lowerVectorShuffleAsBlendAndPermute(const SDLoc &DL, MVT VT,
10475                                                    SDValue V1, SDValue V2,
10476                                                    ArrayRef<int> Mask,
10477                                                    SelectionDAG &DAG,
10478                                                    bool ImmBlends = false) {
10479   // We build up the blend mask while checking whether a blend is a viable way
10480   // to reduce the shuffle.
10481   SmallVector<int, 32> BlendMask(Mask.size(), -1);
10482   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
10483 
10484   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
10485     if (Mask[i] < 0)
10486       continue;
10487 
10488     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
10489 
10490     if (BlendMask[Mask[i] % Size] < 0)
10491       BlendMask[Mask[i] % Size] = Mask[i];
10492     else if (BlendMask[Mask[i] % Size] != Mask[i])
10493       return SDValue(); // Can't blend in the needed input!
10494 
10495     PermuteMask[i] = Mask[i] % Size;
10496   }
10497 
10498   // If only immediate blends, then bail if the blend mask can't be widened to
10499   // i16.
10500   unsigned EltSize = VT.getScalarSizeInBits();
10501   if (ImmBlends && EltSize == 8 && !canWidenShuffleElements(BlendMask))
10502     return SDValue();
10503 
10504   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
10505   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
10506 }
10507 
10508 /// Try to lower as an unpack of elements from two inputs followed by
10509 /// a single-input permutation.
10510 ///
10511 /// This matches the pattern where we can unpack elements from two inputs and
10512 /// then reduce the shuffle to a single-input (wider) permutation.
lowerVectorShuffleAsUNPCKAndPermute(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG)10513 static SDValue lowerVectorShuffleAsUNPCKAndPermute(const SDLoc &DL, MVT VT,
10514                                                    SDValue V1, SDValue V2,
10515                                                    ArrayRef<int> Mask,
10516                                                    SelectionDAG &DAG) {
10517   int NumElts = Mask.size();
10518   int NumLanes = VT.getSizeInBits() / 128;
10519   int NumLaneElts = NumElts / NumLanes;
10520   int NumHalfLaneElts = NumLaneElts / 2;
10521 
10522   bool MatchLo = true, MatchHi = true;
10523   SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
10524 
10525   // Determine UNPCKL/UNPCKH type and operand order.
10526   for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
10527     for (int Elt = 0; Elt != NumLaneElts; ++Elt) {
10528       int M = Mask[Lane + Elt];
10529       if (M < 0)
10530         continue;
10531 
10532       SDValue &Op = Ops[Elt & 1];
10533       if (M < NumElts && (Op.isUndef() || Op == V1))
10534         Op = V1;
10535       else if (NumElts <= M && (Op.isUndef() || Op == V2))
10536         Op = V2;
10537       else
10538         return SDValue();
10539 
10540       int Lo = Lane, Mid = Lane + NumHalfLaneElts, Hi = Lane + NumLaneElts;
10541       MatchLo &= isUndefOrInRange(M, Lo, Mid) ||
10542                  isUndefOrInRange(M, NumElts + Lo, NumElts + Mid);
10543       MatchHi &= isUndefOrInRange(M, Mid, Hi) ||
10544                  isUndefOrInRange(M, NumElts + Mid, NumElts + Hi);
10545       if (!MatchLo && !MatchHi)
10546         return SDValue();
10547     }
10548   }
10549   assert((MatchLo ^ MatchHi) && "Failed to match UNPCKLO/UNPCKHI");
10550 
10551   // Now check that each pair of elts come from the same unpack pair
10552   // and set the permute mask based on each pair.
10553   // TODO - Investigate cases where we permute individual elements.
10554   SmallVector<int, 32> PermuteMask(NumElts, -1);
10555   for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
10556     for (int Elt = 0; Elt != NumLaneElts; Elt += 2) {
10557       int M0 = Mask[Lane + Elt + 0];
10558       int M1 = Mask[Lane + Elt + 1];
10559       if (0 <= M0 && 0 <= M1 &&
10560           (M0 % NumHalfLaneElts) != (M1 % NumHalfLaneElts))
10561         return SDValue();
10562       if (0 <= M0)
10563         PermuteMask[Lane + Elt + 0] = Lane + (2 * (M0 % NumHalfLaneElts));
10564       if (0 <= M1)
10565         PermuteMask[Lane + Elt + 1] = Lane + (2 * (M1 % NumHalfLaneElts)) + 1;
10566     }
10567   }
10568 
10569   unsigned UnpckOp = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
10570   SDValue Unpck = DAG.getNode(UnpckOp, DL, VT, Ops);
10571   return DAG.getVectorShuffle(VT, DL, Unpck, DAG.getUNDEF(VT), PermuteMask);
10572 }
10573 
10574 /// Helper to form a PALIGNR-based rotate+permute, merging 2 inputs and then
10575 /// permuting the elements of the result in place.
lowerVectorShuffleAsByteRotateAndPermute(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)10576 static SDValue lowerVectorShuffleAsByteRotateAndPermute(
10577     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10578     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
10579   if ((VT.is128BitVector() && !Subtarget.hasSSSE3()) ||
10580       (VT.is256BitVector() && !Subtarget.hasAVX2()) ||
10581       (VT.is512BitVector() && !Subtarget.hasBWI()))
10582     return SDValue();
10583 
10584   // We don't currently support lane crossing permutes.
10585   if (is128BitLaneCrossingShuffleMask(VT, Mask))
10586     return SDValue();
10587 
10588   int Scale = VT.getScalarSizeInBits() / 8;
10589   int NumLanes = VT.getSizeInBits() / 128;
10590   int NumElts = VT.getVectorNumElements();
10591   int NumEltsPerLane = NumElts / NumLanes;
10592 
10593   // Determine range of mask elts.
10594   bool Blend1 = true;
10595   bool Blend2 = true;
10596   std::pair<int, int> Range1 = std::make_pair(INT_MAX, INT_MIN);
10597   std::pair<int, int> Range2 = std::make_pair(INT_MAX, INT_MIN);
10598   for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
10599     for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
10600       int M = Mask[Lane + Elt];
10601       if (M < 0)
10602         continue;
10603       if (M < NumElts) {
10604         Blend1 &= (M == (Lane + Elt));
10605         assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
10606         M = M % NumEltsPerLane;
10607         Range1.first = std::min(Range1.first, M);
10608         Range1.second = std::max(Range1.second, M);
10609       } else {
10610         M -= NumElts;
10611         Blend2 &= (M == (Lane + Elt));
10612         assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
10613         M = M % NumEltsPerLane;
10614         Range2.first = std::min(Range2.first, M);
10615         Range2.second = std::max(Range2.second, M);
10616       }
10617     }
10618   }
10619 
10620   // Bail if we don't need both elements.
10621   // TODO - it might be worth doing this for unary shuffles if the permute
10622   // can be widened.
10623   if (!(0 <= Range1.first && Range1.second < NumEltsPerLane) ||
10624       !(0 <= Range2.first && Range2.second < NumEltsPerLane))
10625     return SDValue();
10626 
10627   if (VT.getSizeInBits() > 128 && (Blend1 || Blend2))
10628     return SDValue();
10629 
10630   // Rotate the 2 ops so we can access both ranges, then permute the result.
10631   auto RotateAndPermute = [&](SDValue Lo, SDValue Hi, int RotAmt, int Ofs) {
10632     MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
10633     SDValue Rotate = DAG.getBitcast(
10634         VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, DAG.getBitcast(ByteVT, Hi),
10635                         DAG.getBitcast(ByteVT, Lo),
10636                         DAG.getConstant(Scale * RotAmt, DL, MVT::i8)));
10637     SmallVector<int, 64> PermMask(NumElts, SM_SentinelUndef);
10638     for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
10639       for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
10640         int M = Mask[Lane + Elt];
10641         if (M < 0)
10642           continue;
10643         if (M < NumElts)
10644           PermMask[Lane + Elt] = Lane + ((M + Ofs - RotAmt) % NumEltsPerLane);
10645         else
10646           PermMask[Lane + Elt] = Lane + ((M - Ofs - RotAmt) % NumEltsPerLane);
10647       }
10648     }
10649     return DAG.getVectorShuffle(VT, DL, Rotate, DAG.getUNDEF(VT), PermMask);
10650   };
10651 
10652   // Check if the ranges are small enough to rotate from either direction.
10653   if (Range2.second < Range1.first)
10654     return RotateAndPermute(V1, V2, Range1.first, 0);
10655   if (Range1.second < Range2.first)
10656     return RotateAndPermute(V2, V1, Range2.first, NumElts);
10657   return SDValue();
10658 }
10659 
10660 /// Generic routine to decompose a shuffle and blend into independent
10661 /// blends and permutes.
10662 ///
10663 /// This matches the extremely common pattern for handling combined
10664 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
10665 /// operations. It will try to pick the best arrangement of shuffles and
10666 /// blends.
lowerVectorShuffleAsDecomposedShuffleBlend(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)10667 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(
10668     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10669     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
10670   // Shuffle the input elements into the desired positions in V1 and V2 and
10671   // blend them together.
10672   SmallVector<int, 32> V1Mask(Mask.size(), -1);
10673   SmallVector<int, 32> V2Mask(Mask.size(), -1);
10674   SmallVector<int, 32> BlendMask(Mask.size(), -1);
10675   for (int i = 0, Size = Mask.size(); i < Size; ++i)
10676     if (Mask[i] >= 0 && Mask[i] < Size) {
10677       V1Mask[i] = Mask[i];
10678       BlendMask[i] = i;
10679     } else if (Mask[i] >= Size) {
10680       V2Mask[i] = Mask[i] - Size;
10681       BlendMask[i] = i + Size;
10682     }
10683 
10684   // Try to lower with the simpler initial blend/unpack/rotate strategies unless
10685   // one of the input shuffles would be a no-op. We prefer to shuffle inputs as
10686   // the shuffle may be able to fold with a load or other benefit. However, when
10687   // we'll have to do 2x as many shuffles in order to achieve this, a 2-input
10688   // pre-shuffle first is a better strategy.
10689   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask)) {
10690     // Only prefer immediate blends to unpack/rotate.
10691     if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
10692             DL, VT, V1, V2, Mask, DAG, true))
10693       return BlendPerm;
10694     if (SDValue UnpackPerm =
10695             lowerVectorShuffleAsUNPCKAndPermute(DL, VT, V1, V2, Mask, DAG))
10696       return UnpackPerm;
10697     if (SDValue RotatePerm = lowerVectorShuffleAsByteRotateAndPermute(
10698             DL, VT, V1, V2, Mask, Subtarget, DAG))
10699       return RotatePerm;
10700     // Unpack/rotate failed - try again with variable blends.
10701     if (SDValue BlendPerm =
10702             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
10703       return BlendPerm;
10704   }
10705 
10706   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
10707   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
10708   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
10709 }
10710 
10711 /// Try to lower a vector shuffle as a rotation.
10712 ///
10713 /// This is used for support PALIGNR for SSSE3 or VALIGND/Q for AVX512.
matchVectorShuffleAsRotate(SDValue & V1,SDValue & V2,ArrayRef<int> Mask)10714 static int matchVectorShuffleAsRotate(SDValue &V1, SDValue &V2,
10715                                       ArrayRef<int> Mask) {
10716   int NumElts = Mask.size();
10717 
10718   // We need to detect various ways of spelling a rotation:
10719   //   [11, 12, 13, 14, 15,  0,  1,  2]
10720   //   [-1, 12, 13, 14, -1, -1,  1, -1]
10721   //   [-1, -1, -1, -1, -1, -1,  1,  2]
10722   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
10723   //   [-1,  4,  5,  6, -1, -1,  9, -1]
10724   //   [-1,  4,  5,  6, -1, -1, -1, -1]
10725   int Rotation = 0;
10726   SDValue Lo, Hi;
10727   for (int i = 0; i < NumElts; ++i) {
10728     int M = Mask[i];
10729     assert((M == SM_SentinelUndef || (0 <= M && M < (2*NumElts))) &&
10730            "Unexpected mask index.");
10731     if (M < 0)
10732       continue;
10733 
10734     // Determine where a rotated vector would have started.
10735     int StartIdx = i - (M % NumElts);
10736     if (StartIdx == 0)
10737       // The identity rotation isn't interesting, stop.
10738       return -1;
10739 
10740     // If we found the tail of a vector the rotation must be the missing
10741     // front. If we found the head of a vector, it must be how much of the
10742     // head.
10743     int CandidateRotation = StartIdx < 0 ? -StartIdx : NumElts - StartIdx;
10744 
10745     if (Rotation == 0)
10746       Rotation = CandidateRotation;
10747     else if (Rotation != CandidateRotation)
10748       // The rotations don't match, so we can't match this mask.
10749       return -1;
10750 
10751     // Compute which value this mask is pointing at.
10752     SDValue MaskV = M < NumElts ? V1 : V2;
10753 
10754     // Compute which of the two target values this index should be assigned
10755     // to. This reflects whether the high elements are remaining or the low
10756     // elements are remaining.
10757     SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
10758 
10759     // Either set up this value if we've not encountered it before, or check
10760     // that it remains consistent.
10761     if (!TargetV)
10762       TargetV = MaskV;
10763     else if (TargetV != MaskV)
10764       // This may be a rotation, but it pulls from the inputs in some
10765       // unsupported interleaving.
10766       return -1;
10767   }
10768 
10769   // Check that we successfully analyzed the mask, and normalize the results.
10770   assert(Rotation != 0 && "Failed to locate a viable rotation!");
10771   assert((Lo || Hi) && "Failed to find a rotated input vector!");
10772   if (!Lo)
10773     Lo = Hi;
10774   else if (!Hi)
10775     Hi = Lo;
10776 
10777   V1 = Lo;
10778   V2 = Hi;
10779 
10780   return Rotation;
10781 }
10782 
10783 /// Try to lower a vector shuffle as a byte rotation.
10784 ///
10785 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
10786 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
10787 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
10788 /// try to generically lower a vector shuffle through such an pattern. It
10789 /// does not check for the profitability of lowering either as PALIGNR or
10790 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
10791 /// This matches shuffle vectors that look like:
10792 ///
10793 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
10794 ///
10795 /// Essentially it concatenates V1 and V2, shifts right by some number of
10796 /// elements, and takes the low elements as the result. Note that while this is
10797 /// specified as a *right shift* because x86 is little-endian, it is a *left
10798 /// rotate* of the vector lanes.
matchVectorShuffleAsByteRotate(MVT VT,SDValue & V1,SDValue & V2,ArrayRef<int> Mask)10799 static int matchVectorShuffleAsByteRotate(MVT VT, SDValue &V1, SDValue &V2,
10800                                           ArrayRef<int> Mask) {
10801   // Don't accept any shuffles with zero elements.
10802   if (any_of(Mask, [](int M) { return M == SM_SentinelZero; }))
10803     return -1;
10804 
10805   // PALIGNR works on 128-bit lanes.
10806   SmallVector<int, 16> RepeatedMask;
10807   if (!is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedMask))
10808     return -1;
10809 
10810   int Rotation = matchVectorShuffleAsRotate(V1, V2, RepeatedMask);
10811   if (Rotation <= 0)
10812     return -1;
10813 
10814   // PALIGNR rotates bytes, so we need to scale the
10815   // rotation based on how many bytes are in the vector lane.
10816   int NumElts = RepeatedMask.size();
10817   int Scale = 16 / NumElts;
10818   return Rotation * Scale;
10819 }
10820 
lowerVectorShuffleAsByteRotate(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)10821 static SDValue lowerVectorShuffleAsByteRotate(const SDLoc &DL, MVT VT,
10822                                               SDValue V1, SDValue V2,
10823                                               ArrayRef<int> Mask,
10824                                               const X86Subtarget &Subtarget,
10825                                               SelectionDAG &DAG) {
10826   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
10827 
10828   SDValue Lo = V1, Hi = V2;
10829   int ByteRotation = matchVectorShuffleAsByteRotate(VT, Lo, Hi, Mask);
10830   if (ByteRotation <= 0)
10831     return SDValue();
10832 
10833   // Cast the inputs to i8 vector of correct length to match PALIGNR or
10834   // PSLLDQ/PSRLDQ.
10835   MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
10836   Lo = DAG.getBitcast(ByteVT, Lo);
10837   Hi = DAG.getBitcast(ByteVT, Hi);
10838 
10839   // SSSE3 targets can use the palignr instruction.
10840   if (Subtarget.hasSSSE3()) {
10841     assert((!VT.is512BitVector() || Subtarget.hasBWI()) &&
10842            "512-bit PALIGNR requires BWI instructions");
10843     return DAG.getBitcast(
10844         VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, Lo, Hi,
10845                         DAG.getConstant(ByteRotation, DL, MVT::i8)));
10846   }
10847 
10848   assert(VT.is128BitVector() &&
10849          "Rotate-based lowering only supports 128-bit lowering!");
10850   assert(Mask.size() <= 16 &&
10851          "Can shuffle at most 16 bytes in a 128-bit vector!");
10852   assert(ByteVT == MVT::v16i8 &&
10853          "SSE2 rotate lowering only needed for v16i8!");
10854 
10855   // Default SSE2 implementation
10856   int LoByteShift = 16 - ByteRotation;
10857   int HiByteShift = ByteRotation;
10858 
10859   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Lo,
10860                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
10861   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Hi,
10862                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
10863   return DAG.getBitcast(VT,
10864                         DAG.getNode(ISD::OR, DL, MVT::v16i8, LoShift, HiShift));
10865 }
10866 
10867 /// Try to lower a vector shuffle as a dword/qword rotation.
10868 ///
10869 /// AVX512 has a VALIGND/VALIGNQ instructions that will do an arbitrary
10870 /// rotation of the concatenation of two vectors; This routine will
10871 /// try to generically lower a vector shuffle through such an pattern.
10872 ///
10873 /// Essentially it concatenates V1 and V2, shifts right by some number of
10874 /// elements, and takes the low elements as the result. Note that while this is
10875 /// specified as a *right shift* because x86 is little-endian, it is a *left
10876 /// rotate* of the vector lanes.
lowerVectorShuffleAsRotate(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)10877 static SDValue lowerVectorShuffleAsRotate(const SDLoc &DL, MVT VT,
10878                                           SDValue V1, SDValue V2,
10879                                           ArrayRef<int> Mask,
10880                                           const X86Subtarget &Subtarget,
10881                                           SelectionDAG &DAG) {
10882   assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&
10883          "Only 32-bit and 64-bit elements are supported!");
10884 
10885   // 128/256-bit vectors are only supported with VLX.
10886   assert((Subtarget.hasVLX() || (!VT.is128BitVector() && !VT.is256BitVector()))
10887          && "VLX required for 128/256-bit vectors");
10888 
10889   SDValue Lo = V1, Hi = V2;
10890   int Rotation = matchVectorShuffleAsRotate(Lo, Hi, Mask);
10891   if (Rotation <= 0)
10892     return SDValue();
10893 
10894   return DAG.getNode(X86ISD::VALIGN, DL, VT, Lo, Hi,
10895                      DAG.getConstant(Rotation, DL, MVT::i8));
10896 }
10897 
10898 /// Try to lower a vector shuffle as a bit shift (shifts in zeros).
10899 ///
10900 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
10901 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
10902 /// matches elements from one of the input vectors shuffled to the left or
10903 /// right with zeroable elements 'shifted in'. It handles both the strictly
10904 /// bit-wise element shifts and the byte shift across an entire 128-bit double
10905 /// quad word lane.
10906 ///
10907 /// PSHL : (little-endian) left bit shift.
10908 /// [ zz, 0, zz,  2 ]
10909 /// [ -1, 4, zz, -1 ]
10910 /// PSRL : (little-endian) right bit shift.
10911 /// [  1, zz,  3, zz]
10912 /// [ -1, -1,  7, zz]
10913 /// PSLLDQ : (little-endian) left byte shift
10914 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
10915 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
10916 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
10917 /// PSRLDQ : (little-endian) right byte shift
10918 /// [  5, 6,  7, zz, zz, zz, zz, zz]
10919 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
10920 /// [  1, 2, -1, -1, -1, -1, zz, zz]
matchVectorShuffleAsShift(MVT & ShiftVT,unsigned & Opcode,unsigned ScalarSizeInBits,ArrayRef<int> Mask,int MaskOffset,const APInt & Zeroable,const X86Subtarget & Subtarget)10921 static int matchVectorShuffleAsShift(MVT &ShiftVT, unsigned &Opcode,
10922                                      unsigned ScalarSizeInBits,
10923                                      ArrayRef<int> Mask, int MaskOffset,
10924                                      const APInt &Zeroable,
10925                                      const X86Subtarget &Subtarget) {
10926   int Size = Mask.size();
10927   unsigned SizeInBits = Size * ScalarSizeInBits;
10928 
10929   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
10930     for (int i = 0; i < Size; i += Scale)
10931       for (int j = 0; j < Shift; ++j)
10932         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
10933           return false;
10934 
10935     return true;
10936   };
10937 
10938   auto MatchShift = [&](int Shift, int Scale, bool Left) {
10939     for (int i = 0; i != Size; i += Scale) {
10940       unsigned Pos = Left ? i + Shift : i;
10941       unsigned Low = Left ? i : i + Shift;
10942       unsigned Len = Scale - Shift;
10943       if (!isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset))
10944         return -1;
10945     }
10946 
10947     int ShiftEltBits = ScalarSizeInBits * Scale;
10948     bool ByteShift = ShiftEltBits > 64;
10949     Opcode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
10950                   : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
10951     int ShiftAmt = Shift * ScalarSizeInBits / (ByteShift ? 8 : 1);
10952 
10953     // Normalize the scale for byte shifts to still produce an i64 element
10954     // type.
10955     Scale = ByteShift ? Scale / 2 : Scale;
10956 
10957     // We need to round trip through the appropriate type for the shift.
10958     MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
10959     ShiftVT = ByteShift ? MVT::getVectorVT(MVT::i8, SizeInBits / 8)
10960                         : MVT::getVectorVT(ShiftSVT, Size / Scale);
10961     return (int)ShiftAmt;
10962   };
10963 
10964   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
10965   // keep doubling the size of the integer elements up to that. We can
10966   // then shift the elements of the integer vector by whole multiples of
10967   // their width within the elements of the larger integer vector. Test each
10968   // multiple to see if we can find a match with the moved element indices
10969   // and that the shifted in elements are all zeroable.
10970   unsigned MaxWidth = ((SizeInBits == 512) && !Subtarget.hasBWI() ? 64 : 128);
10971   for (int Scale = 2; Scale * ScalarSizeInBits <= MaxWidth; Scale *= 2)
10972     for (int Shift = 1; Shift != Scale; ++Shift)
10973       for (bool Left : {true, false})
10974         if (CheckZeros(Shift, Scale, Left)) {
10975           int ShiftAmt = MatchShift(Shift, Scale, Left);
10976           if (0 < ShiftAmt)
10977             return ShiftAmt;
10978         }
10979 
10980   // no match
10981   return -1;
10982 }
10983 
lowerVectorShuffleAsShift(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)10984 static SDValue lowerVectorShuffleAsShift(const SDLoc &DL, MVT VT, SDValue V1,
10985                                          SDValue V2, ArrayRef<int> Mask,
10986                                          const APInt &Zeroable,
10987                                          const X86Subtarget &Subtarget,
10988                                          SelectionDAG &DAG) {
10989   int Size = Mask.size();
10990   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
10991 
10992   MVT ShiftVT;
10993   SDValue V = V1;
10994   unsigned Opcode;
10995 
10996   // Try to match shuffle against V1 shift.
10997   int ShiftAmt = matchVectorShuffleAsShift(
10998       ShiftVT, Opcode, VT.getScalarSizeInBits(), Mask, 0, Zeroable, Subtarget);
10999 
11000   // If V1 failed, try to match shuffle against V2 shift.
11001   if (ShiftAmt < 0) {
11002     ShiftAmt =
11003         matchVectorShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
11004                                   Mask, Size, Zeroable, Subtarget);
11005     V = V2;
11006   }
11007 
11008   if (ShiftAmt < 0)
11009     return SDValue();
11010 
11011   assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
11012          "Illegal integer vector type");
11013   V = DAG.getBitcast(ShiftVT, V);
11014   V = DAG.getNode(Opcode, DL, ShiftVT, V,
11015                   DAG.getConstant(ShiftAmt, DL, MVT::i8));
11016   return DAG.getBitcast(VT, V);
11017 }
11018 
11019 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
11020 // Remainder of lower half result is zero and upper half is all undef.
matchVectorShuffleAsEXTRQ(MVT VT,SDValue & V1,SDValue & V2,ArrayRef<int> Mask,uint64_t & BitLen,uint64_t & BitIdx,const APInt & Zeroable)11021 static bool matchVectorShuffleAsEXTRQ(MVT VT, SDValue &V1, SDValue &V2,
11022                                       ArrayRef<int> Mask, uint64_t &BitLen,
11023                                       uint64_t &BitIdx, const APInt &Zeroable) {
11024   int Size = Mask.size();
11025   int HalfSize = Size / 2;
11026   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
11027   assert(!Zeroable.isAllOnesValue() && "Fully zeroable shuffle mask");
11028 
11029   // Upper half must be undefined.
11030   if (!isUndefInRange(Mask, HalfSize, HalfSize))
11031     return false;
11032 
11033   // Determine the extraction length from the part of the
11034   // lower half that isn't zeroable.
11035   int Len = HalfSize;
11036   for (; Len > 0; --Len)
11037     if (!Zeroable[Len - 1])
11038       break;
11039   assert(Len > 0 && "Zeroable shuffle mask");
11040 
11041   // Attempt to match first Len sequential elements from the lower half.
11042   SDValue Src;
11043   int Idx = -1;
11044   for (int i = 0; i != Len; ++i) {
11045     int M = Mask[i];
11046     if (M == SM_SentinelUndef)
11047       continue;
11048     SDValue &V = (M < Size ? V1 : V2);
11049     M = M % Size;
11050 
11051     // The extracted elements must start at a valid index and all mask
11052     // elements must be in the lower half.
11053     if (i > M || M >= HalfSize)
11054       return false;
11055 
11056     if (Idx < 0 || (Src == V && Idx == (M - i))) {
11057       Src = V;
11058       Idx = M - i;
11059       continue;
11060     }
11061     return false;
11062   }
11063 
11064   if (!Src || Idx < 0)
11065     return false;
11066 
11067   assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
11068   BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
11069   BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
11070   V1 = Src;
11071   return true;
11072 }
11073 
11074 // INSERTQ: Extract lowest Len elements from lower half of second source and
11075 // insert over first source, starting at Idx.
11076 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
matchVectorShuffleAsINSERTQ(MVT VT,SDValue & V1,SDValue & V2,ArrayRef<int> Mask,uint64_t & BitLen,uint64_t & BitIdx)11077 static bool matchVectorShuffleAsINSERTQ(MVT VT, SDValue &V1, SDValue &V2,
11078                                         ArrayRef<int> Mask, uint64_t &BitLen,
11079                                         uint64_t &BitIdx) {
11080   int Size = Mask.size();
11081   int HalfSize = Size / 2;
11082   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
11083 
11084   // Upper half must be undefined.
11085   if (!isUndefInRange(Mask, HalfSize, HalfSize))
11086     return false;
11087 
11088   for (int Idx = 0; Idx != HalfSize; ++Idx) {
11089     SDValue Base;
11090 
11091     // Attempt to match first source from mask before insertion point.
11092     if (isUndefInRange(Mask, 0, Idx)) {
11093       /* EMPTY */
11094     } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
11095       Base = V1;
11096     } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
11097       Base = V2;
11098     } else {
11099       continue;
11100     }
11101 
11102     // Extend the extraction length looking to match both the insertion of
11103     // the second source and the remaining elements of the first.
11104     for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
11105       SDValue Insert;
11106       int Len = Hi - Idx;
11107 
11108       // Match insertion.
11109       if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
11110         Insert = V1;
11111       } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
11112         Insert = V2;
11113       } else {
11114         continue;
11115       }
11116 
11117       // Match the remaining elements of the lower half.
11118       if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
11119         /* EMPTY */
11120       } else if ((!Base || (Base == V1)) &&
11121                  isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
11122         Base = V1;
11123       } else if ((!Base || (Base == V2)) &&
11124                  isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
11125                                             Size + Hi)) {
11126         Base = V2;
11127       } else {
11128         continue;
11129       }
11130 
11131       BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
11132       BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
11133       V1 = Base;
11134       V2 = Insert;
11135       return true;
11136     }
11137   }
11138 
11139   return false;
11140 }
11141 
11142 /// Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
lowerVectorShuffleWithSSE4A(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,SelectionDAG & DAG)11143 static SDValue lowerVectorShuffleWithSSE4A(const SDLoc &DL, MVT VT, SDValue V1,
11144                                            SDValue V2, ArrayRef<int> Mask,
11145                                            const APInt &Zeroable,
11146                                            SelectionDAG &DAG) {
11147   uint64_t BitLen, BitIdx;
11148   if (matchVectorShuffleAsEXTRQ(VT, V1, V2, Mask, BitLen, BitIdx, Zeroable))
11149     return DAG.getNode(X86ISD::EXTRQI, DL, VT, V1,
11150                        DAG.getConstant(BitLen, DL, MVT::i8),
11151                        DAG.getConstant(BitIdx, DL, MVT::i8));
11152 
11153   if (matchVectorShuffleAsINSERTQ(VT, V1, V2, Mask, BitLen, BitIdx))
11154     return DAG.getNode(X86ISD::INSERTQI, DL, VT, V1 ? V1 : DAG.getUNDEF(VT),
11155                        V2 ? V2 : DAG.getUNDEF(VT),
11156                        DAG.getConstant(BitLen, DL, MVT::i8),
11157                        DAG.getConstant(BitIdx, DL, MVT::i8));
11158 
11159   return SDValue();
11160 }
11161 
11162 /// Lower a vector shuffle as a zero or any extension.
11163 ///
11164 /// Given a specific number of elements, element bit width, and extension
11165 /// stride, produce either a zero or any extension based on the available
11166 /// features of the subtarget. The extended elements are consecutive and
11167 /// begin and can start from an offsetted element index in the input; to
11168 /// avoid excess shuffling the offset must either being in the bottom lane
11169 /// or at the start of a higher lane. All extended elements must be from
11170 /// the same lane.
lowerVectorShuffleAsSpecificZeroOrAnyExtend(const SDLoc & DL,MVT VT,int Scale,int Offset,bool AnyExt,SDValue InputV,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)11171 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
11172     const SDLoc &DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
11173     ArrayRef<int> Mask, const X86Subtarget &Subtarget, SelectionDAG &DAG) {
11174   assert(Scale > 1 && "Need a scale to extend.");
11175   int EltBits = VT.getScalarSizeInBits();
11176   int NumElements = VT.getVectorNumElements();
11177   int NumEltsPerLane = 128 / EltBits;
11178   int OffsetLane = Offset / NumEltsPerLane;
11179   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
11180          "Only 8, 16, and 32 bit elements can be extended.");
11181   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
11182   assert(0 <= Offset && "Extension offset must be positive.");
11183   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
11184          "Extension offset must be in the first lane or start an upper lane.");
11185 
11186   // Check that an index is in same lane as the base offset.
11187   auto SafeOffset = [&](int Idx) {
11188     return OffsetLane == (Idx / NumEltsPerLane);
11189   };
11190 
11191   // Shift along an input so that the offset base moves to the first element.
11192   auto ShuffleOffset = [&](SDValue V) {
11193     if (!Offset)
11194       return V;
11195 
11196     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
11197     for (int i = 0; i * Scale < NumElements; ++i) {
11198       int SrcIdx = i + Offset;
11199       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
11200     }
11201     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
11202   };
11203 
11204   // Found a valid zext mask! Try various lowering strategies based on the
11205   // input type and available ISA extensions.
11206   if (Subtarget.hasSSE41()) {
11207     // Not worth offsetting 128-bit vectors if scale == 2, a pattern using
11208     // PUNPCK will catch this in a later shuffle match.
11209     if (Offset && Scale == 2 && VT.is128BitVector())
11210       return SDValue();
11211     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
11212                                  NumElements / Scale);
11213     InputV = ShuffleOffset(InputV);
11214     InputV = getExtendInVec(/*Signed*/false, DL, ExtVT, InputV, DAG);
11215     return DAG.getBitcast(VT, InputV);
11216   }
11217 
11218   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
11219 
11220   // For any extends we can cheat for larger element sizes and use shuffle
11221   // instructions that can fold with a load and/or copy.
11222   if (AnyExt && EltBits == 32) {
11223     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
11224                          -1};
11225     return DAG.getBitcast(
11226         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
11227                         DAG.getBitcast(MVT::v4i32, InputV),
11228                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
11229   }
11230   if (AnyExt && EltBits == 16 && Scale > 2) {
11231     int PSHUFDMask[4] = {Offset / 2, -1,
11232                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
11233     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
11234                          DAG.getBitcast(MVT::v4i32, InputV),
11235                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
11236     int PSHUFWMask[4] = {1, -1, -1, -1};
11237     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
11238     return DAG.getBitcast(
11239         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
11240                         DAG.getBitcast(MVT::v8i16, InputV),
11241                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
11242   }
11243 
11244   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
11245   // to 64-bits.
11246   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget.hasSSE4A()) {
11247     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
11248     assert(VT.is128BitVector() && "Unexpected vector width!");
11249 
11250     int LoIdx = Offset * EltBits;
11251     SDValue Lo = DAG.getBitcast(
11252         MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
11253                                 DAG.getConstant(EltBits, DL, MVT::i8),
11254                                 DAG.getConstant(LoIdx, DL, MVT::i8)));
11255 
11256     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
11257         !SafeOffset(Offset + 1))
11258       return DAG.getBitcast(VT, Lo);
11259 
11260     int HiIdx = (Offset + 1) * EltBits;
11261     SDValue Hi = DAG.getBitcast(
11262         MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
11263                                 DAG.getConstant(EltBits, DL, MVT::i8),
11264                                 DAG.getConstant(HiIdx, DL, MVT::i8)));
11265     return DAG.getBitcast(VT,
11266                           DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
11267   }
11268 
11269   // If this would require more than 2 unpack instructions to expand, use
11270   // pshufb when available. We can only use more than 2 unpack instructions
11271   // when zero extending i8 elements which also makes it easier to use pshufb.
11272   if (Scale > 4 && EltBits == 8 && Subtarget.hasSSSE3()) {
11273     assert(NumElements == 16 && "Unexpected byte vector width!");
11274     SDValue PSHUFBMask[16];
11275     for (int i = 0; i < 16; ++i) {
11276       int Idx = Offset + (i / Scale);
11277       PSHUFBMask[i] = DAG.getConstant(
11278           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
11279     }
11280     InputV = DAG.getBitcast(MVT::v16i8, InputV);
11281     return DAG.getBitcast(
11282         VT, DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
11283                         DAG.getBuildVector(MVT::v16i8, DL, PSHUFBMask)));
11284   }
11285 
11286   // If we are extending from an offset, ensure we start on a boundary that
11287   // we can unpack from.
11288   int AlignToUnpack = Offset % (NumElements / Scale);
11289   if (AlignToUnpack) {
11290     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
11291     for (int i = AlignToUnpack; i < NumElements; ++i)
11292       ShMask[i - AlignToUnpack] = i;
11293     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
11294     Offset -= AlignToUnpack;
11295   }
11296 
11297   // Otherwise emit a sequence of unpacks.
11298   do {
11299     unsigned UnpackLoHi = X86ISD::UNPCKL;
11300     if (Offset >= (NumElements / 2)) {
11301       UnpackLoHi = X86ISD::UNPCKH;
11302       Offset -= (NumElements / 2);
11303     }
11304 
11305     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
11306     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
11307                          : getZeroVector(InputVT, Subtarget, DAG, DL);
11308     InputV = DAG.getBitcast(InputVT, InputV);
11309     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
11310     Scale /= 2;
11311     EltBits *= 2;
11312     NumElements /= 2;
11313   } while (Scale > 1);
11314   return DAG.getBitcast(VT, InputV);
11315 }
11316 
11317 /// Try to lower a vector shuffle as a zero extension on any microarch.
11318 ///
11319 /// This routine will try to do everything in its power to cleverly lower
11320 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
11321 /// check for the profitability of this lowering,  it tries to aggressively
11322 /// match this pattern. It will use all of the micro-architectural details it
11323 /// can to emit an efficient lowering. It handles both blends with all-zero
11324 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
11325 /// masking out later).
11326 ///
11327 /// The reason we have dedicated lowering for zext-style shuffles is that they
11328 /// are both incredibly common and often quite performance sensitive.
lowerVectorShuffleAsZeroOrAnyExtend(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)11329 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
11330     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
11331     const APInt &Zeroable, const X86Subtarget &Subtarget,
11332     SelectionDAG &DAG) {
11333   int Bits = VT.getSizeInBits();
11334   int NumLanes = Bits / 128;
11335   int NumElements = VT.getVectorNumElements();
11336   int NumEltsPerLane = NumElements / NumLanes;
11337   assert(VT.getScalarSizeInBits() <= 32 &&
11338          "Exceeds 32-bit integer zero extension limit");
11339   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
11340 
11341   // Define a helper function to check a particular ext-scale and lower to it if
11342   // valid.
11343   auto Lower = [&](int Scale) -> SDValue {
11344     SDValue InputV;
11345     bool AnyExt = true;
11346     int Offset = 0;
11347     int Matches = 0;
11348     for (int i = 0; i < NumElements; ++i) {
11349       int M = Mask[i];
11350       if (M < 0)
11351         continue; // Valid anywhere but doesn't tell us anything.
11352       if (i % Scale != 0) {
11353         // Each of the extended elements need to be zeroable.
11354         if (!Zeroable[i])
11355           return SDValue();
11356 
11357         // We no longer are in the anyext case.
11358         AnyExt = false;
11359         continue;
11360       }
11361 
11362       // Each of the base elements needs to be consecutive indices into the
11363       // same input vector.
11364       SDValue V = M < NumElements ? V1 : V2;
11365       M = M % NumElements;
11366       if (!InputV) {
11367         InputV = V;
11368         Offset = M - (i / Scale);
11369       } else if (InputV != V)
11370         return SDValue(); // Flip-flopping inputs.
11371 
11372       // Offset must start in the lowest 128-bit lane or at the start of an
11373       // upper lane.
11374       // FIXME: Is it ever worth allowing a negative base offset?
11375       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
11376             (Offset % NumEltsPerLane) == 0))
11377         return SDValue();
11378 
11379       // If we are offsetting, all referenced entries must come from the same
11380       // lane.
11381       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
11382         return SDValue();
11383 
11384       if ((M % NumElements) != (Offset + (i / Scale)))
11385         return SDValue(); // Non-consecutive strided elements.
11386       Matches++;
11387     }
11388 
11389     // If we fail to find an input, we have a zero-shuffle which should always
11390     // have already been handled.
11391     // FIXME: Maybe handle this here in case during blending we end up with one?
11392     if (!InputV)
11393       return SDValue();
11394 
11395     // If we are offsetting, don't extend if we only match a single input, we
11396     // can always do better by using a basic PSHUF or PUNPCK.
11397     if (Offset != 0 && Matches < 2)
11398       return SDValue();
11399 
11400     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
11401         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
11402   };
11403 
11404   // The widest scale possible for extending is to a 64-bit integer.
11405   assert(Bits % 64 == 0 &&
11406          "The number of bits in a vector must be divisible by 64 on x86!");
11407   int NumExtElements = Bits / 64;
11408 
11409   // Each iteration, try extending the elements half as much, but into twice as
11410   // many elements.
11411   for (; NumExtElements < NumElements; NumExtElements *= 2) {
11412     assert(NumElements % NumExtElements == 0 &&
11413            "The input vector size must be divisible by the extended size.");
11414     if (SDValue V = Lower(NumElements / NumExtElements))
11415       return V;
11416   }
11417 
11418   // General extends failed, but 128-bit vectors may be able to use MOVQ.
11419   if (Bits != 128)
11420     return SDValue();
11421 
11422   // Returns one of the source operands if the shuffle can be reduced to a
11423   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
11424   auto CanZExtLowHalf = [&]() {
11425     for (int i = NumElements / 2; i != NumElements; ++i)
11426       if (!Zeroable[i])
11427         return SDValue();
11428     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
11429       return V1;
11430     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
11431       return V2;
11432     return SDValue();
11433   };
11434 
11435   if (SDValue V = CanZExtLowHalf()) {
11436     V = DAG.getBitcast(MVT::v2i64, V);
11437     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
11438     return DAG.getBitcast(VT, V);
11439   }
11440 
11441   // No viable ext lowering found.
11442   return SDValue();
11443 }
11444 
11445 /// Try to get a scalar value for a specific element of a vector.
11446 ///
11447 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
getScalarValueForVectorElement(SDValue V,int Idx,SelectionDAG & DAG)11448 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
11449                                               SelectionDAG &DAG) {
11450   MVT VT = V.getSimpleValueType();
11451   MVT EltVT = VT.getVectorElementType();
11452   V = peekThroughBitcasts(V);
11453 
11454   // If the bitcasts shift the element size, we can't extract an equivalent
11455   // element from it.
11456   MVT NewVT = V.getSimpleValueType();
11457   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
11458     return SDValue();
11459 
11460   if (V.getOpcode() == ISD::BUILD_VECTOR ||
11461       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
11462     // Ensure the scalar operand is the same size as the destination.
11463     // FIXME: Add support for scalar truncation where possible.
11464     SDValue S = V.getOperand(Idx);
11465     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
11466       return DAG.getBitcast(EltVT, S);
11467   }
11468 
11469   return SDValue();
11470 }
11471 
11472 /// Helper to test for a load that can be folded with x86 shuffles.
11473 ///
11474 /// This is particularly important because the set of instructions varies
11475 /// significantly based on whether the operand is a load or not.
isShuffleFoldableLoad(SDValue V)11476 static bool isShuffleFoldableLoad(SDValue V) {
11477   V = peekThroughBitcasts(V);
11478   return ISD::isNON_EXTLoad(V.getNode());
11479 }
11480 
11481 /// Try to lower insertion of a single element into a zero vector.
11482 ///
11483 /// This is a common pattern that we have especially efficient patterns to lower
11484 /// across all subtarget feature sets.
lowerVectorShuffleAsElementInsertion(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)11485 static SDValue lowerVectorShuffleAsElementInsertion(
11486     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
11487     const APInt &Zeroable, const X86Subtarget &Subtarget,
11488     SelectionDAG &DAG) {
11489   MVT ExtVT = VT;
11490   MVT EltVT = VT.getVectorElementType();
11491 
11492   int V2Index =
11493       find_if(Mask, [&Mask](int M) { return M >= (int)Mask.size(); }) -
11494       Mask.begin();
11495   bool IsV1Zeroable = true;
11496   for (int i = 0, Size = Mask.size(); i < Size; ++i)
11497     if (i != V2Index && !Zeroable[i]) {
11498       IsV1Zeroable = false;
11499       break;
11500     }
11501 
11502   // Check for a single input from a SCALAR_TO_VECTOR node.
11503   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
11504   // all the smarts here sunk into that routine. However, the current
11505   // lowering of BUILD_VECTOR makes that nearly impossible until the old
11506   // vector shuffle lowering is dead.
11507   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
11508                                                DAG);
11509   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
11510     // We need to zext the scalar if it is smaller than an i32.
11511     V2S = DAG.getBitcast(EltVT, V2S);
11512     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
11513       // Using zext to expand a narrow element won't work for non-zero
11514       // insertions.
11515       if (!IsV1Zeroable)
11516         return SDValue();
11517 
11518       // Zero-extend directly to i32.
11519       ExtVT = MVT::getVectorVT(MVT::i32, ExtVT.getSizeInBits() / 32);
11520       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
11521     }
11522     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
11523   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
11524              EltVT == MVT::i16) {
11525     // Either not inserting from the low element of the input or the input
11526     // element size is too small to use VZEXT_MOVL to clear the high bits.
11527     return SDValue();
11528   }
11529 
11530   if (!IsV1Zeroable) {
11531     // If V1 can't be treated as a zero vector we have fewer options to lower
11532     // this. We can't support integer vectors or non-zero targets cheaply, and
11533     // the V1 elements can't be permuted in any way.
11534     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
11535     if (!VT.isFloatingPoint() || V2Index != 0)
11536       return SDValue();
11537     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
11538     V1Mask[V2Index] = -1;
11539     if (!isNoopShuffleMask(V1Mask))
11540       return SDValue();
11541     if (!VT.is128BitVector())
11542       return SDValue();
11543 
11544     // Otherwise, use MOVSD or MOVSS.
11545     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
11546            "Only two types of floating point element types to handle!");
11547     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
11548                        ExtVT, V1, V2);
11549   }
11550 
11551   // This lowering only works for the low element with floating point vectors.
11552   if (VT.isFloatingPoint() && V2Index != 0)
11553     return SDValue();
11554 
11555   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
11556   if (ExtVT != VT)
11557     V2 = DAG.getBitcast(VT, V2);
11558 
11559   if (V2Index != 0) {
11560     // If we have 4 or fewer lanes we can cheaply shuffle the element into
11561     // the desired position. Otherwise it is more efficient to do a vector
11562     // shift left. We know that we can do a vector shift left because all
11563     // the inputs are zero.
11564     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
11565       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
11566       V2Shuffle[V2Index] = 0;
11567       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
11568     } else {
11569       V2 = DAG.getBitcast(MVT::v16i8, V2);
11570       V2 = DAG.getNode(
11571           X86ISD::VSHLDQ, DL, MVT::v16i8, V2,
11572           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL, MVT::i8));
11573       V2 = DAG.getBitcast(VT, V2);
11574     }
11575   }
11576   return V2;
11577 }
11578 
11579 /// Try to lower broadcast of a single - truncated - integer element,
11580 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
11581 ///
11582 /// This assumes we have AVX2.
lowerVectorShuffleAsTruncBroadcast(const SDLoc & DL,MVT VT,SDValue V0,int BroadcastIdx,const X86Subtarget & Subtarget,SelectionDAG & DAG)11583 static SDValue lowerVectorShuffleAsTruncBroadcast(const SDLoc &DL, MVT VT,
11584                                                   SDValue V0, int BroadcastIdx,
11585                                                   const X86Subtarget &Subtarget,
11586                                                   SelectionDAG &DAG) {
11587   assert(Subtarget.hasAVX2() &&
11588          "We can only lower integer broadcasts with AVX2!");
11589 
11590   EVT EltVT = VT.getVectorElementType();
11591   EVT V0VT = V0.getValueType();
11592 
11593   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
11594   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
11595 
11596   EVT V0EltVT = V0VT.getVectorElementType();
11597   if (!V0EltVT.isInteger())
11598     return SDValue();
11599 
11600   const unsigned EltSize = EltVT.getSizeInBits();
11601   const unsigned V0EltSize = V0EltVT.getSizeInBits();
11602 
11603   // This is only a truncation if the original element type is larger.
11604   if (V0EltSize <= EltSize)
11605     return SDValue();
11606 
11607   assert(((V0EltSize % EltSize) == 0) &&
11608          "Scalar type sizes must all be powers of 2 on x86!");
11609 
11610   const unsigned V0Opc = V0.getOpcode();
11611   const unsigned Scale = V0EltSize / EltSize;
11612   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
11613 
11614   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
11615       V0Opc != ISD::BUILD_VECTOR)
11616     return SDValue();
11617 
11618   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
11619 
11620   // If we're extracting non-least-significant bits, shift so we can truncate.
11621   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
11622   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
11623   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
11624   if (const int OffsetIdx = BroadcastIdx % Scale)
11625     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
11626                          DAG.getConstant(OffsetIdx * EltSize, DL, MVT::i8));
11627 
11628   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
11629                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
11630 }
11631 
11632 /// Try to lower broadcast of a single element.
11633 ///
11634 /// For convenience, this code also bundles all of the subtarget feature set
11635 /// filtering. While a little annoying to re-dispatch on type here, there isn't
11636 /// a convenient way to factor it out.
lowerVectorShuffleAsBroadcast(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)11637 static SDValue lowerVectorShuffleAsBroadcast(const SDLoc &DL, MVT VT,
11638                                              SDValue V1, SDValue V2,
11639                                              ArrayRef<int> Mask,
11640                                              const X86Subtarget &Subtarget,
11641                                              SelectionDAG &DAG) {
11642   if (!((Subtarget.hasSSE3() && VT == MVT::v2f64) ||
11643         (Subtarget.hasAVX() && VT.isFloatingPoint()) ||
11644         (Subtarget.hasAVX2() && VT.isInteger())))
11645     return SDValue();
11646 
11647   // With MOVDDUP (v2f64) we can broadcast from a register or a load, otherwise
11648   // we can only broadcast from a register with AVX2.
11649   unsigned NumElts = Mask.size();
11650   unsigned Opcode = (VT == MVT::v2f64 && !Subtarget.hasAVX2())
11651                         ? X86ISD::MOVDDUP
11652                         : X86ISD::VBROADCAST;
11653   bool BroadcastFromReg = (Opcode == X86ISD::MOVDDUP) || Subtarget.hasAVX2();
11654 
11655   // Check that the mask is a broadcast.
11656   int BroadcastIdx = -1;
11657   for (int i = 0; i != (int)NumElts; ++i) {
11658     SmallVector<int, 8> BroadcastMask(NumElts, i);
11659     if (isShuffleEquivalent(V1, V2, Mask, BroadcastMask)) {
11660       BroadcastIdx = i;
11661       break;
11662     }
11663   }
11664 
11665   if (BroadcastIdx < 0)
11666     return SDValue();
11667   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
11668                                             "a sorted mask where the broadcast "
11669                                             "comes from V1.");
11670 
11671   // Go up the chain of (vector) values to find a scalar load that we can
11672   // combine with the broadcast.
11673   SDValue V = V1;
11674   for (;;) {
11675     switch (V.getOpcode()) {
11676     case ISD::BITCAST: {
11677       // Peek through bitcasts as long as BroadcastIdx can be adjusted.
11678       SDValue VSrc = V.getOperand(0);
11679       unsigned NumEltBits = V.getScalarValueSizeInBits();
11680       unsigned NumSrcBits = VSrc.getScalarValueSizeInBits();
11681       if ((NumEltBits % NumSrcBits) == 0)
11682         BroadcastIdx *= (NumEltBits / NumSrcBits);
11683       else if ((NumSrcBits % NumEltBits) == 0 &&
11684                (BroadcastIdx % (NumSrcBits / NumEltBits)) == 0)
11685         BroadcastIdx /= (NumSrcBits / NumEltBits);
11686       else
11687         break;
11688       V = VSrc;
11689       continue;
11690     }
11691     case ISD::CONCAT_VECTORS: {
11692       int OperandSize =
11693           V.getOperand(0).getSimpleValueType().getVectorNumElements();
11694       V = V.getOperand(BroadcastIdx / OperandSize);
11695       BroadcastIdx %= OperandSize;
11696       continue;
11697     }
11698     case ISD::INSERT_SUBVECTOR: {
11699       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
11700       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
11701       if (!ConstantIdx)
11702         break;
11703 
11704       int BeginIdx = (int)ConstantIdx->getZExtValue();
11705       int EndIdx =
11706           BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
11707       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
11708         BroadcastIdx -= BeginIdx;
11709         V = VInner;
11710       } else {
11711         V = VOuter;
11712       }
11713       continue;
11714     }
11715     }
11716     break;
11717   }
11718 
11719   // Ensure the source vector and BroadcastIdx are for a suitable type.
11720   if (VT.getScalarSizeInBits() != V.getScalarValueSizeInBits()) {
11721     unsigned NumEltBits = VT.getScalarSizeInBits();
11722     unsigned NumSrcBits = V.getScalarValueSizeInBits();
11723     if ((NumSrcBits % NumEltBits) == 0)
11724       BroadcastIdx *= (NumSrcBits / NumEltBits);
11725     else if ((NumEltBits % NumSrcBits) == 0 &&
11726              (BroadcastIdx % (NumEltBits / NumSrcBits)) == 0)
11727       BroadcastIdx /= (NumEltBits / NumSrcBits);
11728     else
11729       return SDValue();
11730 
11731     unsigned NumSrcElts = V.getValueSizeInBits() / NumEltBits;
11732     MVT SrcVT = MVT::getVectorVT(VT.getScalarType(), NumSrcElts);
11733     V = DAG.getBitcast(SrcVT, V);
11734   }
11735 
11736   // Check if this is a broadcast of a scalar. We special case lowering
11737   // for scalars so that we can more effectively fold with loads.
11738   // First, look through bitcast: if the original value has a larger element
11739   // type than the shuffle, the broadcast element is in essence truncated.
11740   // Make that explicit to ease folding.
11741   if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
11742     if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
11743             DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
11744       return TruncBroadcast;
11745 
11746   MVT BroadcastVT = VT;
11747 
11748   // Peek through any bitcast (only useful for loads).
11749   SDValue BC = peekThroughBitcasts(V);
11750 
11751   // Also check the simpler case, where we can directly reuse the scalar.
11752   if ((V.getOpcode() == ISD::BUILD_VECTOR && V.hasOneUse()) ||
11753       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
11754     V = V.getOperand(BroadcastIdx);
11755 
11756     // If we can't broadcast from a register, check that the input is a load.
11757     if (!BroadcastFromReg && !isShuffleFoldableLoad(V))
11758       return SDValue();
11759   } else if (MayFoldLoad(BC) && !cast<LoadSDNode>(BC)->isVolatile()) {
11760     // 32-bit targets need to load i64 as a f64 and then bitcast the result.
11761     if (!Subtarget.is64Bit() && VT.getScalarType() == MVT::i64) {
11762       BroadcastVT = MVT::getVectorVT(MVT::f64, VT.getVectorNumElements());
11763       Opcode = (BroadcastVT.is128BitVector() && !Subtarget.hasAVX2())
11764                    ? X86ISD::MOVDDUP
11765                    : Opcode;
11766     }
11767 
11768     // If we are broadcasting a load that is only used by the shuffle
11769     // then we can reduce the vector load to the broadcasted scalar load.
11770     LoadSDNode *Ld = cast<LoadSDNode>(BC);
11771     SDValue BaseAddr = Ld->getOperand(1);
11772     EVT SVT = BroadcastVT.getScalarType();
11773     unsigned Offset = BroadcastIdx * SVT.getStoreSize();
11774     SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
11775     V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
11776                     DAG.getMachineFunction().getMachineMemOperand(
11777                         Ld->getMemOperand(), Offset, SVT.getStoreSize()));
11778     DAG.makeEquivalentMemoryOrdering(Ld, V);
11779   } else if (!BroadcastFromReg) {
11780     // We can't broadcast from a vector register.
11781     return SDValue();
11782   } else if (BroadcastIdx != 0) {
11783     // We can only broadcast from the zero-element of a vector register,
11784     // but it can be advantageous to broadcast from the zero-element of a
11785     // subvector.
11786     if (!VT.is256BitVector() && !VT.is512BitVector())
11787       return SDValue();
11788 
11789     // VPERMQ/VPERMPD can perform the cross-lane shuffle directly.
11790     if (VT == MVT::v4f64 || VT == MVT::v4i64)
11791       return SDValue();
11792 
11793     // Only broadcast the zero-element of a 128-bit subvector.
11794     unsigned EltSize = VT.getScalarSizeInBits();
11795     if (((BroadcastIdx * EltSize) % 128) != 0)
11796       return SDValue();
11797 
11798     // The shuffle input might have been a bitcast we looked through; look at
11799     // the original input vector.  Emit an EXTRACT_SUBVECTOR of that type; we'll
11800     // later bitcast it to BroadcastVT.
11801     assert(V.getScalarValueSizeInBits() == BroadcastVT.getScalarSizeInBits() &&
11802            "Unexpected vector element size");
11803     assert((V.getValueSizeInBits() == 256 || V.getValueSizeInBits() == 512) &&
11804            "Unexpected vector size");
11805     V = extract128BitVector(V, BroadcastIdx, DAG, DL);
11806   }
11807 
11808   if (Opcode == X86ISD::MOVDDUP && !V.getValueType().isVector())
11809     V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
11810                     DAG.getBitcast(MVT::f64, V));
11811 
11812   // Bitcast back to the same scalar type as BroadcastVT.
11813   MVT SrcVT = V.getSimpleValueType();
11814   if (SrcVT.getScalarType() != BroadcastVT.getScalarType()) {
11815     assert(SrcVT.getScalarSizeInBits() == BroadcastVT.getScalarSizeInBits() &&
11816            "Unexpected vector element size");
11817     if (SrcVT.isVector()) {
11818       unsigned NumSrcElts = SrcVT.getVectorNumElements();
11819       SrcVT = MVT::getVectorVT(BroadcastVT.getScalarType(), NumSrcElts);
11820     } else {
11821       SrcVT = BroadcastVT.getScalarType();
11822     }
11823     V = DAG.getBitcast(SrcVT, V);
11824   }
11825 
11826   // 32-bit targets need to load i64 as a f64 and then bitcast the result.
11827   if (!Subtarget.is64Bit() && SrcVT == MVT::i64) {
11828     V = DAG.getBitcast(MVT::f64, V);
11829     unsigned NumBroadcastElts = BroadcastVT.getVectorNumElements();
11830     BroadcastVT = MVT::getVectorVT(MVT::f64, NumBroadcastElts);
11831   }
11832 
11833   // We only support broadcasting from 128-bit vectors to minimize the
11834   // number of patterns we need to deal with in isel. So extract down to
11835   // 128-bits, removing as many bitcasts as possible.
11836   if (SrcVT.getSizeInBits() > 128) {
11837     MVT ExtVT = MVT::getVectorVT(SrcVT.getScalarType(),
11838                                  128 / SrcVT.getScalarSizeInBits());
11839     V = extract128BitVector(peekThroughBitcasts(V), 0, DAG, DL);
11840     V = DAG.getBitcast(ExtVT, V);
11841   }
11842 
11843   return DAG.getBitcast(VT, DAG.getNode(Opcode, DL, BroadcastVT, V));
11844 }
11845 
11846 // Check for whether we can use INSERTPS to perform the shuffle. We only use
11847 // INSERTPS when the V1 elements are already in the correct locations
11848 // because otherwise we can just always use two SHUFPS instructions which
11849 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
11850 // perform INSERTPS if a single V1 element is out of place and all V2
11851 // elements are zeroable.
matchVectorShuffleAsInsertPS(SDValue & V1,SDValue & V2,unsigned & InsertPSMask,const APInt & Zeroable,ArrayRef<int> Mask,SelectionDAG & DAG)11852 static bool matchVectorShuffleAsInsertPS(SDValue &V1, SDValue &V2,
11853                                          unsigned &InsertPSMask,
11854                                          const APInt &Zeroable,
11855                                          ArrayRef<int> Mask,
11856                                          SelectionDAG &DAG) {
11857   assert(V1.getSimpleValueType().is128BitVector() && "Bad operand type!");
11858   assert(V2.getSimpleValueType().is128BitVector() && "Bad operand type!");
11859   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
11860 
11861   // Attempt to match INSERTPS with one element from VA or VB being
11862   // inserted into VA (or undef). If successful, V1, V2 and InsertPSMask
11863   // are updated.
11864   auto matchAsInsertPS = [&](SDValue VA, SDValue VB,
11865                              ArrayRef<int> CandidateMask) {
11866     unsigned ZMask = 0;
11867     int VADstIndex = -1;
11868     int VBDstIndex = -1;
11869     bool VAUsedInPlace = false;
11870 
11871     for (int i = 0; i < 4; ++i) {
11872       // Synthesize a zero mask from the zeroable elements (includes undefs).
11873       if (Zeroable[i]) {
11874         ZMask |= 1 << i;
11875         continue;
11876       }
11877 
11878       // Flag if we use any VA inputs in place.
11879       if (i == CandidateMask[i]) {
11880         VAUsedInPlace = true;
11881         continue;
11882       }
11883 
11884       // We can only insert a single non-zeroable element.
11885       if (VADstIndex >= 0 || VBDstIndex >= 0)
11886         return false;
11887 
11888       if (CandidateMask[i] < 4) {
11889         // VA input out of place for insertion.
11890         VADstIndex = i;
11891       } else {
11892         // VB input for insertion.
11893         VBDstIndex = i;
11894       }
11895     }
11896 
11897     // Don't bother if we have no (non-zeroable) element for insertion.
11898     if (VADstIndex < 0 && VBDstIndex < 0)
11899       return false;
11900 
11901     // Determine element insertion src/dst indices. The src index is from the
11902     // start of the inserted vector, not the start of the concatenated vector.
11903     unsigned VBSrcIndex = 0;
11904     if (VADstIndex >= 0) {
11905       // If we have a VA input out of place, we use VA as the V2 element
11906       // insertion and don't use the original V2 at all.
11907       VBSrcIndex = CandidateMask[VADstIndex];
11908       VBDstIndex = VADstIndex;
11909       VB = VA;
11910     } else {
11911       VBSrcIndex = CandidateMask[VBDstIndex] - 4;
11912     }
11913 
11914     // If no V1 inputs are used in place, then the result is created only from
11915     // the zero mask and the V2 insertion - so remove V1 dependency.
11916     if (!VAUsedInPlace)
11917       VA = DAG.getUNDEF(MVT::v4f32);
11918 
11919     // Update V1, V2 and InsertPSMask accordingly.
11920     V1 = VA;
11921     V2 = VB;
11922 
11923     // Insert the V2 element into the desired position.
11924     InsertPSMask = VBSrcIndex << 6 | VBDstIndex << 4 | ZMask;
11925     assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
11926     return true;
11927   };
11928 
11929   if (matchAsInsertPS(V1, V2, Mask))
11930     return true;
11931 
11932   // Commute and try again.
11933   SmallVector<int, 4> CommutedMask(Mask.begin(), Mask.end());
11934   ShuffleVectorSDNode::commuteMask(CommutedMask);
11935   if (matchAsInsertPS(V2, V1, CommutedMask))
11936     return true;
11937 
11938   return false;
11939 }
11940 
lowerVectorShuffleAsInsertPS(const SDLoc & DL,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,SelectionDAG & DAG)11941 static SDValue lowerVectorShuffleAsInsertPS(const SDLoc &DL, SDValue V1,
11942                                             SDValue V2, ArrayRef<int> Mask,
11943                                             const APInt &Zeroable,
11944                                             SelectionDAG &DAG) {
11945   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
11946   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
11947 
11948   // Attempt to match the insertps pattern.
11949   unsigned InsertPSMask;
11950   if (!matchVectorShuffleAsInsertPS(V1, V2, InsertPSMask, Zeroable, Mask, DAG))
11951     return SDValue();
11952 
11953   // Insert the V2 element into the desired position.
11954   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
11955                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
11956 }
11957 
11958 /// Try to lower a shuffle as a permute of the inputs followed by an
11959 /// UNPCK instruction.
11960 ///
11961 /// This specifically targets cases where we end up with alternating between
11962 /// the two inputs, and so can permute them into something that feeds a single
11963 /// UNPCK instruction. Note that this routine only targets integer vectors
11964 /// because for floating point vectors we have a generalized SHUFPS lowering
11965 /// strategy that handles everything that doesn't *exactly* match an unpack,
11966 /// making this clever lowering unnecessary.
lowerVectorShuffleAsPermuteAndUnpack(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)11967 static SDValue lowerVectorShuffleAsPermuteAndUnpack(
11968     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
11969     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
11970   assert(!VT.isFloatingPoint() &&
11971          "This routine only supports integer vectors.");
11972   assert(VT.is128BitVector() &&
11973          "This routine only works on 128-bit vectors.");
11974   assert(!V2.isUndef() &&
11975          "This routine should only be used when blending two inputs.");
11976   assert(Mask.size() >= 2 && "Single element masks are invalid.");
11977 
11978   int Size = Mask.size();
11979 
11980   int NumLoInputs =
11981       count_if(Mask, [Size](int M) { return M >= 0 && M % Size < Size / 2; });
11982   int NumHiInputs =
11983       count_if(Mask, [Size](int M) { return M % Size >= Size / 2; });
11984 
11985   bool UnpackLo = NumLoInputs >= NumHiInputs;
11986 
11987   auto TryUnpack = [&](int ScalarSize, int Scale) {
11988     SmallVector<int, 16> V1Mask((unsigned)Size, -1);
11989     SmallVector<int, 16> V2Mask((unsigned)Size, -1);
11990 
11991     for (int i = 0; i < Size; ++i) {
11992       if (Mask[i] < 0)
11993         continue;
11994 
11995       // Each element of the unpack contains Scale elements from this mask.
11996       int UnpackIdx = i / Scale;
11997 
11998       // We only handle the case where V1 feeds the first slots of the unpack.
11999       // We rely on canonicalization to ensure this is the case.
12000       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
12001         return SDValue();
12002 
12003       // Setup the mask for this input. The indexing is tricky as we have to
12004       // handle the unpack stride.
12005       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
12006       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
12007           Mask[i] % Size;
12008     }
12009 
12010     // If we will have to shuffle both inputs to use the unpack, check whether
12011     // we can just unpack first and shuffle the result. If so, skip this unpack.
12012     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
12013         !isNoopShuffleMask(V2Mask))
12014       return SDValue();
12015 
12016     // Shuffle the inputs into place.
12017     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
12018     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
12019 
12020     // Cast the inputs to the type we will use to unpack them.
12021     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), Size / Scale);
12022     V1 = DAG.getBitcast(UnpackVT, V1);
12023     V2 = DAG.getBitcast(UnpackVT, V2);
12024 
12025     // Unpack the inputs and cast the result back to the desired type.
12026     return DAG.getBitcast(
12027         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
12028                         UnpackVT, V1, V2));
12029   };
12030 
12031   // We try each unpack from the largest to the smallest to try and find one
12032   // that fits this mask.
12033   int OrigScalarSize = VT.getScalarSizeInBits();
12034   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2)
12035     if (SDValue Unpack = TryUnpack(ScalarSize, ScalarSize / OrigScalarSize))
12036       return Unpack;
12037 
12038   // If we're shuffling with a zero vector then we're better off not doing
12039   // VECTOR_SHUFFLE(UNPCK()) as we lose track of those zero elements.
12040   if (ISD::isBuildVectorAllZeros(V1.getNode()) ||
12041       ISD::isBuildVectorAllZeros(V2.getNode()))
12042     return SDValue();
12043 
12044   // If none of the unpack-rooted lowerings worked (or were profitable) try an
12045   // initial unpack.
12046   if (NumLoInputs == 0 || NumHiInputs == 0) {
12047     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
12048            "We have to have *some* inputs!");
12049     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
12050 
12051     // FIXME: We could consider the total complexity of the permute of each
12052     // possible unpacking. Or at the least we should consider how many
12053     // half-crossings are created.
12054     // FIXME: We could consider commuting the unpacks.
12055 
12056     SmallVector<int, 32> PermMask((unsigned)Size, -1);
12057     for (int i = 0; i < Size; ++i) {
12058       if (Mask[i] < 0)
12059         continue;
12060 
12061       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
12062 
12063       PermMask[i] =
12064           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
12065     }
12066     return DAG.getVectorShuffle(
12067         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
12068                             DL, VT, V1, V2),
12069         DAG.getUNDEF(VT), PermMask);
12070   }
12071 
12072   return SDValue();
12073 }
12074 
12075 /// Handle lowering of 2-lane 64-bit floating point shuffles.
12076 ///
12077 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
12078 /// support for floating point shuffles but not integer shuffles. These
12079 /// instructions will incur a domain crossing penalty on some chips though so
12080 /// it is better to avoid lowering through this for integer vectors where
12081 /// possible.
lowerV2F64VectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)12082 static SDValue lowerV2F64VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
12083                                        const APInt &Zeroable,
12084                                        SDValue V1, SDValue V2,
12085                                        const X86Subtarget &Subtarget,
12086                                        SelectionDAG &DAG) {
12087   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
12088   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
12089   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
12090 
12091   if (V2.isUndef()) {
12092     // Check for being able to broadcast a single element.
12093     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(
12094             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
12095       return Broadcast;
12096 
12097     // Straight shuffle of a single input vector. Simulate this by using the
12098     // single input as both of the "inputs" to this instruction..
12099     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
12100 
12101     if (Subtarget.hasAVX()) {
12102       // If we have AVX, we can use VPERMILPS which will allow folding a load
12103       // into the shuffle.
12104       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
12105                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
12106     }
12107 
12108     return DAG.getNode(
12109         X86ISD::SHUFP, DL, MVT::v2f64,
12110         Mask[0] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
12111         Mask[1] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
12112         DAG.getConstant(SHUFPDMask, DL, MVT::i8));
12113   }
12114   assert(Mask[0] >= 0 && "No undef lanes in multi-input v2 shuffles!");
12115   assert(Mask[1] >= 0 && "No undef lanes in multi-input v2 shuffles!");
12116   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
12117   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
12118 
12119   // When loading a scalar and then shuffling it into a vector we can often do
12120   // the insertion cheaply.
12121   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
12122           DL, MVT::v2f64, V1, V2, Mask, Zeroable, Subtarget, DAG))
12123     return Insertion;
12124   // Try inverting the insertion since for v2 masks it is easy to do and we
12125   // can't reliably sort the mask one way or the other.
12126   int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
12127                         Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
12128   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
12129           DL, MVT::v2f64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
12130     return Insertion;
12131 
12132   // Try to use one of the special instruction patterns to handle two common
12133   // blend patterns if a zero-blend above didn't work.
12134   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
12135       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
12136     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
12137       // We can either use a special instruction to load over the low double or
12138       // to move just the low double.
12139       return DAG.getNode(
12140           X86ISD::MOVSD, DL, MVT::v2f64, V2,
12141           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
12142 
12143   if (Subtarget.hasSSE41())
12144     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
12145                                                   Zeroable, Subtarget, DAG))
12146       return Blend;
12147 
12148   // Use dedicated unpack instructions for masks that match their pattern.
12149   if (SDValue V =
12150           lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
12151     return V;
12152 
12153   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
12154   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
12155                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
12156 }
12157 
12158 /// Handle lowering of 2-lane 64-bit integer shuffles.
12159 ///
12160 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
12161 /// the integer unit to minimize domain crossing penalties. However, for blends
12162 /// it falls back to the floating point shuffle operation with appropriate bit
12163 /// casting.
lowerV2I64VectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)12164 static SDValue lowerV2I64VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
12165                                        const APInt &Zeroable,
12166                                        SDValue V1, SDValue V2,
12167                                        const X86Subtarget &Subtarget,
12168                                        SelectionDAG &DAG) {
12169   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
12170   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
12171   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
12172 
12173   if (V2.isUndef()) {
12174     // Check for being able to broadcast a single element.
12175     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(
12176             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
12177       return Broadcast;
12178 
12179     // Straight shuffle of a single input vector. For everything from SSE2
12180     // onward this has a single fast instruction with no scary immediates.
12181     // We have to map the mask as it is actually a v4i32 shuffle instruction.
12182     V1 = DAG.getBitcast(MVT::v4i32, V1);
12183     int WidenedMask[4] = {
12184         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
12185         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
12186     return DAG.getBitcast(
12187         MVT::v2i64,
12188         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
12189                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
12190   }
12191   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
12192   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
12193   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
12194   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
12195 
12196   // Try to use shift instructions.
12197   if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask,
12198                                                 Zeroable, Subtarget, DAG))
12199     return Shift;
12200 
12201   // When loading a scalar and then shuffling it into a vector we can often do
12202   // the insertion cheaply.
12203   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
12204           DL, MVT::v2i64, V1, V2, Mask, Zeroable, Subtarget, DAG))
12205     return Insertion;
12206   // Try inverting the insertion since for v2 masks it is easy to do and we
12207   // can't reliably sort the mask one way or the other.
12208   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
12209   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
12210           DL, MVT::v2i64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
12211     return Insertion;
12212 
12213   // We have different paths for blend lowering, but they all must use the
12214   // *exact* same predicate.
12215   bool IsBlendSupported = Subtarget.hasSSE41();
12216   if (IsBlendSupported)
12217     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
12218                                                   Zeroable, Subtarget, DAG))
12219       return Blend;
12220 
12221   // Use dedicated unpack instructions for masks that match their pattern.
12222   if (SDValue V =
12223           lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
12224     return V;
12225 
12226   // Try to use byte rotation instructions.
12227   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
12228   if (Subtarget.hasSSSE3()) {
12229     if (Subtarget.hasVLX())
12230       if (SDValue Rotate = lowerVectorShuffleAsRotate(DL, MVT::v2i64, V1, V2,
12231                                                       Mask, Subtarget, DAG))
12232         return Rotate;
12233 
12234     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
12235             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
12236       return Rotate;
12237   }
12238 
12239   // If we have direct support for blends, we should lower by decomposing into
12240   // a permute. That will be faster than the domain cross.
12241   if (IsBlendSupported)
12242     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
12243                                                       Mask, Subtarget, DAG);
12244 
12245   // We implement this with SHUFPD which is pretty lame because it will likely
12246   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
12247   // However, all the alternatives are still more cycles and newer chips don't
12248   // have this problem. It would be really nice if x86 had better shuffles here.
12249   V1 = DAG.getBitcast(MVT::v2f64, V1);
12250   V2 = DAG.getBitcast(MVT::v2f64, V2);
12251   return DAG.getBitcast(MVT::v2i64,
12252                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
12253 }
12254 
12255 /// Test whether this can be lowered with a single SHUFPS instruction.
12256 ///
12257 /// This is used to disable more specialized lowerings when the shufps lowering
12258 /// will happen to be efficient.
isSingleSHUFPSMask(ArrayRef<int> Mask)12259 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
12260   // This routine only handles 128-bit shufps.
12261   assert(Mask.size() == 4 && "Unsupported mask size!");
12262   assert(Mask[0] >= -1 && Mask[0] < 8 && "Out of bound mask element!");
12263   assert(Mask[1] >= -1 && Mask[1] < 8 && "Out of bound mask element!");
12264   assert(Mask[2] >= -1 && Mask[2] < 8 && "Out of bound mask element!");
12265   assert(Mask[3] >= -1 && Mask[3] < 8 && "Out of bound mask element!");
12266 
12267   // To lower with a single SHUFPS we need to have the low half and high half
12268   // each requiring a single input.
12269   if (Mask[0] >= 0 && Mask[1] >= 0 && (Mask[0] < 4) != (Mask[1] < 4))
12270     return false;
12271   if (Mask[2] >= 0 && Mask[3] >= 0 && (Mask[2] < 4) != (Mask[3] < 4))
12272     return false;
12273 
12274   return true;
12275 }
12276 
12277 /// Lower a vector shuffle using the SHUFPS instruction.
12278 ///
12279 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
12280 /// It makes no assumptions about whether this is the *best* lowering, it simply
12281 /// uses it.
lowerVectorShuffleWithSHUFPS(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,SelectionDAG & DAG)12282 static SDValue lowerVectorShuffleWithSHUFPS(const SDLoc &DL, MVT VT,
12283                                             ArrayRef<int> Mask, SDValue V1,
12284                                             SDValue V2, SelectionDAG &DAG) {
12285   SDValue LowV = V1, HighV = V2;
12286   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
12287 
12288   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
12289 
12290   if (NumV2Elements == 1) {
12291     int V2Index = find_if(Mask, [](int M) { return M >= 4; }) - Mask.begin();
12292 
12293     // Compute the index adjacent to V2Index and in the same half by toggling
12294     // the low bit.
12295     int V2AdjIndex = V2Index ^ 1;
12296 
12297     if (Mask[V2AdjIndex] < 0) {
12298       // Handles all the cases where we have a single V2 element and an undef.
12299       // This will only ever happen in the high lanes because we commute the
12300       // vector otherwise.
12301       if (V2Index < 2)
12302         std::swap(LowV, HighV);
12303       NewMask[V2Index] -= 4;
12304     } else {
12305       // Handle the case where the V2 element ends up adjacent to a V1 element.
12306       // To make this work, blend them together as the first step.
12307       int V1Index = V2AdjIndex;
12308       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
12309       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
12310                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
12311 
12312       // Now proceed to reconstruct the final blend as we have the necessary
12313       // high or low half formed.
12314       if (V2Index < 2) {
12315         LowV = V2;
12316         HighV = V1;
12317       } else {
12318         HighV = V2;
12319       }
12320       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
12321       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
12322     }
12323   } else if (NumV2Elements == 2) {
12324     if (Mask[0] < 4 && Mask[1] < 4) {
12325       // Handle the easy case where we have V1 in the low lanes and V2 in the
12326       // high lanes.
12327       NewMask[2] -= 4;
12328       NewMask[3] -= 4;
12329     } else if (Mask[2] < 4 && Mask[3] < 4) {
12330       // We also handle the reversed case because this utility may get called
12331       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
12332       // arrange things in the right direction.
12333       NewMask[0] -= 4;
12334       NewMask[1] -= 4;
12335       HighV = V1;
12336       LowV = V2;
12337     } else {
12338       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
12339       // trying to place elements directly, just blend them and set up the final
12340       // shuffle to place them.
12341 
12342       // The first two blend mask elements are for V1, the second two are for
12343       // V2.
12344       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
12345                           Mask[2] < 4 ? Mask[2] : Mask[3],
12346                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
12347                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
12348       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
12349                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
12350 
12351       // Now we do a normal shuffle of V1 by giving V1 as both operands to
12352       // a blend.
12353       LowV = HighV = V1;
12354       NewMask[0] = Mask[0] < 4 ? 0 : 2;
12355       NewMask[1] = Mask[0] < 4 ? 2 : 0;
12356       NewMask[2] = Mask[2] < 4 ? 1 : 3;
12357       NewMask[3] = Mask[2] < 4 ? 3 : 1;
12358     }
12359   }
12360   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
12361                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
12362 }
12363 
12364 /// Lower 4-lane 32-bit floating point shuffles.
12365 ///
12366 /// Uses instructions exclusively from the floating point unit to minimize
12367 /// domain crossing penalties, as these are sufficient to implement all v4f32
12368 /// shuffles.
lowerV4F32VectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)12369 static SDValue lowerV4F32VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
12370                                        const APInt &Zeroable,
12371                                        SDValue V1, SDValue V2,
12372                                        const X86Subtarget &Subtarget,
12373                                        SelectionDAG &DAG) {
12374   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
12375   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
12376   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
12377 
12378   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
12379 
12380   if (NumV2Elements == 0) {
12381     // Check for being able to broadcast a single element.
12382     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(
12383             DL, MVT::v4f32, V1, V2, Mask, Subtarget, DAG))
12384       return Broadcast;
12385 
12386     // Use even/odd duplicate instructions for masks that match their pattern.
12387     if (Subtarget.hasSSE3()) {
12388       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
12389         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
12390       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
12391         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
12392     }
12393 
12394     if (Subtarget.hasAVX()) {
12395       // If we have AVX, we can use VPERMILPS which will allow folding a load
12396       // into the shuffle.
12397       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
12398                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
12399     }
12400 
12401     // Use MOVLHPS/MOVHLPS to simulate unary shuffles. These are only valid
12402     // in SSE1 because otherwise they are widened to v2f64 and never get here.
12403     if (!Subtarget.hasSSE2()) {
12404       if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1}))
12405         return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V1);
12406       if (isShuffleEquivalent(V1, V2, Mask, {2, 3, 2, 3}))
12407         return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V1, V1);
12408     }
12409 
12410     // Otherwise, use a straight shuffle of a single input vector. We pass the
12411     // input vector to both operands to simulate this with a SHUFPS.
12412     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
12413                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
12414   }
12415 
12416   // There are special ways we can lower some single-element blends. However, we
12417   // have custom ways we can lower more complex single-element blends below that
12418   // we defer to if both this and BLENDPS fail to match, so restrict this to
12419   // when the V2 input is targeting element 0 of the mask -- that is the fast
12420   // case here.
12421   if (NumV2Elements == 1 && Mask[0] >= 4)
12422     if (SDValue V = lowerVectorShuffleAsElementInsertion(
12423             DL, MVT::v4f32, V1, V2, Mask, Zeroable, Subtarget, DAG))
12424       return V;
12425 
12426   if (Subtarget.hasSSE41()) {
12427     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
12428                                                   Zeroable, Subtarget, DAG))
12429       return Blend;
12430 
12431     // Use INSERTPS if we can complete the shuffle efficiently.
12432     if (SDValue V =
12433             lowerVectorShuffleAsInsertPS(DL, V1, V2, Mask, Zeroable, DAG))
12434       return V;
12435 
12436     if (!isSingleSHUFPSMask(Mask))
12437       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
12438               DL, MVT::v4f32, V1, V2, Mask, DAG))
12439         return BlendPerm;
12440   }
12441 
12442   // Use low/high mov instructions. These are only valid in SSE1 because
12443   // otherwise they are widened to v2f64 and never get here.
12444   if (!Subtarget.hasSSE2()) {
12445     if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5}))
12446       return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V2);
12447     if (isShuffleEquivalent(V1, V2, Mask, {2, 3, 6, 7}))
12448       return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V2, V1);
12449   }
12450 
12451   // Use dedicated unpack instructions for masks that match their pattern.
12452   if (SDValue V =
12453           lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
12454     return V;
12455 
12456   // Otherwise fall back to a SHUFPS lowering strategy.
12457   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
12458 }
12459 
12460 /// Lower 4-lane i32 vector shuffles.
12461 ///
12462 /// We try to handle these with integer-domain shuffles where we can, but for
12463 /// blends we use the floating point domain blend instructions.
lowerV4I32VectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)12464 static SDValue lowerV4I32VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
12465                                        const APInt &Zeroable,
12466                                        SDValue V1, SDValue V2,
12467                                        const X86Subtarget &Subtarget,
12468                                        SelectionDAG &DAG) {
12469   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
12470   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
12471   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
12472 
12473   // Whenever we can lower this as a zext, that instruction is strictly faster
12474   // than any alternative. It also allows us to fold memory operands into the
12475   // shuffle in many cases.
12476   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
12477           DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
12478     return ZExt;
12479 
12480   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
12481 
12482   if (NumV2Elements == 0) {
12483     // Check for being able to broadcast a single element.
12484     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(
12485             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
12486       return Broadcast;
12487 
12488     // Straight shuffle of a single input vector. For everything from SSE2
12489     // onward this has a single fast instruction with no scary immediates.
12490     // We coerce the shuffle pattern to be compatible with UNPCK instructions
12491     // but we aren't actually going to use the UNPCK instruction because doing
12492     // so prevents folding a load into this instruction or making a copy.
12493     const int UnpackLoMask[] = {0, 0, 1, 1};
12494     const int UnpackHiMask[] = {2, 2, 3, 3};
12495     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
12496       Mask = UnpackLoMask;
12497     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
12498       Mask = UnpackHiMask;
12499 
12500     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
12501                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
12502   }
12503 
12504   // Try to use shift instructions.
12505   if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask,
12506                                                 Zeroable, Subtarget, DAG))
12507     return Shift;
12508 
12509   // There are special ways we can lower some single-element blends.
12510   if (NumV2Elements == 1)
12511     if (SDValue V = lowerVectorShuffleAsElementInsertion(
12512             DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
12513       return V;
12514 
12515   // We have different paths for blend lowering, but they all must use the
12516   // *exact* same predicate.
12517   bool IsBlendSupported = Subtarget.hasSSE41();
12518   if (IsBlendSupported)
12519     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
12520                                                   Zeroable, Subtarget, DAG))
12521       return Blend;
12522 
12523   if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask,
12524                                                    Zeroable, DAG))
12525     return Masked;
12526 
12527   // Use dedicated unpack instructions for masks that match their pattern.
12528   if (SDValue V =
12529           lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
12530     return V;
12531 
12532   // Try to use byte rotation instructions.
12533   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
12534   if (Subtarget.hasSSSE3()) {
12535     if (Subtarget.hasVLX())
12536       if (SDValue Rotate = lowerVectorShuffleAsRotate(DL, MVT::v4i32, V1, V2,
12537                                                       Mask, Subtarget, DAG))
12538         return Rotate;
12539 
12540     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
12541             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
12542       return Rotate;
12543   }
12544 
12545   // Assume that a single SHUFPS is faster than an alternative sequence of
12546   // multiple instructions (even if the CPU has a domain penalty).
12547   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
12548   if (!isSingleSHUFPSMask(Mask)) {
12549     // If we have direct support for blends, we should lower by decomposing into
12550     // a permute. That will be faster than the domain cross.
12551     if (IsBlendSupported)
12552       return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
12553                                                         Mask, Subtarget, DAG);
12554 
12555     // Try to lower by permuting the inputs into an unpack instruction.
12556     if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
12557             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
12558       return Unpack;
12559   }
12560 
12561   // We implement this with SHUFPS because it can blend from two vectors.
12562   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
12563   // up the inputs, bypassing domain shift penalties that we would incur if we
12564   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
12565   // relevant.
12566   SDValue CastV1 = DAG.getBitcast(MVT::v4f32, V1);
12567   SDValue CastV2 = DAG.getBitcast(MVT::v4f32, V2);
12568   SDValue ShufPS = DAG.getVectorShuffle(MVT::v4f32, DL, CastV1, CastV2, Mask);
12569   return DAG.getBitcast(MVT::v4i32, ShufPS);
12570 }
12571 
12572 /// Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
12573 /// shuffle lowering, and the most complex part.
12574 ///
12575 /// The lowering strategy is to try to form pairs of input lanes which are
12576 /// targeted at the same half of the final vector, and then use a dword shuffle
12577 /// to place them onto the right half, and finally unpack the paired lanes into
12578 /// their final position.
12579 ///
12580 /// The exact breakdown of how to form these dword pairs and align them on the
12581 /// correct sides is really tricky. See the comments within the function for
12582 /// more of the details.
12583 ///
12584 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
12585 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
12586 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
12587 /// vector, form the analogous 128-bit 8-element Mask.
lowerV8I16GeneralSingleInputVectorShuffle(const SDLoc & DL,MVT VT,SDValue V,MutableArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)12588 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
12589     const SDLoc &DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
12590     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
12591   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
12592   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
12593 
12594   assert(Mask.size() == 8 && "Shuffle mask length doesn't match!");
12595   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
12596   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
12597 
12598   // Attempt to directly match PSHUFLW or PSHUFHW.
12599   if (isUndefOrInRange(LoMask, 0, 4) &&
12600       isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
12601     return DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
12602                        getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
12603   }
12604   if (isUndefOrInRange(HiMask, 4, 8) &&
12605       isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
12606     for (int i = 0; i != 4; ++i)
12607       HiMask[i] = (HiMask[i] < 0 ? HiMask[i] : (HiMask[i] - 4));
12608     return DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
12609                        getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
12610   }
12611 
12612   SmallVector<int, 4> LoInputs;
12613   copy_if(LoMask, std::back_inserter(LoInputs), [](int M) { return M >= 0; });
12614   array_pod_sort(LoInputs.begin(), LoInputs.end());
12615   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
12616   SmallVector<int, 4> HiInputs;
12617   copy_if(HiMask, std::back_inserter(HiInputs), [](int M) { return M >= 0; });
12618   array_pod_sort(HiInputs.begin(), HiInputs.end());
12619   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
12620   int NumLToL =
12621       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
12622   int NumHToL = LoInputs.size() - NumLToL;
12623   int NumLToH =
12624       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
12625   int NumHToH = HiInputs.size() - NumLToH;
12626   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
12627   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
12628   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
12629   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
12630 
12631   // If we are shuffling values from one half - check how many different DWORD
12632   // pairs we need to create. If only 1 or 2 then we can perform this as a
12633   // PSHUFLW/PSHUFHW + PSHUFD instead of the PSHUFD+PSHUFLW+PSHUFHW chain below.
12634   auto ShuffleDWordPairs = [&](ArrayRef<int> PSHUFHalfMask,
12635                                ArrayRef<int> PSHUFDMask, unsigned ShufWOp) {
12636     V = DAG.getNode(ShufWOp, DL, VT, V,
12637                     getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
12638     V = DAG.getBitcast(PSHUFDVT, V);
12639     V = DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, V,
12640                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
12641     return DAG.getBitcast(VT, V);
12642   };
12643 
12644   if ((NumHToL + NumHToH) == 0 || (NumLToL + NumLToH) == 0) {
12645     int PSHUFDMask[4] = { -1, -1, -1, -1 };
12646     SmallVector<std::pair<int, int>, 4> DWordPairs;
12647     int DOffset = ((NumHToL + NumHToH) == 0 ? 0 : 2);
12648 
12649     // Collect the different DWORD pairs.
12650     for (int DWord = 0; DWord != 4; ++DWord) {
12651       int M0 = Mask[2 * DWord + 0];
12652       int M1 = Mask[2 * DWord + 1];
12653       M0 = (M0 >= 0 ? M0 % 4 : M0);
12654       M1 = (M1 >= 0 ? M1 % 4 : M1);
12655       if (M0 < 0 && M1 < 0)
12656         continue;
12657 
12658       bool Match = false;
12659       for (int j = 0, e = DWordPairs.size(); j < e; ++j) {
12660         auto &DWordPair = DWordPairs[j];
12661         if ((M0 < 0 || isUndefOrEqual(DWordPair.first, M0)) &&
12662             (M1 < 0 || isUndefOrEqual(DWordPair.second, M1))) {
12663           DWordPair.first = (M0 >= 0 ? M0 : DWordPair.first);
12664           DWordPair.second = (M1 >= 0 ? M1 : DWordPair.second);
12665           PSHUFDMask[DWord] = DOffset + j;
12666           Match = true;
12667           break;
12668         }
12669       }
12670       if (!Match) {
12671         PSHUFDMask[DWord] = DOffset + DWordPairs.size();
12672         DWordPairs.push_back(std::make_pair(M0, M1));
12673       }
12674     }
12675 
12676     if (DWordPairs.size() <= 2) {
12677       DWordPairs.resize(2, std::make_pair(-1, -1));
12678       int PSHUFHalfMask[4] = {DWordPairs[0].first, DWordPairs[0].second,
12679                               DWordPairs[1].first, DWordPairs[1].second};
12680       if ((NumHToL + NumHToH) == 0)
12681         return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFLW);
12682       if ((NumLToL + NumLToH) == 0)
12683         return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFHW);
12684     }
12685   }
12686 
12687   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
12688   // such inputs we can swap two of the dwords across the half mark and end up
12689   // with <=2 inputs to each half in each half. Once there, we can fall through
12690   // to the generic code below. For example:
12691   //
12692   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
12693   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
12694   //
12695   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
12696   // and an existing 2-into-2 on the other half. In this case we may have to
12697   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
12698   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
12699   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
12700   // because any other situation (including a 3-into-1 or 1-into-3 in the other
12701   // half than the one we target for fixing) will be fixed when we re-enter this
12702   // path. We will also combine away any sequence of PSHUFD instructions that
12703   // result into a single instruction. Here is an example of the tricky case:
12704   //
12705   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
12706   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
12707   //
12708   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
12709   //
12710   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
12711   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
12712   //
12713   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
12714   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
12715   //
12716   // The result is fine to be handled by the generic logic.
12717   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
12718                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
12719                           int AOffset, int BOffset) {
12720     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
12721            "Must call this with A having 3 or 1 inputs from the A half.");
12722     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
12723            "Must call this with B having 1 or 3 inputs from the B half.");
12724     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
12725            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
12726 
12727     bool ThreeAInputs = AToAInputs.size() == 3;
12728 
12729     // Compute the index of dword with only one word among the three inputs in
12730     // a half by taking the sum of the half with three inputs and subtracting
12731     // the sum of the actual three inputs. The difference is the remaining
12732     // slot.
12733     int ADWord, BDWord;
12734     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
12735     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
12736     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
12737     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
12738     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
12739     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
12740     int TripleNonInputIdx =
12741         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
12742     TripleDWord = TripleNonInputIdx / 2;
12743 
12744     // We use xor with one to compute the adjacent DWord to whichever one the
12745     // OneInput is in.
12746     OneInputDWord = (OneInput / 2) ^ 1;
12747 
12748     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
12749     // and BToA inputs. If there is also such a problem with the BToB and AToB
12750     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
12751     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
12752     // is essential that we don't *create* a 3<-1 as then we might oscillate.
12753     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
12754       // Compute how many inputs will be flipped by swapping these DWords. We
12755       // need
12756       // to balance this to ensure we don't form a 3-1 shuffle in the other
12757       // half.
12758       int NumFlippedAToBInputs =
12759           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
12760           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
12761       int NumFlippedBToBInputs =
12762           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
12763           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
12764       if ((NumFlippedAToBInputs == 1 &&
12765            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
12766           (NumFlippedBToBInputs == 1 &&
12767            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
12768         // We choose whether to fix the A half or B half based on whether that
12769         // half has zero flipped inputs. At zero, we may not be able to fix it
12770         // with that half. We also bias towards fixing the B half because that
12771         // will more commonly be the high half, and we have to bias one way.
12772         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
12773                                                        ArrayRef<int> Inputs) {
12774           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
12775           bool IsFixIdxInput = is_contained(Inputs, PinnedIdx ^ 1);
12776           // Determine whether the free index is in the flipped dword or the
12777           // unflipped dword based on where the pinned index is. We use this bit
12778           // in an xor to conditionally select the adjacent dword.
12779           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
12780           bool IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
12781           if (IsFixIdxInput == IsFixFreeIdxInput)
12782             FixFreeIdx += 1;
12783           IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
12784           assert(IsFixIdxInput != IsFixFreeIdxInput &&
12785                  "We need to be changing the number of flipped inputs!");
12786           int PSHUFHalfMask[] = {0, 1, 2, 3};
12787           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
12788           V = DAG.getNode(
12789               FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
12790               MVT::getVectorVT(MVT::i16, V.getValueSizeInBits() / 16), V,
12791               getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
12792 
12793           for (int &M : Mask)
12794             if (M >= 0 && M == FixIdx)
12795               M = FixFreeIdx;
12796             else if (M >= 0 && M == FixFreeIdx)
12797               M = FixIdx;
12798         };
12799         if (NumFlippedBToBInputs != 0) {
12800           int BPinnedIdx =
12801               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
12802           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
12803         } else {
12804           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
12805           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
12806           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
12807         }
12808       }
12809     }
12810 
12811     int PSHUFDMask[] = {0, 1, 2, 3};
12812     PSHUFDMask[ADWord] = BDWord;
12813     PSHUFDMask[BDWord] = ADWord;
12814     V = DAG.getBitcast(
12815         VT,
12816         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
12817                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
12818 
12819     // Adjust the mask to match the new locations of A and B.
12820     for (int &M : Mask)
12821       if (M >= 0 && M/2 == ADWord)
12822         M = 2 * BDWord + M % 2;
12823       else if (M >= 0 && M/2 == BDWord)
12824         M = 2 * ADWord + M % 2;
12825 
12826     // Recurse back into this routine to re-compute state now that this isn't
12827     // a 3 and 1 problem.
12828     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
12829                                                      DAG);
12830   };
12831   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
12832     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
12833   if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
12834     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
12835 
12836   // At this point there are at most two inputs to the low and high halves from
12837   // each half. That means the inputs can always be grouped into dwords and
12838   // those dwords can then be moved to the correct half with a dword shuffle.
12839   // We use at most one low and one high word shuffle to collect these paired
12840   // inputs into dwords, and finally a dword shuffle to place them.
12841   int PSHUFLMask[4] = {-1, -1, -1, -1};
12842   int PSHUFHMask[4] = {-1, -1, -1, -1};
12843   int PSHUFDMask[4] = {-1, -1, -1, -1};
12844 
12845   // First fix the masks for all the inputs that are staying in their
12846   // original halves. This will then dictate the targets of the cross-half
12847   // shuffles.
12848   auto fixInPlaceInputs =
12849       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
12850                     MutableArrayRef<int> SourceHalfMask,
12851                     MutableArrayRef<int> HalfMask, int HalfOffset) {
12852     if (InPlaceInputs.empty())
12853       return;
12854     if (InPlaceInputs.size() == 1) {
12855       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
12856           InPlaceInputs[0] - HalfOffset;
12857       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
12858       return;
12859     }
12860     if (IncomingInputs.empty()) {
12861       // Just fix all of the in place inputs.
12862       for (int Input : InPlaceInputs) {
12863         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
12864         PSHUFDMask[Input / 2] = Input / 2;
12865       }
12866       return;
12867     }
12868 
12869     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
12870     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
12871         InPlaceInputs[0] - HalfOffset;
12872     // Put the second input next to the first so that they are packed into
12873     // a dword. We find the adjacent index by toggling the low bit.
12874     int AdjIndex = InPlaceInputs[0] ^ 1;
12875     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
12876     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
12877     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
12878   };
12879   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
12880   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
12881 
12882   // Now gather the cross-half inputs and place them into a free dword of
12883   // their target half.
12884   // FIXME: This operation could almost certainly be simplified dramatically to
12885   // look more like the 3-1 fixing operation.
12886   auto moveInputsToRightHalf = [&PSHUFDMask](
12887       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
12888       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
12889       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
12890       int DestOffset) {
12891     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
12892       return SourceHalfMask[Word] >= 0 && SourceHalfMask[Word] != Word;
12893     };
12894     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
12895                                                int Word) {
12896       int LowWord = Word & ~1;
12897       int HighWord = Word | 1;
12898       return isWordClobbered(SourceHalfMask, LowWord) ||
12899              isWordClobbered(SourceHalfMask, HighWord);
12900     };
12901 
12902     if (IncomingInputs.empty())
12903       return;
12904 
12905     if (ExistingInputs.empty()) {
12906       // Map any dwords with inputs from them into the right half.
12907       for (int Input : IncomingInputs) {
12908         // If the source half mask maps over the inputs, turn those into
12909         // swaps and use the swapped lane.
12910         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
12911           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] < 0) {
12912             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
12913                 Input - SourceOffset;
12914             // We have to swap the uses in our half mask in one sweep.
12915             for (int &M : HalfMask)
12916               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
12917                 M = Input;
12918               else if (M == Input)
12919                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
12920           } else {
12921             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
12922                        Input - SourceOffset &&
12923                    "Previous placement doesn't match!");
12924           }
12925           // Note that this correctly re-maps both when we do a swap and when
12926           // we observe the other side of the swap above. We rely on that to
12927           // avoid swapping the members of the input list directly.
12928           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
12929         }
12930 
12931         // Map the input's dword into the correct half.
12932         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] < 0)
12933           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
12934         else
12935           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
12936                      Input / 2 &&
12937                  "Previous placement doesn't match!");
12938       }
12939 
12940       // And just directly shift any other-half mask elements to be same-half
12941       // as we will have mirrored the dword containing the element into the
12942       // same position within that half.
12943       for (int &M : HalfMask)
12944         if (M >= SourceOffset && M < SourceOffset + 4) {
12945           M = M - SourceOffset + DestOffset;
12946           assert(M >= 0 && "This should never wrap below zero!");
12947         }
12948       return;
12949     }
12950 
12951     // Ensure we have the input in a viable dword of its current half. This
12952     // is particularly tricky because the original position may be clobbered
12953     // by inputs being moved and *staying* in that half.
12954     if (IncomingInputs.size() == 1) {
12955       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
12956         int InputFixed = find(SourceHalfMask, -1) - std::begin(SourceHalfMask) +
12957                          SourceOffset;
12958         SourceHalfMask[InputFixed - SourceOffset] =
12959             IncomingInputs[0] - SourceOffset;
12960         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
12961                      InputFixed);
12962         IncomingInputs[0] = InputFixed;
12963       }
12964     } else if (IncomingInputs.size() == 2) {
12965       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
12966           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
12967         // We have two non-adjacent or clobbered inputs we need to extract from
12968         // the source half. To do this, we need to map them into some adjacent
12969         // dword slot in the source mask.
12970         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
12971                               IncomingInputs[1] - SourceOffset};
12972 
12973         // If there is a free slot in the source half mask adjacent to one of
12974         // the inputs, place the other input in it. We use (Index XOR 1) to
12975         // compute an adjacent index.
12976         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
12977             SourceHalfMask[InputsFixed[0] ^ 1] < 0) {
12978           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
12979           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
12980           InputsFixed[1] = InputsFixed[0] ^ 1;
12981         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
12982                    SourceHalfMask[InputsFixed[1] ^ 1] < 0) {
12983           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
12984           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
12985           InputsFixed[0] = InputsFixed[1] ^ 1;
12986         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] < 0 &&
12987                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] < 0) {
12988           // The two inputs are in the same DWord but it is clobbered and the
12989           // adjacent DWord isn't used at all. Move both inputs to the free
12990           // slot.
12991           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
12992           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
12993           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
12994           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
12995         } else {
12996           // The only way we hit this point is if there is no clobbering
12997           // (because there are no off-half inputs to this half) and there is no
12998           // free slot adjacent to one of the inputs. In this case, we have to
12999           // swap an input with a non-input.
13000           for (int i = 0; i < 4; ++i)
13001             assert((SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) &&
13002                    "We can't handle any clobbers here!");
13003           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
13004                  "Cannot have adjacent inputs here!");
13005 
13006           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
13007           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
13008 
13009           // We also have to update the final source mask in this case because
13010           // it may need to undo the above swap.
13011           for (int &M : FinalSourceHalfMask)
13012             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
13013               M = InputsFixed[1] + SourceOffset;
13014             else if (M == InputsFixed[1] + SourceOffset)
13015               M = (InputsFixed[0] ^ 1) + SourceOffset;
13016 
13017           InputsFixed[1] = InputsFixed[0] ^ 1;
13018         }
13019 
13020         // Point everything at the fixed inputs.
13021         for (int &M : HalfMask)
13022           if (M == IncomingInputs[0])
13023             M = InputsFixed[0] + SourceOffset;
13024           else if (M == IncomingInputs[1])
13025             M = InputsFixed[1] + SourceOffset;
13026 
13027         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
13028         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
13029       }
13030     } else {
13031       llvm_unreachable("Unhandled input size!");
13032     }
13033 
13034     // Now hoist the DWord down to the right half.
13035     int FreeDWord = (PSHUFDMask[DestOffset / 2] < 0 ? 0 : 1) + DestOffset / 2;
13036     assert(PSHUFDMask[FreeDWord] < 0 && "DWord not free");
13037     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
13038     for (int &M : HalfMask)
13039       for (int Input : IncomingInputs)
13040         if (M == Input)
13041           M = FreeDWord * 2 + Input % 2;
13042   };
13043   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
13044                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
13045   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
13046                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
13047 
13048   // Now enact all the shuffles we've computed to move the inputs into their
13049   // target half.
13050   if (!isNoopShuffleMask(PSHUFLMask))
13051     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
13052                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
13053   if (!isNoopShuffleMask(PSHUFHMask))
13054     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
13055                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
13056   if (!isNoopShuffleMask(PSHUFDMask))
13057     V = DAG.getBitcast(
13058         VT,
13059         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
13060                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
13061 
13062   // At this point, each half should contain all its inputs, and we can then
13063   // just shuffle them into their final position.
13064   assert(count_if(LoMask, [](int M) { return M >= 4; }) == 0 &&
13065          "Failed to lift all the high half inputs to the low mask!");
13066   assert(count_if(HiMask, [](int M) { return M >= 0 && M < 4; }) == 0 &&
13067          "Failed to lift all the low half inputs to the high mask!");
13068 
13069   // Do a half shuffle for the low mask.
13070   if (!isNoopShuffleMask(LoMask))
13071     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
13072                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
13073 
13074   // Do a half shuffle with the high mask after shifting its values down.
13075   for (int &M : HiMask)
13076     if (M >= 0)
13077       M -= 4;
13078   if (!isNoopShuffleMask(HiMask))
13079     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
13080                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
13081 
13082   return V;
13083 }
13084 
13085 /// Helper to form a PSHUFB-based shuffle+blend, opportunistically avoiding the
13086 /// blend if only one input is used.
lowerVectorShuffleAsBlendOfPSHUFBs(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,SelectionDAG & DAG,bool & V1InUse,bool & V2InUse)13087 static SDValue lowerVectorShuffleAsBlendOfPSHUFBs(
13088     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13089     const APInt &Zeroable, SelectionDAG &DAG, bool &V1InUse, bool &V2InUse) {
13090   assert(!is128BitLaneCrossingShuffleMask(VT, Mask) &&
13091          "Lane crossing shuffle masks not supported");
13092 
13093   int NumBytes = VT.getSizeInBits() / 8;
13094   int Size = Mask.size();
13095   int Scale = NumBytes / Size;
13096 
13097   SmallVector<SDValue, 64> V1Mask(NumBytes, DAG.getUNDEF(MVT::i8));
13098   SmallVector<SDValue, 64> V2Mask(NumBytes, DAG.getUNDEF(MVT::i8));
13099   V1InUse = false;
13100   V2InUse = false;
13101 
13102   for (int i = 0; i < NumBytes; ++i) {
13103     int M = Mask[i / Scale];
13104     if (M < 0)
13105       continue;
13106 
13107     const int ZeroMask = 0x80;
13108     int V1Idx = M < Size ? M * Scale + i % Scale : ZeroMask;
13109     int V2Idx = M < Size ? ZeroMask : (M - Size) * Scale + i % Scale;
13110     if (Zeroable[i / Scale])
13111       V1Idx = V2Idx = ZeroMask;
13112 
13113     V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
13114     V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
13115     V1InUse |= (ZeroMask != V1Idx);
13116     V2InUse |= (ZeroMask != V2Idx);
13117   }
13118 
13119   MVT ShufVT = MVT::getVectorVT(MVT::i8, NumBytes);
13120   if (V1InUse)
13121     V1 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V1),
13122                      DAG.getBuildVector(ShufVT, DL, V1Mask));
13123   if (V2InUse)
13124     V2 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V2),
13125                      DAG.getBuildVector(ShufVT, DL, V2Mask));
13126 
13127   // If we need shuffled inputs from both, blend the two.
13128   SDValue V;
13129   if (V1InUse && V2InUse)
13130     V = DAG.getNode(ISD::OR, DL, ShufVT, V1, V2);
13131   else
13132     V = V1InUse ? V1 : V2;
13133 
13134   // Cast the result back to the correct type.
13135   return DAG.getBitcast(VT, V);
13136 }
13137 
13138 /// Generic lowering of 8-lane i16 shuffles.
13139 ///
13140 /// This handles both single-input shuffles and combined shuffle/blends with
13141 /// two inputs. The single input shuffles are immediately delegated to
13142 /// a dedicated lowering routine.
13143 ///
13144 /// The blends are lowered in one of three fundamental ways. If there are few
13145 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
13146 /// of the input is significantly cheaper when lowered as an interleaving of
13147 /// the two inputs, try to interleave them. Otherwise, blend the low and high
13148 /// halves of the inputs separately (making them have relatively few inputs)
13149 /// and then concatenate them.
lowerV8I16VectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)13150 static SDValue lowerV8I16VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
13151                                        const APInt &Zeroable,
13152                                        SDValue V1, SDValue V2,
13153                                        const X86Subtarget &Subtarget,
13154                                        SelectionDAG &DAG) {
13155   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
13156   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
13157   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
13158 
13159   // Whenever we can lower this as a zext, that instruction is strictly faster
13160   // than any alternative.
13161   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
13162           DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
13163     return ZExt;
13164 
13165   int NumV2Inputs = count_if(Mask, [](int M) { return M >= 8; });
13166 
13167   if (NumV2Inputs == 0) {
13168     // Check for being able to broadcast a single element.
13169     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(
13170             DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
13171       return Broadcast;
13172 
13173     // Try to use shift instructions.
13174     if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask,
13175                                                   Zeroable, Subtarget, DAG))
13176       return Shift;
13177 
13178     // Use dedicated unpack instructions for masks that match their pattern.
13179     if (SDValue V =
13180             lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
13181       return V;
13182 
13183     // Use dedicated pack instructions for masks that match their pattern.
13184     if (SDValue V = lowerVectorShuffleWithPACK(DL, MVT::v8i16, Mask, V1, V2,
13185                                                DAG, Subtarget))
13186       return V;
13187 
13188     // Try to use byte rotation instructions.
13189     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
13190                                                         Mask, Subtarget, DAG))
13191       return Rotate;
13192 
13193     // Make a copy of the mask so it can be modified.
13194     SmallVector<int, 8> MutableMask(Mask.begin(), Mask.end());
13195     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1,
13196                                                      MutableMask, Subtarget,
13197                                                      DAG);
13198   }
13199 
13200   assert(llvm::any_of(Mask, [](int M) { return M >= 0 && M < 8; }) &&
13201          "All single-input shuffles should be canonicalized to be V1-input "
13202          "shuffles.");
13203 
13204   // Try to use shift instructions.
13205   if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask,
13206                                                 Zeroable, Subtarget, DAG))
13207     return Shift;
13208 
13209   // See if we can use SSE4A Extraction / Insertion.
13210   if (Subtarget.hasSSE4A())
13211     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask,
13212                                                 Zeroable, DAG))
13213       return V;
13214 
13215   // There are special ways we can lower some single-element blends.
13216   if (NumV2Inputs == 1)
13217     if (SDValue V = lowerVectorShuffleAsElementInsertion(
13218             DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
13219       return V;
13220 
13221   // We have different paths for blend lowering, but they all must use the
13222   // *exact* same predicate.
13223   bool IsBlendSupported = Subtarget.hasSSE41();
13224   if (IsBlendSupported)
13225     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
13226                                                   Zeroable, Subtarget, DAG))
13227       return Blend;
13228 
13229   if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask,
13230                                                    Zeroable, DAG))
13231     return Masked;
13232 
13233   // Use dedicated unpack instructions for masks that match their pattern.
13234   if (SDValue V =
13235           lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
13236     return V;
13237 
13238   // Use dedicated pack instructions for masks that match their pattern.
13239   if (SDValue V = lowerVectorShuffleWithPACK(DL, MVT::v8i16, Mask, V1, V2, DAG,
13240                                              Subtarget))
13241     return V;
13242 
13243   // Try to use byte rotation instructions.
13244   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
13245           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
13246     return Rotate;
13247 
13248   if (SDValue BitBlend =
13249           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
13250     return BitBlend;
13251 
13252   // Try to lower by permuting the inputs into an unpack instruction.
13253   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
13254           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
13255     return Unpack;
13256 
13257   // If we can't directly blend but can use PSHUFB, that will be better as it
13258   // can both shuffle and set up the inefficient blend.
13259   if (!IsBlendSupported && Subtarget.hasSSSE3()) {
13260     bool V1InUse, V2InUse;
13261     return lowerVectorShuffleAsBlendOfPSHUFBs(DL, MVT::v8i16, V1, V2, Mask,
13262                                               Zeroable, DAG, V1InUse, V2InUse);
13263   }
13264 
13265   // We can always bit-blend if we have to so the fallback strategy is to
13266   // decompose into single-input permutes and blends.
13267   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
13268                                                     Mask, Subtarget, DAG);
13269 }
13270 
13271 /// Check whether a compaction lowering can be done by dropping even
13272 /// elements and compute how many times even elements must be dropped.
13273 ///
13274 /// This handles shuffles which take every Nth element where N is a power of
13275 /// two. Example shuffle masks:
13276 ///
13277 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
13278 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
13279 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
13280 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
13281 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
13282 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
13283 ///
13284 /// Any of these lanes can of course be undef.
13285 ///
13286 /// This routine only supports N <= 3.
13287 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
13288 /// for larger N.
13289 ///
13290 /// \returns N above, or the number of times even elements must be dropped if
13291 /// there is such a number. Otherwise returns zero.
canLowerByDroppingEvenElements(ArrayRef<int> Mask,bool IsSingleInput)13292 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask,
13293                                           bool IsSingleInput) {
13294   // The modulus for the shuffle vector entries is based on whether this is
13295   // a single input or not.
13296   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
13297   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
13298          "We should only be called with masks with a power-of-2 size!");
13299 
13300   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
13301 
13302   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
13303   // and 2^3 simultaneously. This is because we may have ambiguity with
13304   // partially undef inputs.
13305   bool ViableForN[3] = {true, true, true};
13306 
13307   for (int i = 0, e = Mask.size(); i < e; ++i) {
13308     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
13309     // want.
13310     if (Mask[i] < 0)
13311       continue;
13312 
13313     bool IsAnyViable = false;
13314     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
13315       if (ViableForN[j]) {
13316         uint64_t N = j + 1;
13317 
13318         // The shuffle mask must be equal to (i * 2^N) % M.
13319         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
13320           IsAnyViable = true;
13321         else
13322           ViableForN[j] = false;
13323       }
13324     // Early exit if we exhaust the possible powers of two.
13325     if (!IsAnyViable)
13326       break;
13327   }
13328 
13329   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
13330     if (ViableForN[j])
13331       return j + 1;
13332 
13333   // Return 0 as there is no viable power of two.
13334   return 0;
13335 }
13336 
lowerVectorShuffleWithPERMV(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,SelectionDAG & DAG)13337 static SDValue lowerVectorShuffleWithPERMV(const SDLoc &DL, MVT VT,
13338                                            ArrayRef<int> Mask, SDValue V1,
13339                                            SDValue V2, SelectionDAG &DAG) {
13340   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
13341   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
13342 
13343   SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
13344   if (V2.isUndef())
13345     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
13346 
13347   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
13348 }
13349 
13350 /// Generic lowering of v16i8 shuffles.
13351 ///
13352 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
13353 /// detect any complexity reducing interleaving. If that doesn't help, it uses
13354 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
13355 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
13356 /// back together.
lowerV16I8VectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)13357 static SDValue lowerV16I8VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
13358                                        const APInt &Zeroable,
13359                                        SDValue V1, SDValue V2,
13360                                        const X86Subtarget &Subtarget,
13361                                        SelectionDAG &DAG) {
13362   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
13363   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
13364   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
13365 
13366   // Try to use shift instructions.
13367   if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask,
13368                                                 Zeroable, Subtarget, DAG))
13369     return Shift;
13370 
13371   // Try to use byte rotation instructions.
13372   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
13373           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
13374     return Rotate;
13375 
13376   // Use dedicated pack instructions for masks that match their pattern.
13377   if (SDValue V = lowerVectorShuffleWithPACK(DL, MVT::v16i8, Mask, V1, V2, DAG,
13378                                              Subtarget))
13379     return V;
13380 
13381   // Try to use a zext lowering.
13382   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
13383           DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
13384     return ZExt;
13385 
13386   // See if we can use SSE4A Extraction / Insertion.
13387   if (Subtarget.hasSSE4A())
13388     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask,
13389                                                 Zeroable, DAG))
13390       return V;
13391 
13392   int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
13393 
13394   // For single-input shuffles, there are some nicer lowering tricks we can use.
13395   if (NumV2Elements == 0) {
13396     // Check for being able to broadcast a single element.
13397     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(
13398             DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
13399       return Broadcast;
13400 
13401     if (SDValue V =
13402             lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
13403       return V;
13404 
13405     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
13406     // Notably, this handles splat and partial-splat shuffles more efficiently.
13407     // However, it only makes sense if the pre-duplication shuffle simplifies
13408     // things significantly. Currently, this means we need to be able to
13409     // express the pre-duplication shuffle as an i16 shuffle.
13410     //
13411     // FIXME: We should check for other patterns which can be widened into an
13412     // i16 shuffle as well.
13413     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
13414       for (int i = 0; i < 16; i += 2)
13415         if (Mask[i] >= 0 && Mask[i + 1] >= 0 && Mask[i] != Mask[i + 1])
13416           return false;
13417 
13418       return true;
13419     };
13420     auto tryToWidenViaDuplication = [&]() -> SDValue {
13421       if (!canWidenViaDuplication(Mask))
13422         return SDValue();
13423       SmallVector<int, 4> LoInputs;
13424       copy_if(Mask, std::back_inserter(LoInputs),
13425               [](int M) { return M >= 0 && M < 8; });
13426       array_pod_sort(LoInputs.begin(), LoInputs.end());
13427       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
13428                      LoInputs.end());
13429       SmallVector<int, 4> HiInputs;
13430       copy_if(Mask, std::back_inserter(HiInputs), [](int M) { return M >= 8; });
13431       array_pod_sort(HiInputs.begin(), HiInputs.end());
13432       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
13433                      HiInputs.end());
13434 
13435       bool TargetLo = LoInputs.size() >= HiInputs.size();
13436       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
13437       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
13438 
13439       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
13440       SmallDenseMap<int, int, 8> LaneMap;
13441       for (int I : InPlaceInputs) {
13442         PreDupI16Shuffle[I/2] = I/2;
13443         LaneMap[I] = I;
13444       }
13445       int j = TargetLo ? 0 : 4, je = j + 4;
13446       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
13447         // Check if j is already a shuffle of this input. This happens when
13448         // there are two adjacent bytes after we move the low one.
13449         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
13450           // If we haven't yet mapped the input, search for a slot into which
13451           // we can map it.
13452           while (j < je && PreDupI16Shuffle[j] >= 0)
13453             ++j;
13454 
13455           if (j == je)
13456             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
13457             return SDValue();
13458 
13459           // Map this input with the i16 shuffle.
13460           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
13461         }
13462 
13463         // Update the lane map based on the mapping we ended up with.
13464         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
13465       }
13466       V1 = DAG.getBitcast(
13467           MVT::v16i8,
13468           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
13469                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
13470 
13471       // Unpack the bytes to form the i16s that will be shuffled into place.
13472       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
13473                        MVT::v16i8, V1, V1);
13474 
13475       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
13476       for (int i = 0; i < 16; ++i)
13477         if (Mask[i] >= 0) {
13478           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
13479           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
13480           if (PostDupI16Shuffle[i / 2] < 0)
13481             PostDupI16Shuffle[i / 2] = MappedMask;
13482           else
13483             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
13484                    "Conflicting entries in the original shuffle!");
13485         }
13486       return DAG.getBitcast(
13487           MVT::v16i8,
13488           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
13489                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
13490     };
13491     if (SDValue V = tryToWidenViaDuplication())
13492       return V;
13493   }
13494 
13495   if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask,
13496                                                    Zeroable, DAG))
13497     return Masked;
13498 
13499   // Use dedicated unpack instructions for masks that match their pattern.
13500   if (SDValue V =
13501           lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
13502     return V;
13503 
13504   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
13505   // with PSHUFB. It is important to do this before we attempt to generate any
13506   // blends but after all of the single-input lowerings. If the single input
13507   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
13508   // want to preserve that and we can DAG combine any longer sequences into
13509   // a PSHUFB in the end. But once we start blending from multiple inputs,
13510   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
13511   // and there are *very* few patterns that would actually be faster than the
13512   // PSHUFB approach because of its ability to zero lanes.
13513   //
13514   // FIXME: The only exceptions to the above are blends which are exact
13515   // interleavings with direct instructions supporting them. We currently don't
13516   // handle those well here.
13517   if (Subtarget.hasSSSE3()) {
13518     bool V1InUse = false;
13519     bool V2InUse = false;
13520 
13521     SDValue PSHUFB = lowerVectorShuffleAsBlendOfPSHUFBs(
13522         DL, MVT::v16i8, V1, V2, Mask, Zeroable, DAG, V1InUse, V2InUse);
13523 
13524     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
13525     // do so. This avoids using them to handle blends-with-zero which is
13526     // important as a single pshufb is significantly faster for that.
13527     if (V1InUse && V2InUse) {
13528       if (Subtarget.hasSSE41())
13529         if (SDValue Blend = lowerVectorShuffleAsBlend(
13530                 DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
13531           return Blend;
13532 
13533       // We can use an unpack to do the blending rather than an or in some
13534       // cases. Even though the or may be (very minorly) more efficient, we
13535       // preference this lowering because there are common cases where part of
13536       // the complexity of the shuffles goes away when we do the final blend as
13537       // an unpack.
13538       // FIXME: It might be worth trying to detect if the unpack-feeding
13539       // shuffles will both be pshufb, in which case we shouldn't bother with
13540       // this.
13541       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
13542               DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
13543         return Unpack;
13544 
13545       // If we have VBMI we can use one VPERM instead of multiple PSHUFBs.
13546       if (Subtarget.hasVBMI() && Subtarget.hasVLX())
13547         return lowerVectorShuffleWithPERMV(DL, MVT::v16i8, Mask, V1, V2, DAG);
13548 
13549       // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
13550       // PALIGNR will be cheaper than the second PSHUFB+OR.
13551       if (SDValue V = lowerVectorShuffleAsByteRotateAndPermute(
13552               DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
13553         return V;
13554     }
13555 
13556     return PSHUFB;
13557   }
13558 
13559   // There are special ways we can lower some single-element blends.
13560   if (NumV2Elements == 1)
13561     if (SDValue V = lowerVectorShuffleAsElementInsertion(
13562             DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
13563       return V;
13564 
13565   if (SDValue BitBlend =
13566           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
13567     return BitBlend;
13568 
13569   // Check whether a compaction lowering can be done. This handles shuffles
13570   // which take every Nth element for some even N. See the helper function for
13571   // details.
13572   //
13573   // We special case these as they can be particularly efficiently handled with
13574   // the PACKUSB instruction on x86 and they show up in common patterns of
13575   // rearranging bytes to truncate wide elements.
13576   bool IsSingleInput = V2.isUndef();
13577   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask, IsSingleInput)) {
13578     // NumEvenDrops is the power of two stride of the elements. Another way of
13579     // thinking about it is that we need to drop the even elements this many
13580     // times to get the original input.
13581 
13582     // First we need to zero all the dropped bytes.
13583     assert(NumEvenDrops <= 3 &&
13584            "No support for dropping even elements more than 3 times.");
13585     // We use the mask type to pick which bytes are preserved based on how many
13586     // elements are dropped.
13587     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
13588     SDValue ByteClearMask = DAG.getBitcast(
13589         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
13590     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
13591     if (!IsSingleInput)
13592       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
13593 
13594     // Now pack things back together.
13595     V1 = DAG.getBitcast(MVT::v8i16, V1);
13596     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
13597     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
13598     for (int i = 1; i < NumEvenDrops; ++i) {
13599       Result = DAG.getBitcast(MVT::v8i16, Result);
13600       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
13601     }
13602 
13603     return Result;
13604   }
13605 
13606   // Handle multi-input cases by blending single-input shuffles.
13607   if (NumV2Elements > 0)
13608     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
13609                                                       Mask, Subtarget, DAG);
13610 
13611   // The fallback path for single-input shuffles widens this into two v8i16
13612   // vectors with unpacks, shuffles those, and then pulls them back together
13613   // with a pack.
13614   SDValue V = V1;
13615 
13616   std::array<int, 8> LoBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
13617   std::array<int, 8> HiBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
13618   for (int i = 0; i < 16; ++i)
13619     if (Mask[i] >= 0)
13620       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
13621 
13622   SDValue VLoHalf, VHiHalf;
13623   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
13624   // them out and avoid using UNPCK{L,H} to extract the elements of V as
13625   // i16s.
13626   if (none_of(LoBlendMask, [](int M) { return M >= 0 && M % 2 == 1; }) &&
13627       none_of(HiBlendMask, [](int M) { return M >= 0 && M % 2 == 1; })) {
13628     // Use a mask to drop the high bytes.
13629     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
13630     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
13631                           DAG.getConstant(0x00FF, DL, MVT::v8i16));
13632 
13633     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
13634     VHiHalf = DAG.getUNDEF(MVT::v8i16);
13635 
13636     // Squash the masks to point directly into VLoHalf.
13637     for (int &M : LoBlendMask)
13638       if (M >= 0)
13639         M /= 2;
13640     for (int &M : HiBlendMask)
13641       if (M >= 0)
13642         M /= 2;
13643   } else {
13644     // Otherwise just unpack the low half of V into VLoHalf and the high half into
13645     // VHiHalf so that we can blend them as i16s.
13646     SDValue Zero = getZeroVector(MVT::v16i8, Subtarget, DAG, DL);
13647 
13648     VLoHalf = DAG.getBitcast(
13649         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
13650     VHiHalf = DAG.getBitcast(
13651         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
13652   }
13653 
13654   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
13655   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
13656 
13657   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
13658 }
13659 
13660 /// Dispatching routine to lower various 128-bit x86 vector shuffles.
13661 ///
13662 /// This routine breaks down the specific type of 128-bit shuffle and
13663 /// dispatches to the lowering routines accordingly.
lower128BitVectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,MVT VT,SDValue V1,SDValue V2,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)13664 static SDValue lower128BitVectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
13665                                         MVT VT, SDValue V1, SDValue V2,
13666                                         const APInt &Zeroable,
13667                                         const X86Subtarget &Subtarget,
13668                                         SelectionDAG &DAG) {
13669   switch (VT.SimpleTy) {
13670   case MVT::v2i64:
13671     return lowerV2I64VectorShuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
13672   case MVT::v2f64:
13673     return lowerV2F64VectorShuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
13674   case MVT::v4i32:
13675     return lowerV4I32VectorShuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
13676   case MVT::v4f32:
13677     return lowerV4F32VectorShuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
13678   case MVT::v8i16:
13679     return lowerV8I16VectorShuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
13680   case MVT::v16i8:
13681     return lowerV16I8VectorShuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
13682 
13683   default:
13684     llvm_unreachable("Unimplemented!");
13685   }
13686 }
13687 
13688 /// Generic routine to split vector shuffle into half-sized shuffles.
13689 ///
13690 /// This routine just extracts two subvectors, shuffles them independently, and
13691 /// then concatenates them back together. This should work effectively with all
13692 /// AVX vector shuffle types.
splitAndLowerVectorShuffle(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG)13693 static SDValue splitAndLowerVectorShuffle(const SDLoc &DL, MVT VT, SDValue V1,
13694                                           SDValue V2, ArrayRef<int> Mask,
13695                                           SelectionDAG &DAG) {
13696   assert(VT.getSizeInBits() >= 256 &&
13697          "Only for 256-bit or wider vector shuffles!");
13698   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
13699   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
13700 
13701   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
13702   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
13703 
13704   int NumElements = VT.getVectorNumElements();
13705   int SplitNumElements = NumElements / 2;
13706   MVT ScalarVT = VT.getVectorElementType();
13707   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
13708 
13709   // Rather than splitting build-vectors, just build two narrower build
13710   // vectors. This helps shuffling with splats and zeros.
13711   auto SplitVector = [&](SDValue V) {
13712     V = peekThroughBitcasts(V);
13713 
13714     MVT OrigVT = V.getSimpleValueType();
13715     int OrigNumElements = OrigVT.getVectorNumElements();
13716     int OrigSplitNumElements = OrigNumElements / 2;
13717     MVT OrigScalarVT = OrigVT.getVectorElementType();
13718     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
13719 
13720     SDValue LoV, HiV;
13721 
13722     auto *BV = dyn_cast<BuildVectorSDNode>(V);
13723     if (!BV) {
13724       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
13725                         DAG.getIntPtrConstant(0, DL));
13726       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
13727                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
13728     } else {
13729 
13730       SmallVector<SDValue, 16> LoOps, HiOps;
13731       for (int i = 0; i < OrigSplitNumElements; ++i) {
13732         LoOps.push_back(BV->getOperand(i));
13733         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
13734       }
13735       LoV = DAG.getBuildVector(OrigSplitVT, DL, LoOps);
13736       HiV = DAG.getBuildVector(OrigSplitVT, DL, HiOps);
13737     }
13738     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
13739                           DAG.getBitcast(SplitVT, HiV));
13740   };
13741 
13742   SDValue LoV1, HiV1, LoV2, HiV2;
13743   std::tie(LoV1, HiV1) = SplitVector(V1);
13744   std::tie(LoV2, HiV2) = SplitVector(V2);
13745 
13746   // Now create two 4-way blends of these half-width vectors.
13747   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
13748     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
13749     SmallVector<int, 32> V1BlendMask((unsigned)SplitNumElements, -1);
13750     SmallVector<int, 32> V2BlendMask((unsigned)SplitNumElements, -1);
13751     SmallVector<int, 32> BlendMask((unsigned)SplitNumElements, -1);
13752     for (int i = 0; i < SplitNumElements; ++i) {
13753       int M = HalfMask[i];
13754       if (M >= NumElements) {
13755         if (M >= NumElements + SplitNumElements)
13756           UseHiV2 = true;
13757         else
13758           UseLoV2 = true;
13759         V2BlendMask[i] = M - NumElements;
13760         BlendMask[i] = SplitNumElements + i;
13761       } else if (M >= 0) {
13762         if (M >= SplitNumElements)
13763           UseHiV1 = true;
13764         else
13765           UseLoV1 = true;
13766         V1BlendMask[i] = M;
13767         BlendMask[i] = i;
13768       }
13769     }
13770 
13771     // Because the lowering happens after all combining takes place, we need to
13772     // manually combine these blend masks as much as possible so that we create
13773     // a minimal number of high-level vector shuffle nodes.
13774 
13775     // First try just blending the halves of V1 or V2.
13776     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
13777       return DAG.getUNDEF(SplitVT);
13778     if (!UseLoV2 && !UseHiV2)
13779       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
13780     if (!UseLoV1 && !UseHiV1)
13781       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
13782 
13783     SDValue V1Blend, V2Blend;
13784     if (UseLoV1 && UseHiV1) {
13785       V1Blend =
13786         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
13787     } else {
13788       // We only use half of V1 so map the usage down into the final blend mask.
13789       V1Blend = UseLoV1 ? LoV1 : HiV1;
13790       for (int i = 0; i < SplitNumElements; ++i)
13791         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
13792           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
13793     }
13794     if (UseLoV2 && UseHiV2) {
13795       V2Blend =
13796         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
13797     } else {
13798       // We only use half of V2 so map the usage down into the final blend mask.
13799       V2Blend = UseLoV2 ? LoV2 : HiV2;
13800       for (int i = 0; i < SplitNumElements; ++i)
13801         if (BlendMask[i] >= SplitNumElements)
13802           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
13803     }
13804     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
13805   };
13806   SDValue Lo = HalfBlend(LoMask);
13807   SDValue Hi = HalfBlend(HiMask);
13808   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
13809 }
13810 
13811 /// Either split a vector in halves or decompose the shuffles and the
13812 /// blend.
13813 ///
13814 /// This is provided as a good fallback for many lowerings of non-single-input
13815 /// shuffles with more than one 128-bit lane. In those cases, we want to select
13816 /// between splitting the shuffle into 128-bit components and stitching those
13817 /// back together vs. extracting the single-input shuffles and blending those
13818 /// results.
lowerVectorShuffleAsSplitOrBlend(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)13819 static SDValue lowerVectorShuffleAsSplitOrBlend(const SDLoc &DL, MVT VT,
13820                                                 SDValue V1, SDValue V2,
13821                                                 ArrayRef<int> Mask,
13822                                                 const X86Subtarget &Subtarget,
13823                                                 SelectionDAG &DAG) {
13824   assert(!V2.isUndef() && "This routine must not be used to lower single-input "
13825          "shuffles as it could then recurse on itself.");
13826   int Size = Mask.size();
13827 
13828   // If this can be modeled as a broadcast of two elements followed by a blend,
13829   // prefer that lowering. This is especially important because broadcasts can
13830   // often fold with memory operands.
13831   auto DoBothBroadcast = [&] {
13832     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
13833     for (int M : Mask)
13834       if (M >= Size) {
13835         if (V2BroadcastIdx < 0)
13836           V2BroadcastIdx = M - Size;
13837         else if (M - Size != V2BroadcastIdx)
13838           return false;
13839       } else if (M >= 0) {
13840         if (V1BroadcastIdx < 0)
13841           V1BroadcastIdx = M;
13842         else if (M != V1BroadcastIdx)
13843           return false;
13844       }
13845     return true;
13846   };
13847   if (DoBothBroadcast())
13848     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
13849                                                       Subtarget, DAG);
13850 
13851   // If the inputs all stem from a single 128-bit lane of each input, then we
13852   // split them rather than blending because the split will decompose to
13853   // unusually few instructions.
13854   int LaneCount = VT.getSizeInBits() / 128;
13855   int LaneSize = Size / LaneCount;
13856   SmallBitVector LaneInputs[2];
13857   LaneInputs[0].resize(LaneCount, false);
13858   LaneInputs[1].resize(LaneCount, false);
13859   for (int i = 0; i < Size; ++i)
13860     if (Mask[i] >= 0)
13861       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
13862   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
13863     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
13864 
13865   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
13866   // that the decomposed single-input shuffles don't end up here.
13867   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
13868                                                     Subtarget, DAG);
13869 }
13870 
13871 /// Lower a vector shuffle crossing multiple 128-bit lanes as
13872 /// a lane permutation followed by a per-lane permutation.
13873 ///
13874 /// This is mainly for cases where we can have non-repeating permutes
13875 /// in each lane.
13876 ///
13877 /// TODO: This is very similar to lowerVectorShuffleByMerging128BitLanes,
13878 /// we should investigate merging them.
lowerVectorShuffleAsLanePermuteAndPermute(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG,const X86Subtarget & Subtarget)13879 static SDValue lowerVectorShuffleAsLanePermuteAndPermute(
13880     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13881     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
13882   int NumElts = VT.getVectorNumElements();
13883   int NumLanes = VT.getSizeInBits() / 128;
13884   int NumEltsPerLane = NumElts / NumLanes;
13885 
13886   SmallVector<int, 4> SrcLaneMask(NumLanes, SM_SentinelUndef);
13887   SmallVector<int, 16> PermMask(NumElts, SM_SentinelUndef);
13888 
13889   for (int i = 0; i != NumElts; ++i) {
13890     int M = Mask[i];
13891     if (M < 0)
13892       continue;
13893 
13894     // Ensure that each lane comes from a single source lane.
13895     int SrcLane = M / NumEltsPerLane;
13896     int DstLane = i / NumEltsPerLane;
13897     if (!isUndefOrEqual(SrcLaneMask[DstLane], SrcLane))
13898       return SDValue();
13899     SrcLaneMask[DstLane] = SrcLane;
13900 
13901     PermMask[i] = (DstLane * NumEltsPerLane) + (M % NumEltsPerLane);
13902   }
13903 
13904   // Make sure we set all elements of the lane mask, to avoid undef propagation.
13905   SmallVector<int, 16> LaneMask(NumElts, SM_SentinelUndef);
13906   for (int DstLane = 0; DstLane != NumLanes; ++DstLane) {
13907     int SrcLane = SrcLaneMask[DstLane];
13908     if (0 <= SrcLane)
13909       for (int j = 0; j != NumEltsPerLane; ++j) {
13910         LaneMask[(DstLane * NumEltsPerLane) + j] =
13911             (SrcLane * NumEltsPerLane) + j;
13912       }
13913   }
13914 
13915   // If we're only shuffling a single lowest lane and the rest are identity
13916   // then don't bother.
13917   // TODO - isShuffleMaskInputInPlace could be extended to something like this.
13918   int NumIdentityLanes = 0;
13919   bool OnlyShuffleLowestLane = true;
13920   for (int i = 0; i != NumLanes; ++i) {
13921     if (isSequentialOrUndefInRange(PermMask, i * NumEltsPerLane, NumEltsPerLane,
13922                                    i * NumEltsPerLane))
13923       NumIdentityLanes++;
13924     else if (SrcLaneMask[i] != 0 && SrcLaneMask[i] != NumLanes)
13925       OnlyShuffleLowestLane = false;
13926   }
13927   if (OnlyShuffleLowestLane && NumIdentityLanes == (NumLanes - 1))
13928     return SDValue();
13929 
13930   SDValue LanePermute = DAG.getVectorShuffle(VT, DL, V1, V2, LaneMask);
13931   return DAG.getVectorShuffle(VT, DL, LanePermute, DAG.getUNDEF(VT), PermMask);
13932 }
13933 
13934 /// Lower a vector shuffle crossing multiple 128-bit lanes as
13935 /// a permutation and blend of those lanes.
13936 ///
13937 /// This essentially blends the out-of-lane inputs to each lane into the lane
13938 /// from a permuted copy of the vector. This lowering strategy results in four
13939 /// instructions in the worst case for a single-input cross lane shuffle which
13940 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
13941 /// of. Special cases for each particular shuffle pattern should be handled
13942 /// prior to trying this lowering.
lowerVectorShuffleAsLanePermuteAndBlend(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG,const X86Subtarget & Subtarget)13943 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(const SDLoc &DL, MVT VT,
13944                                                        SDValue V1, SDValue V2,
13945                                                        ArrayRef<int> Mask,
13946                                                        SelectionDAG &DAG,
13947                                                        const X86Subtarget &Subtarget) {
13948   // FIXME: This should probably be generalized for 512-bit vectors as well.
13949   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
13950   int Size = Mask.size();
13951   int LaneSize = Size / 2;
13952 
13953   // If there are only inputs from one 128-bit lane, splitting will in fact be
13954   // less expensive. The flags track whether the given lane contains an element
13955   // that crosses to another lane.
13956   if (!Subtarget.hasAVX2()) {
13957     bool LaneCrossing[2] = {false, false};
13958     for (int i = 0; i < Size; ++i)
13959       if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
13960         LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
13961     if (!LaneCrossing[0] || !LaneCrossing[1])
13962       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
13963   } else {
13964     bool LaneUsed[2] = {false, false};
13965     for (int i = 0; i < Size; ++i)
13966       if (Mask[i] >= 0)
13967         LaneUsed[(Mask[i] / LaneSize)] = true;
13968     if (!LaneUsed[0] || !LaneUsed[1])
13969       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
13970   }
13971 
13972   assert(V2.isUndef() &&
13973          "This last part of this routine only works on single input shuffles");
13974 
13975   SmallVector<int, 32> FlippedBlendMask(Size);
13976   for (int i = 0; i < Size; ++i)
13977     FlippedBlendMask[i] =
13978         Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
13979                                 ? Mask[i]
13980                                 : Mask[i] % LaneSize +
13981                                       (i / LaneSize) * LaneSize + Size);
13982 
13983   // Flip the vector, and blend the results which should now be in-lane.
13984   MVT PVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
13985   SDValue Flipped = DAG.getBitcast(PVT, V1);
13986   Flipped = DAG.getVectorShuffle(PVT, DL, Flipped, DAG.getUNDEF(PVT),
13987                                  { 2, 3, 0, 1 });
13988   Flipped = DAG.getBitcast(VT, Flipped);
13989   return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
13990 }
13991 
13992 /// Handle lowering 2-lane 128-bit shuffles.
lowerV2X128VectorShuffle(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)13993 static SDValue lowerV2X128VectorShuffle(const SDLoc &DL, MVT VT, SDValue V1,
13994                                         SDValue V2, ArrayRef<int> Mask,
13995                                         const APInt &Zeroable,
13996                                         const X86Subtarget &Subtarget,
13997                                         SelectionDAG &DAG) {
13998   // With AVX2, use VPERMQ/VPERMPD for unary shuffles to allow memory folding.
13999   if (Subtarget.hasAVX2() && V2.isUndef())
14000     return SDValue();
14001 
14002   SmallVector<int, 4> WidenedMask;
14003   if (!canWidenShuffleElements(Mask, Zeroable, WidenedMask))
14004     return SDValue();
14005 
14006   bool IsLowZero = (Zeroable & 0x3) == 0x3;
14007   bool IsHighZero = (Zeroable & 0xc) == 0xc;
14008 
14009   // Try to use an insert into a zero vector.
14010   if (WidenedMask[0] == 0 && IsHighZero) {
14011     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
14012     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
14013                               DAG.getIntPtrConstant(0, DL));
14014     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
14015                        getZeroVector(VT, Subtarget, DAG, DL), LoV,
14016                        DAG.getIntPtrConstant(0, DL));
14017   }
14018 
14019   // TODO: If minimizing size and one of the inputs is a zero vector and the
14020   // the zero vector has only one use, we could use a VPERM2X128 to save the
14021   // instruction bytes needed to explicitly generate the zero vector.
14022 
14023   // Blends are faster and handle all the non-lane-crossing cases.
14024   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
14025                                                 Zeroable, Subtarget, DAG))
14026     return Blend;
14027 
14028   // If either input operand is a zero vector, use VPERM2X128 because its mask
14029   // allows us to replace the zero input with an implicit zero.
14030   if (!IsLowZero && !IsHighZero) {
14031     // Check for patterns which can be matched with a single insert of a 128-bit
14032     // subvector.
14033     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
14034     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
14035 
14036       // With AVX1, use vperm2f128 (below) to allow load folding. Otherwise,
14037       // this will likely become vinsertf128 which can't fold a 256-bit memop.
14038       if (!isa<LoadSDNode>(peekThroughBitcasts(V1))) {
14039         MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
14040         SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
14041                                      OnlyUsesV1 ? V1 : V2,
14042                                      DAG.getIntPtrConstant(0, DL));
14043         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
14044                            DAG.getIntPtrConstant(2, DL));
14045       }
14046     }
14047 
14048     // Try to use SHUF128 if possible.
14049     if (Subtarget.hasVLX()) {
14050       if (WidenedMask[0] < 2 && WidenedMask[1] >= 2) {
14051         unsigned PermMask = ((WidenedMask[0] % 2) << 0) |
14052                             ((WidenedMask[1] % 2) << 1);
14053       return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
14054                          DAG.getConstant(PermMask, DL, MVT::i8));
14055       }
14056     }
14057   }
14058 
14059   // Otherwise form a 128-bit permutation. After accounting for undefs,
14060   // convert the 64-bit shuffle mask selection values into 128-bit
14061   // selection bits by dividing the indexes by 2 and shifting into positions
14062   // defined by a vperm2*128 instruction's immediate control byte.
14063 
14064   // The immediate permute control byte looks like this:
14065   //    [1:0] - select 128 bits from sources for low half of destination
14066   //    [2]   - ignore
14067   //    [3]   - zero low half of destination
14068   //    [5:4] - select 128 bits from sources for high half of destination
14069   //    [6]   - ignore
14070   //    [7]   - zero high half of destination
14071 
14072   assert((WidenedMask[0] >= 0 || IsLowZero) &&
14073          (WidenedMask[1] >= 0 || IsHighZero) && "Undef half?");
14074 
14075   unsigned PermMask = 0;
14076   PermMask |= IsLowZero  ? 0x08 : (WidenedMask[0] << 0);
14077   PermMask |= IsHighZero ? 0x80 : (WidenedMask[1] << 4);
14078 
14079   // Check the immediate mask and replace unused sources with undef.
14080   if ((PermMask & 0x0a) != 0x00 && (PermMask & 0xa0) != 0x00)
14081     V1 = DAG.getUNDEF(VT);
14082   if ((PermMask & 0x0a) != 0x02 && (PermMask & 0xa0) != 0x20)
14083     V2 = DAG.getUNDEF(VT);
14084 
14085   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
14086                      DAG.getConstant(PermMask, DL, MVT::i8));
14087 }
14088 
14089 /// Lower a vector shuffle by first fixing the 128-bit lanes and then
14090 /// shuffling each lane.
14091 ///
14092 /// This attempts to create a repeated lane shuffle where each lane uses one
14093 /// or two of the lanes of the inputs. The lanes of the input vectors are
14094 /// shuffled in one or two independent shuffles to get the lanes into the
14095 /// position needed by the final shuffle.
14096 ///
14097 /// FIXME: This should be generalized to 512-bit shuffles.
lowerVectorShuffleByMerging128BitLanes(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)14098 static SDValue lowerVectorShuffleByMerging128BitLanes(
14099     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14100     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
14101   assert(!V2.isUndef() && "This is only useful with multiple inputs.");
14102 
14103   if (is128BitLaneRepeatedShuffleMask(VT, Mask))
14104     return SDValue();
14105 
14106   int Size = Mask.size();
14107   int LaneSize = 128 / VT.getScalarSizeInBits();
14108   int NumLanes = Size / LaneSize;
14109   assert(NumLanes == 2 && "Only handles 256-bit shuffles.");
14110 
14111   SmallVector<int, 16> RepeatMask(LaneSize, -1);
14112   int LaneSrcs[2][2] = { { -1, -1 }, { -1 , -1 } };
14113 
14114   // First pass will try to fill in the RepeatMask from lanes that need two
14115   // sources.
14116   for (int Lane = 0; Lane != NumLanes; ++Lane) {
14117     int Srcs[2] = { -1, -1 };
14118     SmallVector<int, 16> InLaneMask(LaneSize, -1);
14119     for (int i = 0; i != LaneSize; ++i) {
14120       int M = Mask[(Lane * LaneSize) + i];
14121       if (M < 0)
14122         continue;
14123       // Determine which of the 4 possible input lanes (2 from each source)
14124       // this element comes from. Assign that as one of the sources for this
14125       // lane. We can assign up to 2 sources for this lane. If we run out
14126       // sources we can't do anything.
14127       int LaneSrc = M / LaneSize;
14128       int Src;
14129       if (Srcs[0] < 0 || Srcs[0] == LaneSrc)
14130         Src = 0;
14131       else if (Srcs[1] < 0 || Srcs[1] == LaneSrc)
14132         Src = 1;
14133       else
14134         return SDValue();
14135 
14136       Srcs[Src] = LaneSrc;
14137       InLaneMask[i] = (M % LaneSize) + Src * Size;
14138     }
14139 
14140     // If this lane has two sources, see if it fits with the repeat mask so far.
14141     if (Srcs[1] < 0)
14142       continue;
14143 
14144     LaneSrcs[Lane][0] = Srcs[0];
14145     LaneSrcs[Lane][1] = Srcs[1];
14146 
14147     auto MatchMasks = [](ArrayRef<int> M1, ArrayRef<int> M2) {
14148       assert(M1.size() == M2.size() && "Unexpected mask size");
14149       for (int i = 0, e = M1.size(); i != e; ++i)
14150         if (M1[i] >= 0 && M2[i] >= 0 && M1[i] != M2[i])
14151           return false;
14152       return true;
14153     };
14154 
14155     auto MergeMasks = [](ArrayRef<int> Mask, MutableArrayRef<int> MergedMask) {
14156       assert(Mask.size() == MergedMask.size() && "Unexpected mask size");
14157       for (int i = 0, e = MergedMask.size(); i != e; ++i) {
14158         int M = Mask[i];
14159         if (M < 0)
14160           continue;
14161         assert((MergedMask[i] < 0 || MergedMask[i] == M) &&
14162                "Unexpected mask element");
14163         MergedMask[i] = M;
14164       }
14165     };
14166 
14167     if (MatchMasks(InLaneMask, RepeatMask)) {
14168       // Merge this lane mask into the final repeat mask.
14169       MergeMasks(InLaneMask, RepeatMask);
14170       continue;
14171     }
14172 
14173     // Didn't find a match. Swap the operands and try again.
14174     std::swap(LaneSrcs[Lane][0], LaneSrcs[Lane][1]);
14175     ShuffleVectorSDNode::commuteMask(InLaneMask);
14176 
14177     if (MatchMasks(InLaneMask, RepeatMask)) {
14178       // Merge this lane mask into the final repeat mask.
14179       MergeMasks(InLaneMask, RepeatMask);
14180       continue;
14181     }
14182 
14183     // Couldn't find a match with the operands in either order.
14184     return SDValue();
14185   }
14186 
14187   // Now handle any lanes with only one source.
14188   for (int Lane = 0; Lane != NumLanes; ++Lane) {
14189     // If this lane has already been processed, skip it.
14190     if (LaneSrcs[Lane][0] >= 0)
14191       continue;
14192 
14193     for (int i = 0; i != LaneSize; ++i) {
14194       int M = Mask[(Lane * LaneSize) + i];
14195       if (M < 0)
14196         continue;
14197 
14198       // If RepeatMask isn't defined yet we can define it ourself.
14199       if (RepeatMask[i] < 0)
14200         RepeatMask[i] = M % LaneSize;
14201 
14202       if (RepeatMask[i] < Size) {
14203         if (RepeatMask[i] != M % LaneSize)
14204           return SDValue();
14205         LaneSrcs[Lane][0] = M / LaneSize;
14206       } else {
14207         if (RepeatMask[i] != ((M % LaneSize) + Size))
14208           return SDValue();
14209         LaneSrcs[Lane][1] = M / LaneSize;
14210       }
14211     }
14212 
14213     if (LaneSrcs[Lane][0] < 0 && LaneSrcs[Lane][1] < 0)
14214       return SDValue();
14215   }
14216 
14217   SmallVector<int, 16> NewMask(Size, -1);
14218   for (int Lane = 0; Lane != NumLanes; ++Lane) {
14219     int Src = LaneSrcs[Lane][0];
14220     for (int i = 0; i != LaneSize; ++i) {
14221       int M = -1;
14222       if (Src >= 0)
14223         M = Src * LaneSize + i;
14224       NewMask[Lane * LaneSize + i] = M;
14225     }
14226   }
14227   SDValue NewV1 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
14228   // Ensure we didn't get back the shuffle we started with.
14229   // FIXME: This is a hack to make up for some splat handling code in
14230   // getVectorShuffle.
14231   if (isa<ShuffleVectorSDNode>(NewV1) &&
14232       cast<ShuffleVectorSDNode>(NewV1)->getMask() == Mask)
14233     return SDValue();
14234 
14235   for (int Lane = 0; Lane != NumLanes; ++Lane) {
14236     int Src = LaneSrcs[Lane][1];
14237     for (int i = 0; i != LaneSize; ++i) {
14238       int M = -1;
14239       if (Src >= 0)
14240         M = Src * LaneSize + i;
14241       NewMask[Lane * LaneSize + i] = M;
14242     }
14243   }
14244   SDValue NewV2 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
14245   // Ensure we didn't get back the shuffle we started with.
14246   // FIXME: This is a hack to make up for some splat handling code in
14247   // getVectorShuffle.
14248   if (isa<ShuffleVectorSDNode>(NewV2) &&
14249       cast<ShuffleVectorSDNode>(NewV2)->getMask() == Mask)
14250     return SDValue();
14251 
14252   for (int i = 0; i != Size; ++i) {
14253     NewMask[i] = RepeatMask[i % LaneSize];
14254     if (NewMask[i] < 0)
14255       continue;
14256 
14257     NewMask[i] += (i / LaneSize) * LaneSize;
14258   }
14259   return DAG.getVectorShuffle(VT, DL, NewV1, NewV2, NewMask);
14260 }
14261 
14262 /// Lower shuffles where an entire half of a 256 or 512-bit vector is UNDEF.
14263 /// This allows for fast cases such as subvector extraction/insertion
14264 /// or shuffling smaller vector types which can lower more efficiently.
lowerVectorShuffleWithUndefHalf(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)14265 static SDValue lowerVectorShuffleWithUndefHalf(const SDLoc &DL, MVT VT,
14266                                                SDValue V1, SDValue V2,
14267                                                ArrayRef<int> Mask,
14268                                                const X86Subtarget &Subtarget,
14269                                                SelectionDAG &DAG) {
14270   assert((VT.is256BitVector() || VT.is512BitVector()) &&
14271          "Expected 256-bit or 512-bit vector");
14272 
14273   unsigned NumElts = VT.getVectorNumElements();
14274   unsigned HalfNumElts = NumElts / 2;
14275   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(), HalfNumElts);
14276 
14277   bool UndefLower = isUndefInRange(Mask, 0, HalfNumElts);
14278   bool UndefUpper = isUndefInRange(Mask, HalfNumElts, HalfNumElts);
14279   if (!UndefLower && !UndefUpper)
14280     return SDValue();
14281 
14282   // Upper half is undef and lower half is whole upper subvector.
14283   // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14284   if (UndefUpper &&
14285       isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
14286     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
14287                              DAG.getIntPtrConstant(HalfNumElts, DL));
14288     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
14289                        DAG.getIntPtrConstant(0, DL));
14290   }
14291 
14292   // Lower half is undef and upper half is whole lower subvector.
14293   // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14294   if (UndefLower &&
14295       isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
14296     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
14297                              DAG.getIntPtrConstant(0, DL));
14298     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
14299                        DAG.getIntPtrConstant(HalfNumElts, DL));
14300   }
14301 
14302   // If the shuffle only uses two of the four halves of the input operands,
14303   // then extract them and perform the 'half' shuffle at half width.
14304   // e.g. vector_shuffle <X, X, X, X, u, u, u, u> or <X, X, u, u>
14305   int HalfIdx1 = -1, HalfIdx2 = -1;
14306   SmallVector<int, 8> HalfMask(HalfNumElts);
14307   unsigned Offset = UndefLower ? HalfNumElts : 0;
14308   for (unsigned i = 0; i != HalfNumElts; ++i) {
14309     int M = Mask[i + Offset];
14310     if (M < 0) {
14311       HalfMask[i] = M;
14312       continue;
14313     }
14314 
14315     // Determine which of the 4 half vectors this element is from.
14316     // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
14317     int HalfIdx = M / HalfNumElts;
14318 
14319     // Determine the element index into its half vector source.
14320     int HalfElt = M % HalfNumElts;
14321 
14322     // We can shuffle with up to 2 half vectors, set the new 'half'
14323     // shuffle mask accordingly.
14324     if (HalfIdx1 < 0 || HalfIdx1 == HalfIdx) {
14325       HalfMask[i] = HalfElt;
14326       HalfIdx1 = HalfIdx;
14327       continue;
14328     }
14329     if (HalfIdx2 < 0 || HalfIdx2 == HalfIdx) {
14330       HalfMask[i] = HalfElt + HalfNumElts;
14331       HalfIdx2 = HalfIdx;
14332       continue;
14333     }
14334 
14335     // Too many half vectors referenced.
14336     return SDValue();
14337   }
14338   assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
14339 
14340   // Only shuffle the halves of the inputs when useful.
14341   int NumLowerHalves =
14342       (HalfIdx1 == 0 || HalfIdx1 == 2) + (HalfIdx2 == 0 || HalfIdx2 == 2);
14343   int NumUpperHalves =
14344       (HalfIdx1 == 1 || HalfIdx1 == 3) + (HalfIdx2 == 1 || HalfIdx2 == 3);
14345 
14346   // uuuuXXXX - don't extract uppers just to insert again.
14347   if (UndefLower && NumUpperHalves != 0)
14348     return SDValue();
14349 
14350   // XXXXuuuu - don't extract both uppers, instead shuffle and then extract.
14351   if (UndefUpper && NumUpperHalves == 2)
14352     return SDValue();
14353 
14354   // AVX2 - XXXXuuuu - always extract lowers.
14355   if (Subtarget.hasAVX2() && !(UndefUpper && NumUpperHalves == 0)) {
14356     // AVX2 supports efficient immediate 64-bit element cross-lane shuffles.
14357     if (VT == MVT::v4f64 || VT == MVT::v4i64)
14358       return SDValue();
14359     // AVX2 supports variable 32-bit element cross-lane shuffles.
14360     if (VT == MVT::v8f32 || VT == MVT::v8i32) {
14361       // XXXXuuuu - don't extract lowers and uppers.
14362       if (UndefUpper && NumLowerHalves != 0 && NumUpperHalves != 0)
14363         return SDValue();
14364     }
14365   }
14366 
14367   // AVX512 - XXXXuuuu - always extract lowers.
14368   if (VT.is512BitVector() && !(UndefUpper && NumUpperHalves == 0))
14369     return SDValue();
14370 
14371   auto GetHalfVector = [&](int HalfIdx) {
14372     if (HalfIdx < 0)
14373       return DAG.getUNDEF(HalfVT);
14374     SDValue V = (HalfIdx < 2 ? V1 : V2);
14375     HalfIdx = (HalfIdx % 2) * HalfNumElts;
14376     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
14377                        DAG.getIntPtrConstant(HalfIdx, DL));
14378   };
14379 
14380   SDValue Half1 = GetHalfVector(HalfIdx1);
14381   SDValue Half2 = GetHalfVector(HalfIdx2);
14382   SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
14383   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
14384                      DAG.getIntPtrConstant(Offset, DL));
14385 }
14386 
14387 /// Test whether the specified input (0 or 1) is in-place blended by the
14388 /// given mask.
14389 ///
14390 /// This returns true if the elements from a particular input are already in the
14391 /// slot required by the given mask and require no permutation.
isShuffleMaskInputInPlace(int Input,ArrayRef<int> Mask)14392 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
14393   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
14394   int Size = Mask.size();
14395   for (int i = 0; i < Size; ++i)
14396     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
14397       return false;
14398 
14399   return true;
14400 }
14401 
14402 /// Handle case where shuffle sources are coming from the same 128-bit lane and
14403 /// every lane can be represented as the same repeating mask - allowing us to
14404 /// shuffle the sources with the repeating shuffle and then permute the result
14405 /// to the destination lanes.
lowerShuffleAsRepeatedMaskAndLanePermute(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)14406 static SDValue lowerShuffleAsRepeatedMaskAndLanePermute(
14407     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14408     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
14409   int NumElts = VT.getVectorNumElements();
14410   int NumLanes = VT.getSizeInBits() / 128;
14411   int NumLaneElts = NumElts / NumLanes;
14412 
14413   // On AVX2 we may be able to just shuffle the lowest elements and then
14414   // broadcast the result.
14415   if (Subtarget.hasAVX2()) {
14416     for (unsigned BroadcastSize : {16, 32, 64}) {
14417       if (BroadcastSize <= VT.getScalarSizeInBits())
14418         continue;
14419       int NumBroadcastElts = BroadcastSize / VT.getScalarSizeInBits();
14420 
14421       // Attempt to match a repeating pattern every NumBroadcastElts,
14422       // accounting for UNDEFs but only references the lowest 128-bit
14423       // lane of the inputs.
14424       auto FindRepeatingBroadcastMask = [&](SmallVectorImpl<int> &RepeatMask) {
14425         for (int i = 0; i != NumElts; i += NumBroadcastElts)
14426           for (int j = 0; j != NumBroadcastElts; ++j) {
14427             int M = Mask[i + j];
14428             if (M < 0)
14429               continue;
14430             int &R = RepeatMask[j];
14431             if (0 != ((M % NumElts) / NumLaneElts))
14432               return false;
14433             if (0 <= R && R != M)
14434               return false;
14435             R = M;
14436           }
14437         return true;
14438       };
14439 
14440       SmallVector<int, 8> RepeatMask((unsigned)NumElts, -1);
14441       if (!FindRepeatingBroadcastMask(RepeatMask))
14442         continue;
14443 
14444       // Shuffle the (lowest) repeated elements in place for broadcast.
14445       SDValue RepeatShuf = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatMask);
14446 
14447       // Shuffle the actual broadcast.
14448       SmallVector<int, 8> BroadcastMask((unsigned)NumElts, -1);
14449       for (int i = 0; i != NumElts; i += NumBroadcastElts)
14450         for (int j = 0; j != NumBroadcastElts; ++j)
14451           BroadcastMask[i + j] = j;
14452       return DAG.getVectorShuffle(VT, DL, RepeatShuf, DAG.getUNDEF(VT),
14453                                   BroadcastMask);
14454     }
14455   }
14456 
14457   // Bail if the shuffle mask doesn't cross 128-bit lanes.
14458   if (!is128BitLaneCrossingShuffleMask(VT, Mask))
14459     return SDValue();
14460 
14461   // Bail if we already have a repeated lane shuffle mask.
14462   SmallVector<int, 8> RepeatedShuffleMask;
14463   if (is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedShuffleMask))
14464     return SDValue();
14465 
14466   // On AVX2 targets we can permute 256-bit vectors as 64-bit sub-lanes
14467   // (with PERMQ/PERMPD), otherwise we can only permute whole 128-bit lanes.
14468   int SubLaneScale = Subtarget.hasAVX2() && VT.is256BitVector() ? 2 : 1;
14469   int NumSubLanes = NumLanes * SubLaneScale;
14470   int NumSubLaneElts = NumLaneElts / SubLaneScale;
14471 
14472   // Check that all the sources are coming from the same lane and see if we can
14473   // form a repeating shuffle mask (local to each sub-lane). At the same time,
14474   // determine the source sub-lane for each destination sub-lane.
14475   int TopSrcSubLane = -1;
14476   SmallVector<int, 8> Dst2SrcSubLanes((unsigned)NumSubLanes, -1);
14477   SmallVector<int, 8> RepeatedSubLaneMasks[2] = {
14478       SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef),
14479       SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef)};
14480 
14481   for (int DstSubLane = 0; DstSubLane != NumSubLanes; ++DstSubLane) {
14482     // Extract the sub-lane mask, check that it all comes from the same lane
14483     // and normalize the mask entries to come from the first lane.
14484     int SrcLane = -1;
14485     SmallVector<int, 8> SubLaneMask((unsigned)NumSubLaneElts, -1);
14486     for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
14487       int M = Mask[(DstSubLane * NumSubLaneElts) + Elt];
14488       if (M < 0)
14489         continue;
14490       int Lane = (M % NumElts) / NumLaneElts;
14491       if ((0 <= SrcLane) && (SrcLane != Lane))
14492         return SDValue();
14493       SrcLane = Lane;
14494       int LocalM = (M % NumLaneElts) + (M < NumElts ? 0 : NumElts);
14495       SubLaneMask[Elt] = LocalM;
14496     }
14497 
14498     // Whole sub-lane is UNDEF.
14499     if (SrcLane < 0)
14500       continue;
14501 
14502     // Attempt to match against the candidate repeated sub-lane masks.
14503     for (int SubLane = 0; SubLane != SubLaneScale; ++SubLane) {
14504       auto MatchMasks = [NumSubLaneElts](ArrayRef<int> M1, ArrayRef<int> M2) {
14505         for (int i = 0; i != NumSubLaneElts; ++i) {
14506           if (M1[i] < 0 || M2[i] < 0)
14507             continue;
14508           if (M1[i] != M2[i])
14509             return false;
14510         }
14511         return true;
14512       };
14513 
14514       auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane];
14515       if (!MatchMasks(SubLaneMask, RepeatedSubLaneMask))
14516         continue;
14517 
14518       // Merge the sub-lane mask into the matching repeated sub-lane mask.
14519       for (int i = 0; i != NumSubLaneElts; ++i) {
14520         int M = SubLaneMask[i];
14521         if (M < 0)
14522           continue;
14523         assert((RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] == M) &&
14524                "Unexpected mask element");
14525         RepeatedSubLaneMask[i] = M;
14526       }
14527 
14528       // Track the top most source sub-lane - by setting the remaining to UNDEF
14529       // we can greatly simplify shuffle matching.
14530       int SrcSubLane = (SrcLane * SubLaneScale) + SubLane;
14531       TopSrcSubLane = std::max(TopSrcSubLane, SrcSubLane);
14532       Dst2SrcSubLanes[DstSubLane] = SrcSubLane;
14533       break;
14534     }
14535 
14536     // Bail if we failed to find a matching repeated sub-lane mask.
14537     if (Dst2SrcSubLanes[DstSubLane] < 0)
14538       return SDValue();
14539   }
14540   assert(0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes &&
14541          "Unexpected source lane");
14542 
14543   // Create a repeating shuffle mask for the entire vector.
14544   SmallVector<int, 8> RepeatedMask((unsigned)NumElts, -1);
14545   for (int SubLane = 0; SubLane <= TopSrcSubLane; ++SubLane) {
14546     int Lane = SubLane / SubLaneScale;
14547     auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane % SubLaneScale];
14548     for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
14549       int M = RepeatedSubLaneMask[Elt];
14550       if (M < 0)
14551         continue;
14552       int Idx = (SubLane * NumSubLaneElts) + Elt;
14553       RepeatedMask[Idx] = M + (Lane * NumLaneElts);
14554     }
14555   }
14556   SDValue RepeatedShuffle = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatedMask);
14557 
14558   // Shuffle each source sub-lane to its destination.
14559   SmallVector<int, 8> SubLaneMask((unsigned)NumElts, -1);
14560   for (int i = 0; i != NumElts; i += NumSubLaneElts) {
14561     int SrcSubLane = Dst2SrcSubLanes[i / NumSubLaneElts];
14562     if (SrcSubLane < 0)
14563       continue;
14564     for (int j = 0; j != NumSubLaneElts; ++j)
14565       SubLaneMask[i + j] = j + (SrcSubLane * NumSubLaneElts);
14566   }
14567 
14568   return DAG.getVectorShuffle(VT, DL, RepeatedShuffle, DAG.getUNDEF(VT),
14569                               SubLaneMask);
14570 }
14571 
matchVectorShuffleWithSHUFPD(MVT VT,SDValue & V1,SDValue & V2,unsigned & ShuffleImm,ArrayRef<int> Mask)14572 static bool matchVectorShuffleWithSHUFPD(MVT VT, SDValue &V1, SDValue &V2,
14573                                          unsigned &ShuffleImm,
14574                                          ArrayRef<int> Mask) {
14575   int NumElts = VT.getVectorNumElements();
14576   assert(VT.getScalarSizeInBits() == 64 &&
14577          (NumElts == 2 || NumElts == 4 || NumElts == 8) &&
14578          "Unexpected data type for VSHUFPD");
14579 
14580   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
14581   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
14582   ShuffleImm = 0;
14583   bool ShufpdMask = true;
14584   bool CommutableMask = true;
14585   for (int i = 0; i < NumElts; ++i) {
14586     if (Mask[i] == SM_SentinelUndef)
14587       continue;
14588     if (Mask[i] < 0)
14589       return false;
14590     int Val = (i & 6) + NumElts * (i & 1);
14591     int CommutVal = (i & 0xe) + NumElts * ((i & 1) ^ 1);
14592     if (Mask[i] < Val || Mask[i] > Val + 1)
14593       ShufpdMask = false;
14594     if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
14595       CommutableMask = false;
14596     ShuffleImm |= (Mask[i] % 2) << i;
14597   }
14598 
14599   if (ShufpdMask)
14600     return true;
14601   if (CommutableMask) {
14602     std::swap(V1, V2);
14603     return true;
14604   }
14605 
14606   return false;
14607 }
14608 
lowerVectorShuffleWithSHUFPD(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,SelectionDAG & DAG)14609 static SDValue lowerVectorShuffleWithSHUFPD(const SDLoc &DL, MVT VT,
14610                                             ArrayRef<int> Mask, SDValue V1,
14611                                             SDValue V2, SelectionDAG &DAG) {
14612   assert((VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v8f64)&&
14613          "Unexpected data type for VSHUFPD");
14614 
14615   unsigned Immediate = 0;
14616   if (!matchVectorShuffleWithSHUFPD(VT, V1, V2, Immediate, Mask))
14617     return SDValue();
14618 
14619   return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
14620                      DAG.getConstant(Immediate, DL, MVT::i8));
14621 }
14622 
14623 /// Handle lowering of 4-lane 64-bit floating point shuffles.
14624 ///
14625 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
14626 /// isn't available.
lowerV4F64VectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)14627 static SDValue lowerV4F64VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
14628                                        const APInt &Zeroable,
14629                                        SDValue V1, SDValue V2,
14630                                        const X86Subtarget &Subtarget,
14631                                        SelectionDAG &DAG) {
14632   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
14633   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
14634   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
14635 
14636   if (SDValue V = lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask,
14637                                            Zeroable, Subtarget, DAG))
14638     return V;
14639 
14640   if (V2.isUndef()) {
14641     // Check for being able to broadcast a single element.
14642     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(
14643             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
14644       return Broadcast;
14645 
14646     // Use low duplicate instructions for masks that match their pattern.
14647     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
14648       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
14649 
14650     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
14651       // Non-half-crossing single input shuffles can be lowered with an
14652       // interleaved permutation.
14653       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
14654                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
14655       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
14656                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
14657     }
14658 
14659     // With AVX2 we have direct support for this permutation.
14660     if (Subtarget.hasAVX2())
14661       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
14662                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
14663 
14664     // Try to create an in-lane repeating shuffle mask and then shuffle the
14665     // results into the target lanes.
14666     if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
14667             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
14668       return V;
14669 
14670     // Try to permute the lanes and then use a per-lane permute.
14671     if (SDValue V = lowerVectorShuffleAsLanePermuteAndPermute(
14672             DL, MVT::v4f64, V1, V2, Mask, DAG, Subtarget))
14673       return V;
14674 
14675     // Otherwise, fall back.
14676     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
14677                                                    DAG, Subtarget);
14678   }
14679 
14680   // Use dedicated unpack instructions for masks that match their pattern.
14681   if (SDValue V =
14682           lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
14683     return V;
14684 
14685   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
14686                                                 Zeroable, Subtarget, DAG))
14687     return Blend;
14688 
14689   // Check if the blend happens to exactly fit that of SHUFPD.
14690   if (SDValue Op =
14691       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
14692     return Op;
14693 
14694   // Try to create an in-lane repeating shuffle mask and then shuffle the
14695   // results into the target lanes.
14696   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
14697           DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
14698     return V;
14699 
14700   // Try to simplify this by merging 128-bit lanes to enable a lane-based
14701   // shuffle. However, if we have AVX2 and either inputs are already in place,
14702   // we will be able to shuffle even across lanes the other input in a single
14703   // instruction so skip this pattern.
14704   if (!(Subtarget.hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
14705                                 isShuffleMaskInputInPlace(1, Mask))))
14706     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
14707             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
14708       return Result;
14709 
14710   // If we have VLX support, we can use VEXPAND.
14711   if (Subtarget.hasVLX())
14712     if (SDValue V = lowerVectorShuffleToEXPAND(DL, MVT::v4f64, Zeroable, Mask,
14713                                                V1, V2, DAG, Subtarget))
14714       return V;
14715 
14716   // If we have AVX2 then we always want to lower with a blend because an v4 we
14717   // can fully permute the elements.
14718   if (Subtarget.hasAVX2())
14719     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
14720                                                       Mask, Subtarget, DAG);
14721 
14722   // Otherwise fall back on generic lowering.
14723   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask,
14724                                           Subtarget, DAG);
14725 }
14726 
14727 /// Handle lowering of 4-lane 64-bit integer shuffles.
14728 ///
14729 /// This routine is only called when we have AVX2 and thus a reasonable
14730 /// instruction set for v4i64 shuffling..
lowerV4I64VectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)14731 static SDValue lowerV4I64VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
14732                                        const APInt &Zeroable,
14733                                        SDValue V1, SDValue V2,
14734                                        const X86Subtarget &Subtarget,
14735                                        SelectionDAG &DAG) {
14736   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
14737   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
14738   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
14739   assert(Subtarget.hasAVX2() && "We can only lower v4i64 with AVX2!");
14740 
14741   if (SDValue V = lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask,
14742                                            Zeroable, Subtarget, DAG))
14743     return V;
14744 
14745   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
14746                                                 Zeroable, Subtarget, DAG))
14747     return Blend;
14748 
14749   // Check for being able to broadcast a single element.
14750   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1, V2,
14751                                                         Mask, Subtarget, DAG))
14752     return Broadcast;
14753 
14754   if (V2.isUndef()) {
14755     // When the shuffle is mirrored between the 128-bit lanes of the unit, we
14756     // can use lower latency instructions that will operate on both lanes.
14757     SmallVector<int, 2> RepeatedMask;
14758     if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
14759       SmallVector<int, 4> PSHUFDMask;
14760       scaleShuffleMask<int>(2, RepeatedMask, PSHUFDMask);
14761       return DAG.getBitcast(
14762           MVT::v4i64,
14763           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
14764                       DAG.getBitcast(MVT::v8i32, V1),
14765                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
14766     }
14767 
14768     // AVX2 provides a direct instruction for permuting a single input across
14769     // lanes.
14770     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
14771                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
14772   }
14773 
14774   // Try to use shift instructions.
14775   if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask,
14776                                                 Zeroable, Subtarget, DAG))
14777     return Shift;
14778 
14779   // If we have VLX support, we can use VALIGN or VEXPAND.
14780   if (Subtarget.hasVLX()) {
14781     if (SDValue Rotate = lowerVectorShuffleAsRotate(DL, MVT::v4i64, V1, V2,
14782                                                     Mask, Subtarget, DAG))
14783       return Rotate;
14784 
14785     if (SDValue V = lowerVectorShuffleToEXPAND(DL, MVT::v4i64, Zeroable, Mask,
14786                                                V1, V2, DAG, Subtarget))
14787       return V;
14788   }
14789 
14790   // Try to use PALIGNR.
14791   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v4i64, V1, V2,
14792                                                       Mask, Subtarget, DAG))
14793     return Rotate;
14794 
14795   // Use dedicated unpack instructions for masks that match their pattern.
14796   if (SDValue V =
14797           lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
14798     return V;
14799 
14800   // Try to create an in-lane repeating shuffle mask and then shuffle the
14801   // results into the target lanes.
14802   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
14803           DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
14804     return V;
14805 
14806   // Try to simplify this by merging 128-bit lanes to enable a lane-based
14807   // shuffle. However, if we have AVX2 and either inputs are already in place,
14808   // we will be able to shuffle even across lanes the other input in a single
14809   // instruction so skip this pattern.
14810   if (!isShuffleMaskInputInPlace(0, Mask) &&
14811       !isShuffleMaskInputInPlace(1, Mask))
14812     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
14813             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
14814       return Result;
14815 
14816   // Otherwise fall back on generic blend lowering.
14817   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
14818                                                     Mask, Subtarget, DAG);
14819 }
14820 
14821 /// Handle lowering of 8-lane 32-bit floating point shuffles.
14822 ///
14823 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
14824 /// isn't available.
lowerV8F32VectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)14825 static SDValue lowerV8F32VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
14826                                        const APInt &Zeroable,
14827                                        SDValue V1, SDValue V2,
14828                                        const X86Subtarget &Subtarget,
14829                                        SelectionDAG &DAG) {
14830   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
14831   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
14832   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
14833 
14834   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
14835                                                 Zeroable, Subtarget, DAG))
14836     return Blend;
14837 
14838   // Check for being able to broadcast a single element.
14839   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1, V2,
14840                                                         Mask, Subtarget, DAG))
14841     return Broadcast;
14842 
14843   // If the shuffle mask is repeated in each 128-bit lane, we have many more
14844   // options to efficiently lower the shuffle.
14845   SmallVector<int, 4> RepeatedMask;
14846   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
14847     assert(RepeatedMask.size() == 4 &&
14848            "Repeated masks must be half the mask width!");
14849 
14850     // Use even/odd duplicate instructions for masks that match their pattern.
14851     if (isShuffleEquivalent(V1, V2, RepeatedMask, {0, 0, 2, 2}))
14852       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
14853     if (isShuffleEquivalent(V1, V2, RepeatedMask, {1, 1, 3, 3}))
14854       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
14855 
14856     if (V2.isUndef())
14857       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
14858                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
14859 
14860     // Use dedicated unpack instructions for masks that match their pattern.
14861     if (SDValue V =
14862             lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
14863       return V;
14864 
14865     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
14866     // have already handled any direct blends.
14867     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
14868   }
14869 
14870   // Try to create an in-lane repeating shuffle mask and then shuffle the
14871   // results into the target lanes.
14872   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
14873           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
14874     return V;
14875 
14876   // If we have a single input shuffle with different shuffle patterns in the
14877   // two 128-bit lanes use the variable mask to VPERMILPS.
14878   if (V2.isUndef()) {
14879     SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
14880     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
14881       return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, V1, VPermMask);
14882 
14883     if (Subtarget.hasAVX2())
14884       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32, VPermMask, V1);
14885 
14886     // Otherwise, fall back.
14887     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
14888                                                    DAG, Subtarget);
14889   }
14890 
14891   // Try to simplify this by merging 128-bit lanes to enable a lane-based
14892   // shuffle.
14893   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
14894           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
14895     return Result;
14896   // If we have VLX support, we can use VEXPAND.
14897   if (Subtarget.hasVLX())
14898     if (SDValue V = lowerVectorShuffleToEXPAND(DL, MVT::v8f32, Zeroable, Mask,
14899                                                V1, V2, DAG, Subtarget))
14900       return V;
14901 
14902   // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
14903   // since after split we get a more efficient code using vpunpcklwd and
14904   // vpunpckhwd instrs than vblend.
14905   if (!Subtarget.hasAVX512() && isUnpackWdShuffleMask(Mask, MVT::v8f32))
14906     if (SDValue V = lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2,
14907                                                      Mask, Subtarget, DAG))
14908       return V;
14909 
14910   // If we have AVX2 then we always want to lower with a blend because at v8 we
14911   // can fully permute the elements.
14912   if (Subtarget.hasAVX2())
14913     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
14914                                                       Mask, Subtarget, DAG);
14915 
14916   // Otherwise fall back on generic lowering.
14917   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask,
14918                                           Subtarget, DAG);
14919 }
14920 
14921 /// Handle lowering of 8-lane 32-bit integer shuffles.
14922 ///
14923 /// This routine is only called when we have AVX2 and thus a reasonable
14924 /// instruction set for v8i32 shuffling..
lowerV8I32VectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)14925 static SDValue lowerV8I32VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
14926                                        const APInt &Zeroable,
14927                                        SDValue V1, SDValue V2,
14928                                        const X86Subtarget &Subtarget,
14929                                        SelectionDAG &DAG) {
14930   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
14931   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
14932   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
14933   assert(Subtarget.hasAVX2() && "We can only lower v8i32 with AVX2!");
14934 
14935   // Whenever we can lower this as a zext, that instruction is strictly faster
14936   // than any alternative. It also allows us to fold memory operands into the
14937   // shuffle in many cases.
14938   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
14939           DL, MVT::v8i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
14940     return ZExt;
14941 
14942   // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
14943   // since after split we get a more efficient code than vblend by using
14944   // vpunpcklwd and vpunpckhwd instrs.
14945   if (isUnpackWdShuffleMask(Mask, MVT::v8i32) && !V2.isUndef() &&
14946       !Subtarget.hasAVX512())
14947     if (SDValue V = lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8i32, V1, V2,
14948                                                      Mask, Subtarget, DAG))
14949       return V;
14950 
14951   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
14952                                                 Zeroable, Subtarget, DAG))
14953     return Blend;
14954 
14955   // Check for being able to broadcast a single element.
14956   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1, V2,
14957                                                         Mask, Subtarget, DAG))
14958     return Broadcast;
14959 
14960   // If the shuffle mask is repeated in each 128-bit lane we can use more
14961   // efficient instructions that mirror the shuffles across the two 128-bit
14962   // lanes.
14963   SmallVector<int, 4> RepeatedMask;
14964   bool Is128BitLaneRepeatedShuffle =
14965       is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask);
14966   if (Is128BitLaneRepeatedShuffle) {
14967     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
14968     if (V2.isUndef())
14969       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
14970                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
14971 
14972     // Use dedicated unpack instructions for masks that match their pattern.
14973     if (SDValue V =
14974             lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
14975       return V;
14976   }
14977 
14978   // Try to use shift instructions.
14979   if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask,
14980                                                 Zeroable, Subtarget, DAG))
14981     return Shift;
14982 
14983   // If we have VLX support, we can use VALIGN or EXPAND.
14984   if (Subtarget.hasVLX()) {
14985     if (SDValue Rotate = lowerVectorShuffleAsRotate(DL, MVT::v8i32, V1, V2,
14986                                                     Mask, Subtarget, DAG))
14987       return Rotate;
14988 
14989     if (SDValue V = lowerVectorShuffleToEXPAND(DL, MVT::v8i32, Zeroable, Mask,
14990                                                V1, V2, DAG, Subtarget))
14991       return V;
14992   }
14993 
14994   // Try to use byte rotation instructions.
14995   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
14996           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
14997     return Rotate;
14998 
14999   // Try to create an in-lane repeating shuffle mask and then shuffle the
15000   // results into the target lanes.
15001   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
15002           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
15003     return V;
15004 
15005   // If the shuffle patterns aren't repeated but it is a single input, directly
15006   // generate a cross-lane VPERMD instruction.
15007   if (V2.isUndef()) {
15008     SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
15009     return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8i32, VPermMask, V1);
15010   }
15011 
15012   // Assume that a single SHUFPS is faster than an alternative sequence of
15013   // multiple instructions (even if the CPU has a domain penalty).
15014   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
15015   if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
15016     SDValue CastV1 = DAG.getBitcast(MVT::v8f32, V1);
15017     SDValue CastV2 = DAG.getBitcast(MVT::v8f32, V2);
15018     SDValue ShufPS = lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask,
15019                                                   CastV1, CastV2, DAG);
15020     return DAG.getBitcast(MVT::v8i32, ShufPS);
15021   }
15022 
15023   // Try to simplify this by merging 128-bit lanes to enable a lane-based
15024   // shuffle.
15025   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
15026           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
15027     return Result;
15028 
15029   // Otherwise fall back on generic blend lowering.
15030   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
15031                                                     Mask, Subtarget, DAG);
15032 }
15033 
15034 /// Handle lowering of 16-lane 16-bit integer shuffles.
15035 ///
15036 /// This routine is only called when we have AVX2 and thus a reasonable
15037 /// instruction set for v16i16 shuffling..
lowerV16I16VectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)15038 static SDValue lowerV16I16VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
15039                                         const APInt &Zeroable,
15040                                         SDValue V1, SDValue V2,
15041                                         const X86Subtarget &Subtarget,
15042                                         SelectionDAG &DAG) {
15043   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
15044   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
15045   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
15046   assert(Subtarget.hasAVX2() && "We can only lower v16i16 with AVX2!");
15047 
15048   // Whenever we can lower this as a zext, that instruction is strictly faster
15049   // than any alternative. It also allows us to fold memory operands into the
15050   // shuffle in many cases.
15051   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
15052           DL, MVT::v16i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
15053     return ZExt;
15054 
15055   // Check for being able to broadcast a single element.
15056   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1, V2,
15057                                                         Mask, Subtarget, DAG))
15058     return Broadcast;
15059 
15060   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
15061                                                 Zeroable, Subtarget, DAG))
15062     return Blend;
15063 
15064   // Use dedicated unpack instructions for masks that match their pattern.
15065   if (SDValue V =
15066           lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
15067     return V;
15068 
15069   // Use dedicated pack instructions for masks that match their pattern.
15070   if (SDValue V = lowerVectorShuffleWithPACK(DL, MVT::v16i16, Mask, V1, V2, DAG,
15071                                              Subtarget))
15072     return V;
15073 
15074   // Try to use shift instructions.
15075   if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask,
15076                                                 Zeroable, Subtarget, DAG))
15077     return Shift;
15078 
15079   // Try to use byte rotation instructions.
15080   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
15081           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
15082     return Rotate;
15083 
15084   // Try to create an in-lane repeating shuffle mask and then shuffle the
15085   // results into the target lanes.
15086   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
15087           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
15088     return V;
15089 
15090   if (V2.isUndef()) {
15091     // There are no generalized cross-lane shuffle operations available on i16
15092     // element types.
15093     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask)) {
15094       if (SDValue V = lowerVectorShuffleAsLanePermuteAndPermute(
15095               DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
15096         return V;
15097 
15098       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
15099                                                      Mask, DAG, Subtarget);
15100     }
15101 
15102     SmallVector<int, 8> RepeatedMask;
15103     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
15104       // As this is a single-input shuffle, the repeated mask should be
15105       // a strictly valid v8i16 mask that we can pass through to the v8i16
15106       // lowering to handle even the v16 case.
15107       return lowerV8I16GeneralSingleInputVectorShuffle(
15108           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
15109     }
15110   }
15111 
15112   if (SDValue PSHUFB = lowerVectorShuffleWithPSHUFB(
15113           DL, MVT::v16i16, Mask, V1, V2, Zeroable, Subtarget, DAG))
15114     return PSHUFB;
15115 
15116   // AVX512BWVL can lower to VPERMW.
15117   if (Subtarget.hasBWI() && Subtarget.hasVLX())
15118     return lowerVectorShuffleWithPERMV(DL, MVT::v16i16, Mask, V1, V2, DAG);
15119 
15120   // Try to simplify this by merging 128-bit lanes to enable a lane-based
15121   // shuffle.
15122   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
15123           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
15124     return Result;
15125 
15126   // Try to permute the lanes and then use a per-lane permute.
15127   if (SDValue V = lowerVectorShuffleAsLanePermuteAndPermute(
15128           DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
15129     return V;
15130 
15131   // Otherwise fall back on generic lowering.
15132   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask,
15133                                           Subtarget, DAG);
15134 }
15135 
15136 /// Handle lowering of 32-lane 8-bit integer shuffles.
15137 ///
15138 /// This routine is only called when we have AVX2 and thus a reasonable
15139 /// instruction set for v32i8 shuffling..
lowerV32I8VectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)15140 static SDValue lowerV32I8VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
15141                                        const APInt &Zeroable,
15142                                        SDValue V1, SDValue V2,
15143                                        const X86Subtarget &Subtarget,
15144                                        SelectionDAG &DAG) {
15145   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
15146   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
15147   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
15148   assert(Subtarget.hasAVX2() && "We can only lower v32i8 with AVX2!");
15149 
15150   // Whenever we can lower this as a zext, that instruction is strictly faster
15151   // than any alternative. It also allows us to fold memory operands into the
15152   // shuffle in many cases.
15153   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
15154           DL, MVT::v32i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
15155     return ZExt;
15156 
15157   // Check for being able to broadcast a single element.
15158   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1, V2,
15159                                                         Mask, Subtarget, DAG))
15160     return Broadcast;
15161 
15162   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
15163                                                 Zeroable, Subtarget, DAG))
15164     return Blend;
15165 
15166   // Use dedicated unpack instructions for masks that match their pattern.
15167   if (SDValue V =
15168           lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
15169     return V;
15170 
15171   // Use dedicated pack instructions for masks that match their pattern.
15172   if (SDValue V = lowerVectorShuffleWithPACK(DL, MVT::v32i8, Mask, V1, V2, DAG,
15173                                              Subtarget))
15174     return V;
15175 
15176   // Try to use shift instructions.
15177   if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask,
15178                                                 Zeroable, Subtarget, DAG))
15179     return Shift;
15180 
15181   // Try to use byte rotation instructions.
15182   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
15183           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
15184     return Rotate;
15185 
15186   // Try to create an in-lane repeating shuffle mask and then shuffle the
15187   // results into the target lanes.
15188   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
15189           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
15190     return V;
15191 
15192   // There are no generalized cross-lane shuffle operations available on i8
15193   // element types.
15194   if (V2.isUndef() && is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask)) {
15195     if (SDValue V = lowerVectorShuffleAsLanePermuteAndPermute(
15196             DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
15197       return V;
15198 
15199     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2, Mask,
15200                                                    DAG, Subtarget);
15201   }
15202 
15203   if (SDValue PSHUFB = lowerVectorShuffleWithPSHUFB(
15204           DL, MVT::v32i8, Mask, V1, V2, Zeroable, Subtarget, DAG))
15205     return PSHUFB;
15206 
15207   // AVX512VBMIVL can lower to VPERMB.
15208   if (Subtarget.hasVBMI() && Subtarget.hasVLX())
15209     return lowerVectorShuffleWithPERMV(DL, MVT::v32i8, Mask, V1, V2, DAG);
15210 
15211   // Try to simplify this by merging 128-bit lanes to enable a lane-based
15212   // shuffle.
15213   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
15214           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
15215     return Result;
15216 
15217   // Try to permute the lanes and then use a per-lane permute.
15218   if (SDValue V = lowerVectorShuffleAsLanePermuteAndPermute(
15219           DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
15220     return V;
15221 
15222   // Otherwise fall back on generic lowering.
15223   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask,
15224                                           Subtarget, DAG);
15225 }
15226 
15227 /// High-level routine to lower various 256-bit x86 vector shuffles.
15228 ///
15229 /// This routine either breaks down the specific type of a 256-bit x86 vector
15230 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
15231 /// together based on the available instructions.
lower256BitVectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,MVT VT,SDValue V1,SDValue V2,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)15232 static SDValue lower256BitVectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
15233                                         MVT VT, SDValue V1, SDValue V2,
15234                                         const APInt &Zeroable,
15235                                         const X86Subtarget &Subtarget,
15236                                         SelectionDAG &DAG) {
15237   // If we have a single input to the zero element, insert that into V1 if we
15238   // can do so cheaply.
15239   int NumElts = VT.getVectorNumElements();
15240   int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
15241 
15242   if (NumV2Elements == 1 && Mask[0] >= NumElts)
15243     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
15244             DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
15245       return Insertion;
15246 
15247   // Handle special cases where the lower or upper half is UNDEF.
15248   if (SDValue V =
15249           lowerVectorShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
15250     return V;
15251 
15252   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
15253   // can check for those subtargets here and avoid much of the subtarget
15254   // querying in the per-vector-type lowering routines. With AVX1 we have
15255   // essentially *zero* ability to manipulate a 256-bit vector with integer
15256   // types. Since we'll use floating point types there eventually, just
15257   // immediately cast everything to a float and operate entirely in that domain.
15258   if (VT.isInteger() && !Subtarget.hasAVX2()) {
15259     int ElementBits = VT.getScalarSizeInBits();
15260     if (ElementBits < 32) {
15261       // No floating point type available, if we can't use the bit operations
15262       // for masking/blending then decompose into 128-bit vectors.
15263       if (SDValue V =
15264               lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable, DAG))
15265         return V;
15266       if (SDValue V = lowerVectorShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
15267         return V;
15268       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
15269     }
15270 
15271     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
15272                                 VT.getVectorNumElements());
15273     V1 = DAG.getBitcast(FpVT, V1);
15274     V2 = DAG.getBitcast(FpVT, V2);
15275     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
15276   }
15277 
15278   switch (VT.SimpleTy) {
15279   case MVT::v4f64:
15280     return lowerV4F64VectorShuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15281   case MVT::v4i64:
15282     return lowerV4I64VectorShuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15283   case MVT::v8f32:
15284     return lowerV8F32VectorShuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15285   case MVT::v8i32:
15286     return lowerV8I32VectorShuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15287   case MVT::v16i16:
15288     return lowerV16I16VectorShuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15289   case MVT::v32i8:
15290     return lowerV32I8VectorShuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15291 
15292   default:
15293     llvm_unreachable("Not a valid 256-bit x86 vector type!");
15294   }
15295 }
15296 
15297 /// Try to lower a vector shuffle as a 128-bit shuffles.
lowerV4X128VectorShuffle(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)15298 static SDValue lowerV4X128VectorShuffle(const SDLoc &DL, MVT VT,
15299                                         ArrayRef<int> Mask,
15300                                         const APInt &Zeroable,
15301                                         SDValue V1, SDValue V2,
15302                                         const X86Subtarget &Subtarget,
15303                                         SelectionDAG &DAG) {
15304   assert(VT.getScalarSizeInBits() == 64 &&
15305          "Unexpected element type size for 128bit shuffle.");
15306 
15307   // To handle 256 bit vector requires VLX and most probably
15308   // function lowerV2X128VectorShuffle() is better solution.
15309   assert(VT.is512BitVector() && "Unexpected vector size for 512bit shuffle.");
15310 
15311   // TODO - use Zeroable like we do for lowerV2X128VectorShuffle?
15312   SmallVector<int, 4> WidenedMask;
15313   if (!canWidenShuffleElements(Mask, WidenedMask))
15314     return SDValue();
15315 
15316   // Try to use an insert into a zero vector.
15317   if (WidenedMask[0] == 0 && (Zeroable & 0xf0) == 0xf0 &&
15318       (WidenedMask[1] == 1 || (Zeroable & 0x0c) == 0x0c)) {
15319     unsigned NumElts = ((Zeroable & 0x0c) == 0x0c) ? 2 : 4;
15320     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
15321     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
15322                               DAG.getIntPtrConstant(0, DL));
15323     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
15324                        getZeroVector(VT, Subtarget, DAG, DL), LoV,
15325                        DAG.getIntPtrConstant(0, DL));
15326   }
15327 
15328   // Check for patterns which can be matched with a single insert of a 256-bit
15329   // subvector.
15330   bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask,
15331                                         {0, 1, 2, 3, 0, 1, 2, 3});
15332   if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask,
15333                                         {0, 1, 2, 3, 8, 9, 10, 11})) {
15334     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 4);
15335     SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
15336                                  OnlyUsesV1 ? V1 : V2,
15337                               DAG.getIntPtrConstant(0, DL));
15338     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
15339                        DAG.getIntPtrConstant(4, DL));
15340   }
15341 
15342   assert(WidenedMask.size() == 4);
15343 
15344   // See if this is an insertion of the lower 128-bits of V2 into V1.
15345   bool IsInsert = true;
15346   int V2Index = -1;
15347   for (int i = 0; i < 4; ++i) {
15348     assert(WidenedMask[i] >= -1);
15349     if (WidenedMask[i] < 0)
15350       continue;
15351 
15352     // Make sure all V1 subvectors are in place.
15353     if (WidenedMask[i] < 4) {
15354       if (WidenedMask[i] != i) {
15355         IsInsert = false;
15356         break;
15357       }
15358     } else {
15359       // Make sure we only have a single V2 index and its the lowest 128-bits.
15360       if (V2Index >= 0 || WidenedMask[i] != 4) {
15361         IsInsert = false;
15362         break;
15363       }
15364       V2Index = i;
15365     }
15366   }
15367   if (IsInsert && V2Index >= 0) {
15368     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
15369     SDValue Subvec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
15370                                  DAG.getIntPtrConstant(0, DL));
15371     return insert128BitVector(V1, Subvec, V2Index * 2, DAG, DL);
15372   }
15373 
15374   // Try to lower to vshuf64x2/vshuf32x4.
15375   SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
15376   unsigned PermMask = 0;
15377   // Insure elements came from the same Op.
15378   for (int i = 0; i < 4; ++i) {
15379     assert(WidenedMask[i] >= -1);
15380     if (WidenedMask[i] < 0)
15381       continue;
15382 
15383     SDValue Op = WidenedMask[i] >= 4 ? V2 : V1;
15384     unsigned OpIndex = i / 2;
15385     if (Ops[OpIndex].isUndef())
15386       Ops[OpIndex] = Op;
15387     else if (Ops[OpIndex] != Op)
15388       return SDValue();
15389 
15390     // Convert the 128-bit shuffle mask selection values into 128-bit selection
15391     // bits defined by a vshuf64x2 instruction's immediate control byte.
15392     PermMask |= (WidenedMask[i] % 4) << (i * 2);
15393   }
15394 
15395   return DAG.getNode(X86ISD::SHUF128, DL, VT, Ops[0], Ops[1],
15396                      DAG.getConstant(PermMask, DL, MVT::i8));
15397 }
15398 
15399 /// Handle lowering of 8-lane 64-bit floating point shuffles.
lowerV8F64VectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)15400 static SDValue lowerV8F64VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
15401                                        const APInt &Zeroable,
15402                                        SDValue V1, SDValue V2,
15403                                        const X86Subtarget &Subtarget,
15404                                        SelectionDAG &DAG) {
15405   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
15406   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
15407   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
15408 
15409   if (V2.isUndef()) {
15410     // Use low duplicate instructions for masks that match their pattern.
15411     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
15412       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v8f64, V1);
15413 
15414     if (!is128BitLaneCrossingShuffleMask(MVT::v8f64, Mask)) {
15415       // Non-half-crossing single input shuffles can be lowered with an
15416       // interleaved permutation.
15417       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
15418                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3) |
15419                               ((Mask[4] == 5) << 4) | ((Mask[5] == 5) << 5) |
15420                               ((Mask[6] == 7) << 6) | ((Mask[7] == 7) << 7);
15421       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f64, V1,
15422                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
15423     }
15424 
15425     SmallVector<int, 4> RepeatedMask;
15426     if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask))
15427       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8f64, V1,
15428                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
15429   }
15430 
15431   if (SDValue Shuf128 =
15432           lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, Zeroable, V1, V2,
15433                                    Subtarget, DAG))
15434     return Shuf128;
15435 
15436   if (SDValue Unpck =
15437           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
15438     return Unpck;
15439 
15440   // Check if the blend happens to exactly fit that of SHUFPD.
15441   if (SDValue Op =
15442       lowerVectorShuffleWithSHUFPD(DL, MVT::v8f64, Mask, V1, V2, DAG))
15443     return Op;
15444 
15445   if (SDValue V = lowerVectorShuffleToEXPAND(DL, MVT::v8f64, Zeroable, Mask, V1,
15446                                              V2, DAG, Subtarget))
15447     return V;
15448 
15449   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f64, V1, V2, Mask,
15450                                                 Zeroable, Subtarget, DAG))
15451     return Blend;
15452 
15453   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
15454 }
15455 
15456 /// Handle lowering of 16-lane 32-bit floating point shuffles.
lowerV16F32VectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)15457 static SDValue lowerV16F32VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
15458                                         const APInt &Zeroable,
15459                                         SDValue V1, SDValue V2,
15460                                         const X86Subtarget &Subtarget,
15461                                         SelectionDAG &DAG) {
15462   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
15463   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
15464   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
15465 
15466   // If the shuffle mask is repeated in each 128-bit lane, we have many more
15467   // options to efficiently lower the shuffle.
15468   SmallVector<int, 4> RepeatedMask;
15469   if (is128BitLaneRepeatedShuffleMask(MVT::v16f32, Mask, RepeatedMask)) {
15470     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
15471 
15472     // Use even/odd duplicate instructions for masks that match their pattern.
15473     if (isShuffleEquivalent(V1, V2, RepeatedMask, {0, 0, 2, 2}))
15474       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v16f32, V1);
15475     if (isShuffleEquivalent(V1, V2, RepeatedMask, {1, 1, 3, 3}))
15476       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v16f32, V1);
15477 
15478     if (V2.isUndef())
15479       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v16f32, V1,
15480                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
15481 
15482     // Use dedicated unpack instructions for masks that match their pattern.
15483     if (SDValue Unpck =
15484             lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
15485       return Unpck;
15486 
15487     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16f32, V1, V2, Mask,
15488                                                   Zeroable, Subtarget, DAG))
15489       return Blend;
15490 
15491     // Otherwise, fall back to a SHUFPS sequence.
15492     return lowerVectorShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask, V1, V2, DAG);
15493   }
15494 
15495   // If we have a single input shuffle with different shuffle patterns in the
15496   // 128-bit lanes and don't lane cross, use variable mask VPERMILPS.
15497   if (V2.isUndef() &&
15498       !is128BitLaneCrossingShuffleMask(MVT::v16f32, Mask)) {
15499     SDValue VPermMask = getConstVector(Mask, MVT::v16i32, DAG, DL, true);
15500     return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v16f32, V1, VPermMask);
15501   }
15502 
15503   // If we have AVX512F support, we can use VEXPAND.
15504   if (SDValue V = lowerVectorShuffleToEXPAND(DL, MVT::v16f32, Zeroable, Mask,
15505                                              V1, V2, DAG, Subtarget))
15506     return V;
15507 
15508   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
15509 }
15510 
15511 /// Handle lowering of 8-lane 64-bit integer shuffles.
lowerV8I64VectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)15512 static SDValue lowerV8I64VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
15513                                        const APInt &Zeroable,
15514                                        SDValue V1, SDValue V2,
15515                                        const X86Subtarget &Subtarget,
15516                                        SelectionDAG &DAG) {
15517   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
15518   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
15519   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
15520 
15521   if (V2.isUndef()) {
15522     // When the shuffle is mirrored between the 128-bit lanes of the unit, we
15523     // can use lower latency instructions that will operate on all four
15524     // 128-bit lanes.
15525     SmallVector<int, 2> Repeated128Mask;
15526     if (is128BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated128Mask)) {
15527       SmallVector<int, 4> PSHUFDMask;
15528       scaleShuffleMask<int>(2, Repeated128Mask, PSHUFDMask);
15529       return DAG.getBitcast(
15530           MVT::v8i64,
15531           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32,
15532                       DAG.getBitcast(MVT::v16i32, V1),
15533                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
15534     }
15535 
15536     SmallVector<int, 4> Repeated256Mask;
15537     if (is256BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated256Mask))
15538       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8i64, V1,
15539                          getV4X86ShuffleImm8ForMask(Repeated256Mask, DL, DAG));
15540   }
15541 
15542   if (SDValue Shuf128 =
15543           lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, Zeroable,
15544                                    V1, V2, Subtarget, DAG))
15545     return Shuf128;
15546 
15547   // Try to use shift instructions.
15548   if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask,
15549                                                 Zeroable, Subtarget, DAG))
15550     return Shift;
15551 
15552   // Try to use VALIGN.
15553   if (SDValue Rotate = lowerVectorShuffleAsRotate(DL, MVT::v8i64, V1, V2,
15554                                                   Mask, Subtarget, DAG))
15555     return Rotate;
15556 
15557   // Try to use PALIGNR.
15558   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i64, V1, V2,
15559                                                       Mask, Subtarget, DAG))
15560     return Rotate;
15561 
15562   if (SDValue Unpck =
15563           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
15564     return Unpck;
15565   // If we have AVX512F support, we can use VEXPAND.
15566   if (SDValue V = lowerVectorShuffleToEXPAND(DL, MVT::v8i64, Zeroable, Mask, V1,
15567                                              V2, DAG, Subtarget))
15568     return V;
15569 
15570   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i64, V1, V2, Mask,
15571                                                 Zeroable, Subtarget, DAG))
15572     return Blend;
15573 
15574   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
15575 }
15576 
15577 /// Handle lowering of 16-lane 32-bit integer shuffles.
lowerV16I32VectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)15578 static SDValue lowerV16I32VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
15579                                         const APInt &Zeroable,
15580                                         SDValue V1, SDValue V2,
15581                                         const X86Subtarget &Subtarget,
15582                                         SelectionDAG &DAG) {
15583   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
15584   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
15585   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
15586 
15587   // Whenever we can lower this as a zext, that instruction is strictly faster
15588   // than any alternative. It also allows us to fold memory operands into the
15589   // shuffle in many cases.
15590   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
15591           DL, MVT::v16i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
15592     return ZExt;
15593 
15594   // If the shuffle mask is repeated in each 128-bit lane we can use more
15595   // efficient instructions that mirror the shuffles across the four 128-bit
15596   // lanes.
15597   SmallVector<int, 4> RepeatedMask;
15598   bool Is128BitLaneRepeatedShuffle =
15599       is128BitLaneRepeatedShuffleMask(MVT::v16i32, Mask, RepeatedMask);
15600   if (Is128BitLaneRepeatedShuffle) {
15601     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
15602     if (V2.isUndef())
15603       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32, V1,
15604                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
15605 
15606     // Use dedicated unpack instructions for masks that match their pattern.
15607     if (SDValue V =
15608             lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
15609       return V;
15610   }
15611 
15612   // Try to use shift instructions.
15613   if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask,
15614                                                 Zeroable, Subtarget, DAG))
15615     return Shift;
15616 
15617   // Try to use VALIGN.
15618   if (SDValue Rotate = lowerVectorShuffleAsRotate(DL, MVT::v16i32, V1, V2,
15619                                                   Mask, Subtarget, DAG))
15620     return Rotate;
15621 
15622   // Try to use byte rotation instructions.
15623   if (Subtarget.hasBWI())
15624     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
15625             DL, MVT::v16i32, V1, V2, Mask, Subtarget, DAG))
15626       return Rotate;
15627 
15628   // Assume that a single SHUFPS is faster than using a permv shuffle.
15629   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
15630   if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
15631     SDValue CastV1 = DAG.getBitcast(MVT::v16f32, V1);
15632     SDValue CastV2 = DAG.getBitcast(MVT::v16f32, V2);
15633     SDValue ShufPS = lowerVectorShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask,
15634                                                   CastV1, CastV2, DAG);
15635     return DAG.getBitcast(MVT::v16i32, ShufPS);
15636   }
15637   // If we have AVX512F support, we can use VEXPAND.
15638   if (SDValue V = lowerVectorShuffleToEXPAND(DL, MVT::v16i32, Zeroable, Mask,
15639                                              V1, V2, DAG, Subtarget))
15640     return V;
15641 
15642   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i32, V1, V2, Mask,
15643                                                 Zeroable, Subtarget, DAG))
15644     return Blend;
15645   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
15646 }
15647 
15648 /// Handle lowering of 32-lane 16-bit integer shuffles.
lowerV32I16VectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)15649 static SDValue lowerV32I16VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
15650                                         const APInt &Zeroable,
15651                                         SDValue V1, SDValue V2,
15652                                         const X86Subtarget &Subtarget,
15653                                         SelectionDAG &DAG) {
15654   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
15655   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
15656   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
15657   assert(Subtarget.hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
15658 
15659   // Whenever we can lower this as a zext, that instruction is strictly faster
15660   // than any alternative. It also allows us to fold memory operands into the
15661   // shuffle in many cases.
15662   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
15663           DL, MVT::v32i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
15664     return ZExt;
15665 
15666   // Use dedicated unpack instructions for masks that match their pattern.
15667   if (SDValue V =
15668           lowerVectorShuffleWithUNPCK(DL, MVT::v32i16, Mask, V1, V2, DAG))
15669     return V;
15670 
15671   // Try to use shift instructions.
15672   if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v32i16, V1, V2, Mask,
15673                                                 Zeroable, Subtarget, DAG))
15674     return Shift;
15675 
15676   // Try to use byte rotation instructions.
15677   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
15678           DL, MVT::v32i16, V1, V2, Mask, Subtarget, DAG))
15679     return Rotate;
15680 
15681   if (V2.isUndef()) {
15682     SmallVector<int, 8> RepeatedMask;
15683     if (is128BitLaneRepeatedShuffleMask(MVT::v32i16, Mask, RepeatedMask)) {
15684       // As this is a single-input shuffle, the repeated mask should be
15685       // a strictly valid v8i16 mask that we can pass through to the v8i16
15686       // lowering to handle even the v32 case.
15687       return lowerV8I16GeneralSingleInputVectorShuffle(
15688           DL, MVT::v32i16, V1, RepeatedMask, Subtarget, DAG);
15689     }
15690   }
15691 
15692   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i16, V1, V2, Mask,
15693                                                 Zeroable, Subtarget, DAG))
15694     return Blend;
15695 
15696   if (SDValue PSHUFB = lowerVectorShuffleWithPSHUFB(
15697           DL, MVT::v32i16, Mask, V1, V2, Zeroable, Subtarget, DAG))
15698     return PSHUFB;
15699 
15700   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
15701 }
15702 
15703 /// Handle lowering of 64-lane 8-bit integer shuffles.
lowerV64I8VectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)15704 static SDValue lowerV64I8VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
15705                                        const APInt &Zeroable,
15706                                        SDValue V1, SDValue V2,
15707                                        const X86Subtarget &Subtarget,
15708                                        SelectionDAG &DAG) {
15709   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
15710   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
15711   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
15712   assert(Subtarget.hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
15713 
15714   // Whenever we can lower this as a zext, that instruction is strictly faster
15715   // than any alternative. It also allows us to fold memory operands into the
15716   // shuffle in many cases.
15717   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
15718           DL, MVT::v64i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
15719     return ZExt;
15720 
15721   // Use dedicated unpack instructions for masks that match their pattern.
15722   if (SDValue V =
15723           lowerVectorShuffleWithUNPCK(DL, MVT::v64i8, Mask, V1, V2, DAG))
15724     return V;
15725 
15726   // Use dedicated pack instructions for masks that match their pattern.
15727   if (SDValue V = lowerVectorShuffleWithPACK(DL, MVT::v64i8, Mask, V1, V2, DAG,
15728                                              Subtarget))
15729     return V;
15730 
15731   // Try to use shift instructions.
15732   if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v64i8, V1, V2, Mask,
15733                                                 Zeroable, Subtarget, DAG))
15734     return Shift;
15735 
15736   // Try to use byte rotation instructions.
15737   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
15738           DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
15739     return Rotate;
15740 
15741   if (SDValue PSHUFB = lowerVectorShuffleWithPSHUFB(
15742           DL, MVT::v64i8, Mask, V1, V2, Zeroable, Subtarget, DAG))
15743     return PSHUFB;
15744 
15745   // VBMI can use VPERMV/VPERMV3 byte shuffles.
15746   if (Subtarget.hasVBMI())
15747     return lowerVectorShuffleWithPERMV(DL, MVT::v64i8, Mask, V1, V2, DAG);
15748 
15749   // Try to create an in-lane repeating shuffle mask and then shuffle the
15750   // results into the target lanes.
15751   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
15752           DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
15753     return V;
15754 
15755   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v64i8, V1, V2, Mask,
15756                                                 Zeroable, Subtarget, DAG))
15757     return Blend;
15758 
15759   // FIXME: Implement direct support for this type!
15760   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
15761 }
15762 
15763 /// High-level routine to lower various 512-bit x86 vector shuffles.
15764 ///
15765 /// This routine either breaks down the specific type of a 512-bit x86 vector
15766 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
15767 /// together based on the available instructions.
lower512BitVectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,MVT VT,SDValue V1,SDValue V2,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)15768 static SDValue lower512BitVectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
15769                                         MVT VT, SDValue V1, SDValue V2,
15770                                         const APInt &Zeroable,
15771                                         const X86Subtarget &Subtarget,
15772                                         SelectionDAG &DAG) {
15773   assert(Subtarget.hasAVX512() &&
15774          "Cannot lower 512-bit vectors w/ basic ISA!");
15775 
15776   // If we have a single input to the zero element, insert that into V1 if we
15777   // can do so cheaply.
15778   int NumElts = Mask.size();
15779   int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
15780 
15781   if (NumV2Elements == 1 && Mask[0] >= NumElts)
15782     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
15783             DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
15784       return Insertion;
15785 
15786   // Handle special cases where the lower or upper half is UNDEF.
15787   if (SDValue V =
15788         lowerVectorShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
15789     return V;
15790 
15791   // Check for being able to broadcast a single element.
15792   if (SDValue Broadcast =
15793           lowerVectorShuffleAsBroadcast(DL, VT, V1, V2, Mask, Subtarget, DAG))
15794     return Broadcast;
15795 
15796   // Dispatch to each element type for lowering. If we don't have support for
15797   // specific element type shuffles at 512 bits, immediately split them and
15798   // lower them. Each lowering routine of a given type is allowed to assume that
15799   // the requisite ISA extensions for that element type are available.
15800   switch (VT.SimpleTy) {
15801   case MVT::v8f64:
15802     return lowerV8F64VectorShuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15803   case MVT::v16f32:
15804     return lowerV16F32VectorShuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15805   case MVT::v8i64:
15806     return lowerV8I64VectorShuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15807   case MVT::v16i32:
15808     return lowerV16I32VectorShuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15809   case MVT::v32i16:
15810     return lowerV32I16VectorShuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15811   case MVT::v64i8:
15812     return lowerV64I8VectorShuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15813 
15814   default:
15815     llvm_unreachable("Not a valid 512-bit x86 vector type!");
15816   }
15817 }
15818 
15819 // Determine if this shuffle can be implemented with a KSHIFT instruction.
15820 // Returns the shift amount if possible or -1 if not. This is a simplified
15821 // version of matchVectorShuffleAsShift.
match1BitShuffleAsKSHIFT(unsigned & Opcode,ArrayRef<int> Mask,int MaskOffset,const APInt & Zeroable)15822 static int match1BitShuffleAsKSHIFT(unsigned &Opcode, ArrayRef<int> Mask,
15823                                     int MaskOffset, const APInt &Zeroable) {
15824   int Size = Mask.size();
15825 
15826   auto CheckZeros = [&](int Shift, bool Left) {
15827     for (int j = 0; j < Shift; ++j)
15828       if (!Zeroable[j + (Left ? 0 : (Size - Shift))])
15829         return false;
15830 
15831     return true;
15832   };
15833 
15834   auto MatchShift = [&](int Shift, bool Left) {
15835     unsigned Pos = Left ? Shift : 0;
15836     unsigned Low = Left ? 0 : Shift;
15837     unsigned Len = Size - Shift;
15838     return isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset);
15839   };
15840 
15841   for (int Shift = 1; Shift != Size; ++Shift)
15842     for (bool Left : {true, false})
15843       if (CheckZeros(Shift, Left) && MatchShift(Shift, Left)) {
15844         Opcode = Left ? X86ISD::KSHIFTL : X86ISD::KSHIFTR;
15845         return Shift;
15846       }
15847 
15848   return -1;
15849 }
15850 
15851 
15852 // Lower vXi1 vector shuffles.
15853 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
15854 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
15855 // vector, shuffle and then truncate it back.
lower1BitVectorShuffle(const SDLoc & DL,ArrayRef<int> Mask,MVT VT,SDValue V1,SDValue V2,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)15856 static SDValue lower1BitVectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
15857                                       MVT VT, SDValue V1, SDValue V2,
15858                                       const APInt &Zeroable,
15859                                       const X86Subtarget &Subtarget,
15860                                       SelectionDAG &DAG) {
15861   assert(Subtarget.hasAVX512() &&
15862          "Cannot lower 512-bit vectors w/o basic ISA!");
15863 
15864   unsigned NumElts = Mask.size();
15865 
15866   // Try to recognize shuffles that are just padding a subvector with zeros.
15867   unsigned SubvecElts = 0;
15868   for (int i = 0; i != (int)NumElts; ++i) {
15869     if (Mask[i] >= 0 && Mask[i] != i)
15870       break;
15871 
15872     ++SubvecElts;
15873   }
15874   assert(SubvecElts != NumElts && "Identity shuffle?");
15875 
15876   // Clip to a power 2.
15877   SubvecElts = PowerOf2Floor(SubvecElts);
15878 
15879   // Make sure the number of zeroable bits in the top at least covers the bits
15880   // not covered by the subvector.
15881   if (Zeroable.countLeadingOnes() >= (NumElts - SubvecElts)) {
15882     MVT ExtractVT = MVT::getVectorVT(MVT::i1, SubvecElts);
15883     SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT,
15884                                   V1, DAG.getIntPtrConstant(0, DL));
15885     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
15886                        getZeroVector(VT, Subtarget, DAG, DL),
15887                        Extract, DAG.getIntPtrConstant(0, DL));
15888   }
15889 
15890   // Try to match KSHIFTs.
15891   // TODO: Support narrower than legal shifts by widening and extracting.
15892   if (NumElts >= 16 || (Subtarget.hasDQI() && NumElts == 8)) {
15893     unsigned Offset = 0;
15894     for (SDValue V : { V1, V2 }) {
15895       unsigned Opcode;
15896       int ShiftAmt = match1BitShuffleAsKSHIFT(Opcode, Mask, Offset, Zeroable);
15897       if (ShiftAmt >= 0)
15898         return DAG.getNode(Opcode, DL, VT, V,
15899                            DAG.getConstant(ShiftAmt, DL, MVT::i8));
15900       Offset += NumElts; // Increment for next iteration.
15901     }
15902   }
15903 
15904 
15905   MVT ExtVT;
15906   switch (VT.SimpleTy) {
15907   default:
15908     llvm_unreachable("Expected a vector of i1 elements");
15909   case MVT::v2i1:
15910     ExtVT = MVT::v2i64;
15911     break;
15912   case MVT::v4i1:
15913     ExtVT = MVT::v4i32;
15914     break;
15915   case MVT::v8i1:
15916     // Take 512-bit type, more shuffles on KNL. If we have VLX use a 256-bit
15917     // shuffle.
15918     ExtVT = Subtarget.hasVLX() ? MVT::v8i32 : MVT::v8i64;
15919     break;
15920   case MVT::v16i1:
15921     // Take 512-bit type, unless we are avoiding 512-bit types and have the
15922     // 256-bit operation available.
15923     ExtVT = Subtarget.canExtendTo512DQ() ? MVT::v16i32 : MVT::v16i16;
15924     break;
15925   case MVT::v32i1:
15926     // Take 512-bit type, unless we are avoiding 512-bit types and have the
15927     // 256-bit operation available.
15928     assert(Subtarget.hasBWI() && "Expected AVX512BW support");
15929     ExtVT = Subtarget.canExtendTo512BW() ? MVT::v32i16 : MVT::v32i8;
15930     break;
15931   case MVT::v64i1:
15932     ExtVT = MVT::v64i8;
15933     break;
15934   }
15935 
15936   V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
15937   V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
15938 
15939   SDValue Shuffle = DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask);
15940   // i1 was sign extended we can use X86ISD::CVT2MASK.
15941   int NumElems = VT.getVectorNumElements();
15942   if ((Subtarget.hasBWI() && (NumElems >= 32)) ||
15943       (Subtarget.hasDQI() && (NumElems < 32)))
15944     return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, ExtVT),
15945                        Shuffle, ISD::SETGT);
15946 
15947   return DAG.getNode(ISD::TRUNCATE, DL, VT, Shuffle);
15948 }
15949 
15950 /// Helper function that returns true if the shuffle mask should be
15951 /// commuted to improve canonicalization.
canonicalizeShuffleMaskWithCommute(ArrayRef<int> Mask)15952 static bool canonicalizeShuffleMaskWithCommute(ArrayRef<int> Mask) {
15953   int NumElements = Mask.size();
15954 
15955   int NumV1Elements = 0, NumV2Elements = 0;
15956   for (int M : Mask)
15957     if (M < 0)
15958       continue;
15959     else if (M < NumElements)
15960       ++NumV1Elements;
15961     else
15962       ++NumV2Elements;
15963 
15964   // Commute the shuffle as needed such that more elements come from V1 than
15965   // V2. This allows us to match the shuffle pattern strictly on how many
15966   // elements come from V1 without handling the symmetric cases.
15967   if (NumV2Elements > NumV1Elements)
15968     return true;
15969 
15970   assert(NumV1Elements > 0 && "No V1 indices");
15971 
15972   if (NumV2Elements == 0)
15973     return false;
15974 
15975   // When the number of V1 and V2 elements are the same, try to minimize the
15976   // number of uses of V2 in the low half of the vector. When that is tied,
15977   // ensure that the sum of indices for V1 is equal to or lower than the sum
15978   // indices for V2. When those are equal, try to ensure that the number of odd
15979   // indices for V1 is lower than the number of odd indices for V2.
15980   if (NumV1Elements == NumV2Elements) {
15981     int LowV1Elements = 0, LowV2Elements = 0;
15982     for (int M : Mask.slice(0, NumElements / 2))
15983       if (M >= NumElements)
15984         ++LowV2Elements;
15985       else if (M >= 0)
15986         ++LowV1Elements;
15987     if (LowV2Elements > LowV1Elements)
15988       return true;
15989     if (LowV2Elements == LowV1Elements) {
15990       int SumV1Indices = 0, SumV2Indices = 0;
15991       for (int i = 0, Size = Mask.size(); i < Size; ++i)
15992         if (Mask[i] >= NumElements)
15993           SumV2Indices += i;
15994         else if (Mask[i] >= 0)
15995           SumV1Indices += i;
15996       if (SumV2Indices < SumV1Indices)
15997         return true;
15998       if (SumV2Indices == SumV1Indices) {
15999         int NumV1OddIndices = 0, NumV2OddIndices = 0;
16000         for (int i = 0, Size = Mask.size(); i < Size; ++i)
16001           if (Mask[i] >= NumElements)
16002             NumV2OddIndices += i % 2;
16003           else if (Mask[i] >= 0)
16004             NumV1OddIndices += i % 2;
16005         if (NumV2OddIndices < NumV1OddIndices)
16006           return true;
16007       }
16008     }
16009   }
16010 
16011   return false;
16012 }
16013 
16014 /// Top-level lowering for x86 vector shuffles.
16015 ///
16016 /// This handles decomposition, canonicalization, and lowering of all x86
16017 /// vector shuffles. Most of the specific lowering strategies are encapsulated
16018 /// above in helper routines. The canonicalization attempts to widen shuffles
16019 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
16020 /// s.t. only one of the two inputs needs to be tested, etc.
lowerVectorShuffle(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)16021 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget &Subtarget,
16022                                   SelectionDAG &DAG) {
16023   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
16024   ArrayRef<int> Mask = SVOp->getMask();
16025   SDValue V1 = Op.getOperand(0);
16026   SDValue V2 = Op.getOperand(1);
16027   MVT VT = Op.getSimpleValueType();
16028   int NumElements = VT.getVectorNumElements();
16029   SDLoc DL(Op);
16030   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
16031 
16032   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
16033          "Can't lower MMX shuffles");
16034 
16035   bool V1IsUndef = V1.isUndef();
16036   bool V2IsUndef = V2.isUndef();
16037   if (V1IsUndef && V2IsUndef)
16038     return DAG.getUNDEF(VT);
16039 
16040   // When we create a shuffle node we put the UNDEF node to second operand,
16041   // but in some cases the first operand may be transformed to UNDEF.
16042   // In this case we should just commute the node.
16043   if (V1IsUndef)
16044     return DAG.getCommutedVectorShuffle(*SVOp);
16045 
16046   // Check for non-undef masks pointing at an undef vector and make the masks
16047   // undef as well. This makes it easier to match the shuffle based solely on
16048   // the mask.
16049   if (V2IsUndef)
16050     for (int M : Mask)
16051       if (M >= NumElements) {
16052         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
16053         for (int &M : NewMask)
16054           if (M >= NumElements)
16055             M = -1;
16056         return DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
16057       }
16058 
16059   // Check for illegal shuffle mask element index values.
16060   int MaskUpperLimit = Mask.size() * (V2IsUndef ? 1 : 2); (void)MaskUpperLimit;
16061   assert(llvm::all_of(Mask,
16062                       [&](int M) { return -1 <= M && M < MaskUpperLimit; }) &&
16063          "Out of bounds shuffle index");
16064 
16065   // We actually see shuffles that are entirely re-arrangements of a set of
16066   // zero inputs. This mostly happens while decomposing complex shuffles into
16067   // simple ones. Directly lower these as a buildvector of zeros.
16068   APInt Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
16069   if (Zeroable.isAllOnesValue())
16070     return getZeroVector(VT, Subtarget, DAG, DL);
16071 
16072   bool V2IsZero = !V2IsUndef && ISD::isBuildVectorAllZeros(V2.getNode());
16073 
16074   // Create an alternative mask with info about zeroable elements.
16075   // Here we do not set undef elements as zeroable.
16076   SmallVector<int, 64> ZeroableMask(Mask.begin(), Mask.end());
16077   if (V2IsZero) {
16078     assert(!Zeroable.isNullValue() && "V2's non-undef elements are used?!");
16079     for (int i = 0; i != NumElements; ++i)
16080       if (Mask[i] != SM_SentinelUndef && Zeroable[i])
16081         ZeroableMask[i] = SM_SentinelZero;
16082   }
16083 
16084   // Try to collapse shuffles into using a vector type with fewer elements but
16085   // wider element types. We cap this to not form integers or floating point
16086   // elements wider than 64 bits, but it might be interesting to form i128
16087   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
16088   SmallVector<int, 16> WidenedMask;
16089   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
16090       canWidenShuffleElements(ZeroableMask, WidenedMask)) {
16091     // Shuffle mask widening should not interfere with a broadcast opportunity
16092     // by obfuscating the operands with bitcasts.
16093     // TODO: Avoid lowering directly from this top-level function: make this
16094     // a query (canLowerAsBroadcast) and defer lowering to the type-based calls.
16095     if (SDValue Broadcast =
16096             lowerVectorShuffleAsBroadcast(DL, VT, V1, V2, Mask, Subtarget, DAG))
16097       return Broadcast;
16098 
16099     MVT NewEltVT = VT.isFloatingPoint()
16100                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
16101                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
16102     int NewNumElts = NumElements / 2;
16103     MVT NewVT = MVT::getVectorVT(NewEltVT, NewNumElts);
16104     // Make sure that the new vector type is legal. For example, v2f64 isn't
16105     // legal on SSE1.
16106     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
16107       if (V2IsZero) {
16108         // Modify the new Mask to take all zeros from the all-zero vector.
16109         // Choose indices that are blend-friendly.
16110         bool UsedZeroVector = false;
16111         assert(find(WidenedMask, SM_SentinelZero) != WidenedMask.end() &&
16112                "V2's non-undef elements are used?!");
16113         for (int i = 0; i != NewNumElts; ++i)
16114           if (WidenedMask[i] == SM_SentinelZero) {
16115             WidenedMask[i] = i + NewNumElts;
16116             UsedZeroVector = true;
16117           }
16118         // Ensure all elements of V2 are zero - isBuildVectorAllZeros permits
16119         // some elements to be undef.
16120         if (UsedZeroVector)
16121           V2 = getZeroVector(NewVT, Subtarget, DAG, DL);
16122       }
16123       V1 = DAG.getBitcast(NewVT, V1);
16124       V2 = DAG.getBitcast(NewVT, V2);
16125       return DAG.getBitcast(
16126           VT, DAG.getVectorShuffle(NewVT, DL, V1, V2, WidenedMask));
16127     }
16128   }
16129 
16130   // Commute the shuffle if it will improve canonicalization.
16131   if (canonicalizeShuffleMaskWithCommute(Mask))
16132     return DAG.getCommutedVectorShuffle(*SVOp);
16133 
16134   if (SDValue V =
16135           lowerVectorShuffleWithVPMOV(DL, Mask, VT, V1, V2, DAG, Subtarget))
16136     return V;
16137 
16138   // For each vector width, delegate to a specialized lowering routine.
16139   if (VT.is128BitVector())
16140     return lower128BitVectorShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget,
16141                                     DAG);
16142 
16143   if (VT.is256BitVector())
16144     return lower256BitVectorShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget,
16145                                     DAG);
16146 
16147   if (VT.is512BitVector())
16148     return lower512BitVectorShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget,
16149                                     DAG);
16150 
16151   if (Is1BitVector)
16152     return lower1BitVectorShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget,
16153                                   DAG);
16154 
16155   llvm_unreachable("Unimplemented!");
16156 }
16157 
16158 /// Try to lower a VSELECT instruction to a vector shuffle.
lowerVSELECTtoVectorShuffle(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)16159 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
16160                                            const X86Subtarget &Subtarget,
16161                                            SelectionDAG &DAG) {
16162   SDValue Cond = Op.getOperand(0);
16163   SDValue LHS = Op.getOperand(1);
16164   SDValue RHS = Op.getOperand(2);
16165   MVT VT = Op.getSimpleValueType();
16166 
16167   // Only non-legal VSELECTs reach this lowering, convert those into generic
16168   // shuffles and re-use the shuffle lowering path for blends.
16169   SmallVector<int, 32> Mask;
16170   if (createShuffleMaskFromVSELECT(Mask, Cond))
16171     return DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, Mask);
16172 
16173   return SDValue();
16174 }
16175 
LowerVSELECT(SDValue Op,SelectionDAG & DAG) const16176 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
16177   SDValue Cond = Op.getOperand(0);
16178   SDValue LHS = Op.getOperand(1);
16179   SDValue RHS = Op.getOperand(2);
16180 
16181   // A vselect where all conditions and data are constants can be optimized into
16182   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
16183   if (ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()) &&
16184       ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
16185       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
16186     return SDValue();
16187 
16188   // Try to lower this to a blend-style vector shuffle. This can handle all
16189   // constant condition cases.
16190   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
16191     return BlendOp;
16192 
16193   // If this VSELECT has a vector if i1 as a mask, it will be directly matched
16194   // with patterns on the mask registers on AVX-512.
16195   MVT CondVT = Cond.getSimpleValueType();
16196   unsigned CondEltSize = Cond.getScalarValueSizeInBits();
16197   if (CondEltSize == 1)
16198     return Op;
16199 
16200   // Variable blends are only legal from SSE4.1 onward.
16201   if (!Subtarget.hasSSE41())
16202     return SDValue();
16203 
16204   SDLoc dl(Op);
16205   MVT VT = Op.getSimpleValueType();
16206   unsigned EltSize = VT.getScalarSizeInBits();
16207   unsigned NumElts = VT.getVectorNumElements();
16208 
16209   // If the VSELECT is on a 512-bit type, we have to convert a non-i1 condition
16210   // into an i1 condition so that we can use the mask-based 512-bit blend
16211   // instructions.
16212   if (VT.getSizeInBits() == 512) {
16213     // Build a mask by testing the condition against zero.
16214     MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
16215     SDValue Mask = DAG.getSetCC(dl, MaskVT, Cond,
16216                                 DAG.getConstant(0, dl, CondVT),
16217                                 ISD::SETNE);
16218     // Now return a new VSELECT using the mask.
16219     return DAG.getSelect(dl, VT, Mask, LHS, RHS);
16220   }
16221 
16222   // SEXT/TRUNC cases where the mask doesn't match the destination size.
16223   if (CondEltSize != EltSize) {
16224     // If we don't have a sign splat, rely on the expansion.
16225     if (CondEltSize != DAG.ComputeNumSignBits(Cond))
16226       return SDValue();
16227 
16228     MVT NewCondSVT = MVT::getIntegerVT(EltSize);
16229     MVT NewCondVT = MVT::getVectorVT(NewCondSVT, NumElts);
16230     Cond = DAG.getSExtOrTrunc(Cond, dl, NewCondVT);
16231     return DAG.getNode(ISD::VSELECT, dl, VT, Cond, LHS, RHS);
16232   }
16233 
16234   // Only some types will be legal on some subtargets. If we can emit a legal
16235   // VSELECT-matching blend, return Op, and but if we need to expand, return
16236   // a null value.
16237   switch (VT.SimpleTy) {
16238   default:
16239     // Most of the vector types have blends past SSE4.1.
16240     return Op;
16241 
16242   case MVT::v32i8:
16243     // The byte blends for AVX vectors were introduced only in AVX2.
16244     if (Subtarget.hasAVX2())
16245       return Op;
16246 
16247     return SDValue();
16248 
16249   case MVT::v8i16:
16250   case MVT::v16i16: {
16251     // Bitcast everything to the vXi8 type and use a vXi8 vselect.
16252     MVT CastVT = MVT::getVectorVT(MVT::i8, NumElts * 2);
16253     Cond = DAG.getBitcast(CastVT, Cond);
16254     LHS = DAG.getBitcast(CastVT, LHS);
16255     RHS = DAG.getBitcast(CastVT, RHS);
16256     SDValue Select = DAG.getNode(ISD::VSELECT, dl, CastVT, Cond, LHS, RHS);
16257     return DAG.getBitcast(VT, Select);
16258   }
16259   }
16260 }
16261 
LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,SelectionDAG & DAG)16262 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
16263   MVT VT = Op.getSimpleValueType();
16264   SDLoc dl(Op);
16265 
16266   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
16267     return SDValue();
16268 
16269   if (VT.getSizeInBits() == 8) {
16270     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
16271                                   Op.getOperand(0), Op.getOperand(1));
16272     return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
16273   }
16274 
16275   if (VT == MVT::f32) {
16276     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
16277     // the result back to FR32 register. It's only worth matching if the
16278     // result has a single use which is a store or a bitcast to i32.  And in
16279     // the case of a store, it's not worth it if the index is a constant 0,
16280     // because a MOVSSmr can be used instead, which is smaller and faster.
16281     if (!Op.hasOneUse())
16282       return SDValue();
16283     SDNode *User = *Op.getNode()->use_begin();
16284     if ((User->getOpcode() != ISD::STORE ||
16285          isNullConstant(Op.getOperand(1))) &&
16286         (User->getOpcode() != ISD::BITCAST ||
16287          User->getValueType(0) != MVT::i32))
16288       return SDValue();
16289     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
16290                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
16291                                   Op.getOperand(1));
16292     return DAG.getBitcast(MVT::f32, Extract);
16293   }
16294 
16295   if (VT == MVT::i32 || VT == MVT::i64) {
16296     // ExtractPS/pextrq works with constant index.
16297     if (isa<ConstantSDNode>(Op.getOperand(1)))
16298       return Op;
16299   }
16300 
16301   return SDValue();
16302 }
16303 
16304 /// Extract one bit from mask vector, like v16i1 or v8i1.
16305 /// AVX-512 feature.
ExtractBitFromMaskVector(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)16306 static SDValue ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG,
16307                                         const X86Subtarget &Subtarget) {
16308   SDValue Vec = Op.getOperand(0);
16309   SDLoc dl(Vec);
16310   MVT VecVT = Vec.getSimpleValueType();
16311   SDValue Idx = Op.getOperand(1);
16312   MVT EltVT = Op.getSimpleValueType();
16313 
16314   assert((VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI()) &&
16315          "Unexpected vector type in ExtractBitFromMaskVector");
16316 
16317   // variable index can't be handled in mask registers,
16318   // extend vector to VR512/128
16319   if (!isa<ConstantSDNode>(Idx)) {
16320     unsigned NumElts = VecVT.getVectorNumElements();
16321     // Extending v8i1/v16i1 to 512-bit get better performance on KNL
16322     // than extending to 128/256bit.
16323     MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
16324     MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
16325     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec);
16326     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ExtEltVT, Ext, Idx);
16327     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
16328   }
16329 
16330   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
16331   if (IdxVal == 0) // the operation is legal
16332     return Op;
16333 
16334   // Extend to natively supported kshift.
16335   unsigned NumElems = VecVT.getVectorNumElements();
16336   MVT WideVecVT = VecVT;
16337   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8) {
16338     WideVecVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
16339     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVecVT,
16340                       DAG.getUNDEF(WideVecVT), Vec,
16341                       DAG.getIntPtrConstant(0, dl));
16342   }
16343 
16344   // Use kshiftr instruction to move to the lower element.
16345   Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideVecVT, Vec,
16346                     DAG.getConstant(IdxVal, dl, MVT::i8));
16347 
16348   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
16349                      DAG.getIntPtrConstant(0, dl));
16350 }
16351 
16352 SDValue
LowerEXTRACT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG) const16353 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
16354                                            SelectionDAG &DAG) const {
16355   SDLoc dl(Op);
16356   SDValue Vec = Op.getOperand(0);
16357   MVT VecVT = Vec.getSimpleValueType();
16358   SDValue Idx = Op.getOperand(1);
16359 
16360   if (VecVT.getVectorElementType() == MVT::i1)
16361     return ExtractBitFromMaskVector(Op, DAG, Subtarget);
16362 
16363   if (!isa<ConstantSDNode>(Idx)) {
16364     // Its more profitable to go through memory (1 cycles throughput)
16365     // than using VMOVD + VPERMV/PSHUFB sequence ( 2/3 cycles throughput)
16366     // IACA tool was used to get performance estimation
16367     // (https://software.intel.com/en-us/articles/intel-architecture-code-analyzer)
16368     //
16369     // example : extractelement <16 x i8> %a, i32 %i
16370     //
16371     // Block Throughput: 3.00 Cycles
16372     // Throughput Bottleneck: Port5
16373     //
16374     // | Num Of |   Ports pressure in cycles  |    |
16375     // |  Uops  |  0  - DV  |  5  |  6  |  7  |    |
16376     // ---------------------------------------------
16377     // |   1    |           | 1.0 |     |     | CP | vmovd xmm1, edi
16378     // |   1    |           | 1.0 |     |     | CP | vpshufb xmm0, xmm0, xmm1
16379     // |   2    | 1.0       | 1.0 |     |     | CP | vpextrb eax, xmm0, 0x0
16380     // Total Num Of Uops: 4
16381     //
16382     //
16383     // Block Throughput: 1.00 Cycles
16384     // Throughput Bottleneck: PORT2_AGU, PORT3_AGU, Port4
16385     //
16386     // |    |  Ports pressure in cycles   |  |
16387     // |Uops| 1 | 2 - D  |3 -  D  | 4 | 5 |  |
16388     // ---------------------------------------------------------
16389     // |2^  |   | 0.5    | 0.5    |1.0|   |CP| vmovaps xmmword ptr [rsp-0x18], xmm0
16390     // |1   |0.5|        |        |   |0.5|  | lea rax, ptr [rsp-0x18]
16391     // |1   |   |0.5, 0.5|0.5, 0.5|   |   |CP| mov al, byte ptr [rdi+rax*1]
16392     // Total Num Of Uops: 4
16393 
16394     return SDValue();
16395   }
16396 
16397   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
16398 
16399   // If this is a 256-bit vector result, first extract the 128-bit vector and
16400   // then extract the element from the 128-bit vector.
16401   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
16402     // Get the 128-bit vector.
16403     Vec = extract128BitVector(Vec, IdxVal, DAG, dl);
16404     MVT EltVT = VecVT.getVectorElementType();
16405 
16406     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
16407     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
16408 
16409     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
16410     // this can be done with a mask.
16411     IdxVal &= ElemsPerChunk - 1;
16412     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
16413                        DAG.getConstant(IdxVal, dl, MVT::i32));
16414   }
16415 
16416   assert(VecVT.is128BitVector() && "Unexpected vector length");
16417 
16418   MVT VT = Op.getSimpleValueType();
16419 
16420   if (VT.getSizeInBits() == 16) {
16421     // If IdxVal is 0, it's cheaper to do a move instead of a pextrw, unless
16422     // we're going to zero extend the register or fold the store (SSE41 only).
16423     if (IdxVal == 0 && !MayFoldIntoZeroExtend(Op) &&
16424         !(Subtarget.hasSSE41() && MayFoldIntoStore(Op)))
16425       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
16426                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
16427                                      DAG.getBitcast(MVT::v4i32, Vec), Idx));
16428 
16429     // Transform it so it match pextrw which produces a 32-bit result.
16430     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
16431                                   Op.getOperand(0), Op.getOperand(1));
16432     return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
16433   }
16434 
16435   if (Subtarget.hasSSE41())
16436     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
16437       return Res;
16438 
16439   // TODO: We only extract a single element from v16i8, we can probably afford
16440   // to be more aggressive here before using the default approach of spilling to
16441   // stack.
16442   if (VT.getSizeInBits() == 8 && Op->isOnlyUserOf(Vec.getNode())) {
16443     // Extract either the lowest i32 or any i16, and extract the sub-byte.
16444     int DWordIdx = IdxVal / 4;
16445     if (DWordIdx == 0) {
16446       SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
16447                                 DAG.getBitcast(MVT::v4i32, Vec),
16448                                 DAG.getIntPtrConstant(DWordIdx, dl));
16449       int ShiftVal = (IdxVal % 4) * 8;
16450       if (ShiftVal != 0)
16451         Res = DAG.getNode(ISD::SRL, dl, MVT::i32, Res,
16452                           DAG.getConstant(ShiftVal, dl, MVT::i8));
16453       return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
16454     }
16455 
16456     int WordIdx = IdxVal / 2;
16457     SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
16458                               DAG.getBitcast(MVT::v8i16, Vec),
16459                               DAG.getIntPtrConstant(WordIdx, dl));
16460     int ShiftVal = (IdxVal % 2) * 8;
16461     if (ShiftVal != 0)
16462       Res = DAG.getNode(ISD::SRL, dl, MVT::i16, Res,
16463                         DAG.getConstant(ShiftVal, dl, MVT::i8));
16464     return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
16465   }
16466 
16467   if (VT.getSizeInBits() == 32) {
16468     if (IdxVal == 0)
16469       return Op;
16470 
16471     // SHUFPS the element to the lowest double word, then movss.
16472     int Mask[4] = { static_cast<int>(IdxVal), -1, -1, -1 };
16473     Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
16474     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
16475                        DAG.getIntPtrConstant(0, dl));
16476   }
16477 
16478   if (VT.getSizeInBits() == 64) {
16479     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
16480     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
16481     //        to match extract_elt for f64.
16482     if (IdxVal == 0)
16483       return Op;
16484 
16485     // UNPCKHPD the element to the lowest double word, then movsd.
16486     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
16487     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
16488     int Mask[2] = { 1, -1 };
16489     Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
16490     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
16491                        DAG.getIntPtrConstant(0, dl));
16492   }
16493 
16494   return SDValue();
16495 }
16496 
16497 /// Insert one bit to mask vector, like v16i1 or v8i1.
16498 /// AVX-512 feature.
InsertBitToMaskVector(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)16499 static SDValue InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG,
16500                                      const X86Subtarget &Subtarget) {
16501   SDLoc dl(Op);
16502   SDValue Vec = Op.getOperand(0);
16503   SDValue Elt = Op.getOperand(1);
16504   SDValue Idx = Op.getOperand(2);
16505   MVT VecVT = Vec.getSimpleValueType();
16506 
16507   if (!isa<ConstantSDNode>(Idx)) {
16508     // Non constant index. Extend source and destination,
16509     // insert element and then truncate the result.
16510     unsigned NumElts = VecVT.getVectorNumElements();
16511     MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
16512     MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
16513     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
16514       DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec),
16515       DAG.getNode(ISD::SIGN_EXTEND, dl, ExtEltVT, Elt), Idx);
16516     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
16517   }
16518 
16519   // Copy into a k-register, extract to v1i1 and insert_subvector.
16520   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i1, Elt);
16521 
16522   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VecVT, Vec, EltInVec,
16523                      Op.getOperand(2));
16524 }
16525 
LowerINSERT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG) const16526 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
16527                                                   SelectionDAG &DAG) const {
16528   MVT VT = Op.getSimpleValueType();
16529   MVT EltVT = VT.getVectorElementType();
16530   unsigned NumElts = VT.getVectorNumElements();
16531 
16532   if (EltVT == MVT::i1)
16533     return InsertBitToMaskVector(Op, DAG, Subtarget);
16534 
16535   SDLoc dl(Op);
16536   SDValue N0 = Op.getOperand(0);
16537   SDValue N1 = Op.getOperand(1);
16538   SDValue N2 = Op.getOperand(2);
16539   if (!isa<ConstantSDNode>(N2))
16540     return SDValue();
16541   auto *N2C = cast<ConstantSDNode>(N2);
16542   unsigned IdxVal = N2C->getZExtValue();
16543 
16544   bool IsZeroElt = X86::isZeroNode(N1);
16545   bool IsAllOnesElt = VT.isInteger() && llvm::isAllOnesConstant(N1);
16546 
16547   // If we are inserting a element, see if we can do this more efficiently with
16548   // a blend shuffle with a rematerializable vector than a costly integer
16549   // insertion.
16550   if ((IsZeroElt || IsAllOnesElt) && Subtarget.hasSSE41() &&
16551       16 <= EltVT.getSizeInBits()) {
16552     SmallVector<int, 8> BlendMask;
16553     for (unsigned i = 0; i != NumElts; ++i)
16554       BlendMask.push_back(i == IdxVal ? i + NumElts : i);
16555     SDValue CstVector = IsZeroElt ? getZeroVector(VT, Subtarget, DAG, dl)
16556                                   : getOnesVector(VT, DAG, dl);
16557     return DAG.getVectorShuffle(VT, dl, N0, CstVector, BlendMask);
16558   }
16559 
16560   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
16561   // into that, and then insert the subvector back into the result.
16562   if (VT.is256BitVector() || VT.is512BitVector()) {
16563     // With a 256-bit vector, we can insert into the zero element efficiently
16564     // using a blend if we have AVX or AVX2 and the right data type.
16565     if (VT.is256BitVector() && IdxVal == 0) {
16566       // TODO: It is worthwhile to cast integer to floating point and back
16567       // and incur a domain crossing penalty if that's what we'll end up
16568       // doing anyway after extracting to a 128-bit vector.
16569       if ((Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
16570           (Subtarget.hasAVX2() && EltVT == MVT::i32)) {
16571         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
16572         N2 = DAG.getIntPtrConstant(1, dl);
16573         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
16574       }
16575     }
16576 
16577     // Get the desired 128-bit vector chunk.
16578     SDValue V = extract128BitVector(N0, IdxVal, DAG, dl);
16579 
16580     // Insert the element into the desired chunk.
16581     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
16582     assert(isPowerOf2_32(NumEltsIn128));
16583     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
16584     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
16585 
16586     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
16587                     DAG.getConstant(IdxIn128, dl, MVT::i32));
16588 
16589     // Insert the changed part back into the bigger vector
16590     return insert128BitVector(N0, V, IdxVal, DAG, dl);
16591   }
16592   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
16593 
16594   // Transform it so it match pinsr{b,w} which expects a GR32 as its second
16595   // argument. SSE41 required for pinsrb.
16596   if (VT == MVT::v8i16 || (VT == MVT::v16i8 && Subtarget.hasSSE41())) {
16597     unsigned Opc;
16598     if (VT == MVT::v8i16) {
16599       assert(Subtarget.hasSSE2() && "SSE2 required for PINSRW");
16600       Opc = X86ISD::PINSRW;
16601     } else {
16602       assert(VT == MVT::v16i8 && "PINSRB requires v16i8 vector");
16603       assert(Subtarget.hasSSE41() && "SSE41 required for PINSRB");
16604       Opc = X86ISD::PINSRB;
16605     }
16606 
16607     if (N1.getValueType() != MVT::i32)
16608       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
16609     if (N2.getValueType() != MVT::i32)
16610       N2 = DAG.getIntPtrConstant(IdxVal, dl);
16611     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
16612   }
16613 
16614   if (Subtarget.hasSSE41()) {
16615     if (EltVT == MVT::f32) {
16616       // Bits [7:6] of the constant are the source select. This will always be
16617       //   zero here. The DAG Combiner may combine an extract_elt index into
16618       //   these bits. For example (insert (extract, 3), 2) could be matched by
16619       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
16620       // Bits [5:4] of the constant are the destination select. This is the
16621       //   value of the incoming immediate.
16622       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
16623       //   combine either bitwise AND or insert of float 0.0 to set these bits.
16624 
16625       bool MinSize = DAG.getMachineFunction().getFunction().optForMinSize();
16626       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
16627         // If this is an insertion of 32-bits into the low 32-bits of
16628         // a vector, we prefer to generate a blend with immediate rather
16629         // than an insertps. Blends are simpler operations in hardware and so
16630         // will always have equal or better performance than insertps.
16631         // But if optimizing for size and there's a load folding opportunity,
16632         // generate insertps because blendps does not have a 32-bit memory
16633         // operand form.
16634         N2 = DAG.getIntPtrConstant(1, dl);
16635         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
16636         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
16637       }
16638       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
16639       // Create this as a scalar to vector..
16640       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
16641       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
16642     }
16643 
16644     // PINSR* works with constant index.
16645     if (EltVT == MVT::i32 || EltVT == MVT::i64)
16646       return Op;
16647   }
16648 
16649   return SDValue();
16650 }
16651 
LowerSCALAR_TO_VECTOR(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)16652 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, const X86Subtarget &Subtarget,
16653                                      SelectionDAG &DAG) {
16654   SDLoc dl(Op);
16655   MVT OpVT = Op.getSimpleValueType();
16656 
16657   // It's always cheaper to replace a xor+movd with xorps and simplifies further
16658   // combines.
16659   if (X86::isZeroNode(Op.getOperand(0)))
16660     return getZeroVector(OpVT, Subtarget, DAG, dl);
16661 
16662   // If this is a 256-bit vector result, first insert into a 128-bit
16663   // vector and then insert into the 256-bit vector.
16664   if (!OpVT.is128BitVector()) {
16665     // Insert into a 128-bit vector.
16666     unsigned SizeFactor = OpVT.getSizeInBits() / 128;
16667     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
16668                                  OpVT.getVectorNumElements() / SizeFactor);
16669 
16670     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
16671 
16672     // Insert the 128-bit vector.
16673     return insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
16674   }
16675   assert(OpVT.is128BitVector() && "Expected an SSE type!");
16676 
16677   // Pass through a v4i32 SCALAR_TO_VECTOR as that's what we use in tblgen.
16678   if (OpVT == MVT::v4i32)
16679     return Op;
16680 
16681   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
16682   return DAG.getBitcast(
16683       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
16684 }
16685 
16686 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
16687 // simple superregister reference or explicit instructions to insert
16688 // the upper bits of a vector.
LowerINSERT_SUBVECTOR(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)16689 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
16690                                      SelectionDAG &DAG) {
16691   assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1);
16692 
16693   return insert1BitVector(Op, DAG, Subtarget);
16694 }
16695 
LowerEXTRACT_SUBVECTOR(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)16696 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
16697                                       SelectionDAG &DAG) {
16698   assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
16699          "Only vXi1 extract_subvectors need custom lowering");
16700 
16701   SDLoc dl(Op);
16702   SDValue Vec = Op.getOperand(0);
16703   SDValue Idx = Op.getOperand(1);
16704 
16705   if (!isa<ConstantSDNode>(Idx))
16706     return SDValue();
16707 
16708   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
16709   if (IdxVal == 0) // the operation is legal
16710     return Op;
16711 
16712   MVT VecVT = Vec.getSimpleValueType();
16713   unsigned NumElems = VecVT.getVectorNumElements();
16714 
16715   // Extend to natively supported kshift.
16716   MVT WideVecVT = VecVT;
16717   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8) {
16718     WideVecVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
16719     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVecVT,
16720                       DAG.getUNDEF(WideVecVT), Vec,
16721                       DAG.getIntPtrConstant(0, dl));
16722   }
16723 
16724   // Shift to the LSB.
16725   Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideVecVT, Vec,
16726                     DAG.getConstant(IdxVal, dl, MVT::i8));
16727 
16728   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, Op.getValueType(), Vec,
16729                      DAG.getIntPtrConstant(0, dl));
16730 }
16731 
16732 // Returns the appropriate wrapper opcode for a global reference.
getGlobalWrapperKind(const GlobalValue * GV,const unsigned char OpFlags) const16733 unsigned X86TargetLowering::getGlobalWrapperKind(
16734     const GlobalValue *GV, const unsigned char OpFlags) const {
16735   // References to absolute symbols are never PC-relative.
16736   if (GV && GV->isAbsoluteSymbolRef())
16737     return X86ISD::Wrapper;
16738 
16739   CodeModel::Model M = getTargetMachine().getCodeModel();
16740   if (Subtarget.isPICStyleRIPRel() &&
16741       (M == CodeModel::Small || M == CodeModel::Kernel))
16742     return X86ISD::WrapperRIP;
16743 
16744   // GOTPCREL references must always use RIP.
16745   if (OpFlags == X86II::MO_GOTPCREL)
16746     return X86ISD::WrapperRIP;
16747 
16748   return X86ISD::Wrapper;
16749 }
16750 
16751 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
16752 // their target counterpart wrapped in the X86ISD::Wrapper node. Suppose N is
16753 // one of the above mentioned nodes. It has to be wrapped because otherwise
16754 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
16755 // be used to form addressing mode. These wrapped nodes will be selected
16756 // into MOV32ri.
16757 SDValue
LowerConstantPool(SDValue Op,SelectionDAG & DAG) const16758 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
16759   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
16760 
16761   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
16762   // global base reg.
16763   unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
16764 
16765   auto PtrVT = getPointerTy(DAG.getDataLayout());
16766   SDValue Result = DAG.getTargetConstantPool(
16767       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
16768   SDLoc DL(CP);
16769   Result = DAG.getNode(getGlobalWrapperKind(), DL, PtrVT, Result);
16770   // With PIC, the address is actually $g + Offset.
16771   if (OpFlag) {
16772     Result =
16773         DAG.getNode(ISD::ADD, DL, PtrVT,
16774                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
16775   }
16776 
16777   return Result;
16778 }
16779 
LowerJumpTable(SDValue Op,SelectionDAG & DAG) const16780 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
16781   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
16782 
16783   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
16784   // global base reg.
16785   unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
16786 
16787   auto PtrVT = getPointerTy(DAG.getDataLayout());
16788   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
16789   SDLoc DL(JT);
16790   Result = DAG.getNode(getGlobalWrapperKind(), DL, PtrVT, Result);
16791 
16792   // With PIC, the address is actually $g + Offset.
16793   if (OpFlag)
16794     Result =
16795         DAG.getNode(ISD::ADD, DL, PtrVT,
16796                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
16797 
16798   return Result;
16799 }
16800 
16801 SDValue
LowerExternalSymbol(SDValue Op,SelectionDAG & DAG) const16802 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
16803   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
16804 
16805   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
16806   // global base reg.
16807   const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
16808   unsigned char OpFlag = Subtarget.classifyGlobalReference(nullptr, *Mod);
16809 
16810   auto PtrVT = getPointerTy(DAG.getDataLayout());
16811   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
16812 
16813   SDLoc DL(Op);
16814   Result = DAG.getNode(getGlobalWrapperKind(), DL, PtrVT, Result);
16815 
16816   // With PIC, the address is actually $g + Offset.
16817   if (OpFlag) {
16818     Result =
16819         DAG.getNode(ISD::ADD, DL, PtrVT,
16820                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
16821   }
16822 
16823   // For symbols that require a load from a stub to get the address, emit the
16824   // load.
16825   if (isGlobalStubReference(OpFlag))
16826     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
16827                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
16828 
16829   return Result;
16830 }
16831 
16832 SDValue
LowerBlockAddress(SDValue Op,SelectionDAG & DAG) const16833 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
16834   // Create the TargetBlockAddressAddress node.
16835   unsigned char OpFlags =
16836     Subtarget.classifyBlockAddressReference();
16837   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
16838   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
16839   SDLoc dl(Op);
16840   auto PtrVT = getPointerTy(DAG.getDataLayout());
16841   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
16842   Result = DAG.getNode(getGlobalWrapperKind(), dl, PtrVT, Result);
16843 
16844   // With PIC, the address is actually $g + Offset.
16845   if (isGlobalRelativeToPICBase(OpFlags)) {
16846     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
16847                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
16848   }
16849 
16850   return Result;
16851 }
16852 
LowerGlobalAddress(const GlobalValue * GV,const SDLoc & dl,int64_t Offset,SelectionDAG & DAG) const16853 SDValue X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV,
16854                                               const SDLoc &dl, int64_t Offset,
16855                                               SelectionDAG &DAG) const {
16856   // Create the TargetGlobalAddress node, folding in the constant
16857   // offset if it is legal.
16858   unsigned char OpFlags = Subtarget.classifyGlobalReference(GV);
16859   CodeModel::Model M = DAG.getTarget().getCodeModel();
16860   auto PtrVT = getPointerTy(DAG.getDataLayout());
16861   SDValue Result;
16862   if (OpFlags == X86II::MO_NO_FLAG &&
16863       X86::isOffsetSuitableForCodeModel(Offset, M)) {
16864     // A direct static reference to a global.
16865     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
16866     Offset = 0;
16867   } else {
16868     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
16869   }
16870 
16871   Result = DAG.getNode(getGlobalWrapperKind(GV, OpFlags), dl, PtrVT, Result);
16872 
16873   // With PIC, the address is actually $g + Offset.
16874   if (isGlobalRelativeToPICBase(OpFlags)) {
16875     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
16876                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
16877   }
16878 
16879   // For globals that require a load from a stub to get the address, emit the
16880   // load.
16881   if (isGlobalStubReference(OpFlags))
16882     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
16883                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
16884 
16885   // If there was a non-zero offset that we didn't fold, create an explicit
16886   // addition for it.
16887   if (Offset != 0)
16888     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
16889                          DAG.getConstant(Offset, dl, PtrVT));
16890 
16891   return Result;
16892 }
16893 
16894 SDValue
LowerGlobalAddress(SDValue Op,SelectionDAG & DAG) const16895 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
16896   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
16897   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
16898   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
16899 }
16900 
16901 static SDValue
GetTLSADDR(SelectionDAG & DAG,SDValue Chain,GlobalAddressSDNode * GA,SDValue * InFlag,const EVT PtrVT,unsigned ReturnReg,unsigned char OperandFlags,bool LocalDynamic=false)16902 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
16903            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
16904            unsigned char OperandFlags, bool LocalDynamic = false) {
16905   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
16906   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
16907   SDLoc dl(GA);
16908   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
16909                                            GA->getValueType(0),
16910                                            GA->getOffset(),
16911                                            OperandFlags);
16912 
16913   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
16914                                            : X86ISD::TLSADDR;
16915 
16916   if (InFlag) {
16917     SDValue Ops[] = { Chain,  TGA, *InFlag };
16918     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
16919   } else {
16920     SDValue Ops[]  = { Chain, TGA };
16921     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
16922   }
16923 
16924   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
16925   MFI.setAdjustsStack(true);
16926   MFI.setHasCalls(true);
16927 
16928   SDValue Flag = Chain.getValue(1);
16929   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
16930 }
16931 
16932 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
16933 static SDValue
LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode * GA,SelectionDAG & DAG,const EVT PtrVT)16934 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
16935                                 const EVT PtrVT) {
16936   SDValue InFlag;
16937   SDLoc dl(GA);  // ? function entry point might be better
16938   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
16939                                    DAG.getNode(X86ISD::GlobalBaseReg,
16940                                                SDLoc(), PtrVT), InFlag);
16941   InFlag = Chain.getValue(1);
16942 
16943   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
16944 }
16945 
16946 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
16947 static SDValue
LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode * GA,SelectionDAG & DAG,const EVT PtrVT)16948 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
16949                                 const EVT PtrVT) {
16950   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
16951                     X86::RAX, X86II::MO_TLSGD);
16952 }
16953 
LowerToTLSLocalDynamicModel(GlobalAddressSDNode * GA,SelectionDAG & DAG,const EVT PtrVT,bool is64Bit)16954 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
16955                                            SelectionDAG &DAG,
16956                                            const EVT PtrVT,
16957                                            bool is64Bit) {
16958   SDLoc dl(GA);
16959 
16960   // Get the start address of the TLS block for this module.
16961   X86MachineFunctionInfo *MFI = DAG.getMachineFunction()
16962       .getInfo<X86MachineFunctionInfo>();
16963   MFI->incNumLocalDynamicTLSAccesses();
16964 
16965   SDValue Base;
16966   if (is64Bit) {
16967     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
16968                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
16969   } else {
16970     SDValue InFlag;
16971     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
16972         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
16973     InFlag = Chain.getValue(1);
16974     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
16975                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
16976   }
16977 
16978   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
16979   // of Base.
16980 
16981   // Build x@dtpoff.
16982   unsigned char OperandFlags = X86II::MO_DTPOFF;
16983   unsigned WrapperKind = X86ISD::Wrapper;
16984   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
16985                                            GA->getValueType(0),
16986                                            GA->getOffset(), OperandFlags);
16987   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
16988 
16989   // Add x@dtpoff with the base.
16990   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
16991 }
16992 
16993 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
LowerToTLSExecModel(GlobalAddressSDNode * GA,SelectionDAG & DAG,const EVT PtrVT,TLSModel::Model model,bool is64Bit,bool isPIC)16994 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
16995                                    const EVT PtrVT, TLSModel::Model model,
16996                                    bool is64Bit, bool isPIC) {
16997   SDLoc dl(GA);
16998 
16999   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
17000   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
17001                                                          is64Bit ? 257 : 256));
17002 
17003   SDValue ThreadPointer =
17004       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
17005                   MachinePointerInfo(Ptr));
17006 
17007   unsigned char OperandFlags = 0;
17008   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
17009   // initialexec.
17010   unsigned WrapperKind = X86ISD::Wrapper;
17011   if (model == TLSModel::LocalExec) {
17012     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
17013   } else if (model == TLSModel::InitialExec) {
17014     if (is64Bit) {
17015       OperandFlags = X86II::MO_GOTTPOFF;
17016       WrapperKind = X86ISD::WrapperRIP;
17017     } else {
17018       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
17019     }
17020   } else {
17021     llvm_unreachable("Unexpected model");
17022   }
17023 
17024   // emit "addl x@ntpoff,%eax" (local exec)
17025   // or "addl x@indntpoff,%eax" (initial exec)
17026   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
17027   SDValue TGA =
17028       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
17029                                  GA->getOffset(), OperandFlags);
17030   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
17031 
17032   if (model == TLSModel::InitialExec) {
17033     if (isPIC && !is64Bit) {
17034       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
17035                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
17036                            Offset);
17037     }
17038 
17039     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
17040                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
17041   }
17042 
17043   // The address of the thread local variable is the add of the thread
17044   // pointer with the offset of the variable.
17045   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
17046 }
17047 
17048 SDValue
LowerGlobalTLSAddress(SDValue Op,SelectionDAG & DAG) const17049 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
17050 
17051   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
17052 
17053   if (DAG.getTarget().useEmulatedTLS())
17054     return LowerToTLSEmulatedModel(GA, DAG);
17055 
17056   const GlobalValue *GV = GA->getGlobal();
17057   auto PtrVT = getPointerTy(DAG.getDataLayout());
17058   bool PositionIndependent = isPositionIndependent();
17059 
17060   if (Subtarget.isTargetELF()) {
17061     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
17062     switch (model) {
17063       case TLSModel::GeneralDynamic:
17064         if (Subtarget.is64Bit())
17065           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
17066         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
17067       case TLSModel::LocalDynamic:
17068         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
17069                                            Subtarget.is64Bit());
17070       case TLSModel::InitialExec:
17071       case TLSModel::LocalExec:
17072         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget.is64Bit(),
17073                                    PositionIndependent);
17074     }
17075     llvm_unreachable("Unknown TLS model.");
17076   }
17077 
17078   if (Subtarget.isTargetDarwin()) {
17079     // Darwin only has one model of TLS.  Lower to that.
17080     unsigned char OpFlag = 0;
17081     unsigned WrapperKind = Subtarget.isPICStyleRIPRel() ?
17082                            X86ISD::WrapperRIP : X86ISD::Wrapper;
17083 
17084     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
17085     // global base reg.
17086     bool PIC32 = PositionIndependent && !Subtarget.is64Bit();
17087     if (PIC32)
17088       OpFlag = X86II::MO_TLVP_PIC_BASE;
17089     else
17090       OpFlag = X86II::MO_TLVP;
17091     SDLoc DL(Op);
17092     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
17093                                                 GA->getValueType(0),
17094                                                 GA->getOffset(), OpFlag);
17095     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
17096 
17097     // With PIC32, the address is actually $g + Offset.
17098     if (PIC32)
17099       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
17100                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
17101                            Offset);
17102 
17103     // Lowering the machine isd will make sure everything is in the right
17104     // location.
17105     SDValue Chain = DAG.getEntryNode();
17106     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
17107     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
17108     SDValue Args[] = { Chain, Offset };
17109     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
17110     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
17111                                DAG.getIntPtrConstant(0, DL, true),
17112                                Chain.getValue(1), DL);
17113 
17114     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
17115     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17116     MFI.setAdjustsStack(true);
17117 
17118     // And our return value (tls address) is in the standard call return value
17119     // location.
17120     unsigned Reg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
17121     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
17122   }
17123 
17124   if (Subtarget.isTargetKnownWindowsMSVC() ||
17125       Subtarget.isTargetWindowsItanium() ||
17126       Subtarget.isTargetWindowsGNU()) {
17127     // Just use the implicit TLS architecture
17128     // Need to generate something similar to:
17129     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
17130     //                                  ; from TEB
17131     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
17132     //   mov     rcx, qword [rdx+rcx*8]
17133     //   mov     eax, .tls$:tlsvar
17134     //   [rax+rcx] contains the address
17135     // Windows 64bit: gs:0x58
17136     // Windows 32bit: fs:__tls_array
17137 
17138     SDLoc dl(GA);
17139     SDValue Chain = DAG.getEntryNode();
17140 
17141     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
17142     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
17143     // use its literal value of 0x2C.
17144     Value *Ptr = Constant::getNullValue(Subtarget.is64Bit()
17145                                         ? Type::getInt8PtrTy(*DAG.getContext(),
17146                                                              256)
17147                                         : Type::getInt32PtrTy(*DAG.getContext(),
17148                                                               257));
17149 
17150     SDValue TlsArray = Subtarget.is64Bit()
17151                            ? DAG.getIntPtrConstant(0x58, dl)
17152                            : (Subtarget.isTargetWindowsGNU()
17153                                   ? DAG.getIntPtrConstant(0x2C, dl)
17154                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
17155 
17156     SDValue ThreadPointer =
17157         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr));
17158 
17159     SDValue res;
17160     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
17161       res = ThreadPointer;
17162     } else {
17163       // Load the _tls_index variable
17164       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
17165       if (Subtarget.is64Bit())
17166         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
17167                              MachinePointerInfo(), MVT::i32);
17168       else
17169         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo());
17170 
17171       auto &DL = DAG.getDataLayout();
17172       SDValue Scale =
17173           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, MVT::i8);
17174       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
17175 
17176       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
17177     }
17178 
17179     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo());
17180 
17181     // Get the offset of start of .tls section
17182     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
17183                                              GA->getValueType(0),
17184                                              GA->getOffset(), X86II::MO_SECREL);
17185     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
17186 
17187     // The address of the thread local variable is the add of the thread
17188     // pointer with the offset of the variable.
17189     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
17190   }
17191 
17192   llvm_unreachable("TLS not implemented for this target.");
17193 }
17194 
17195 /// Lower SRA_PARTS and friends, which return two i32 values
17196 /// and take a 2 x i32 value to shift plus a shift amount.
17197 /// TODO: Can this be moved to general expansion code?
LowerShiftParts(SDValue Op,SelectionDAG & DAG)17198 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
17199   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
17200   MVT VT = Op.getSimpleValueType();
17201   unsigned VTBits = VT.getSizeInBits();
17202   SDLoc dl(Op);
17203   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
17204   SDValue ShOpLo = Op.getOperand(0);
17205   SDValue ShOpHi = Op.getOperand(1);
17206   SDValue ShAmt  = Op.getOperand(2);
17207   // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
17208   // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's optimized away
17209   // during isel.
17210   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
17211                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
17212   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
17213                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
17214                        : DAG.getConstant(0, dl, VT);
17215 
17216   SDValue Tmp2, Tmp3;
17217   if (Op.getOpcode() == ISD::SHL_PARTS) {
17218     Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
17219     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
17220   } else {
17221     Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
17222     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
17223   }
17224 
17225   // If the shift amount is larger or equal than the width of a part we can't
17226   // rely on the results of shld/shrd. Insert a test and select the appropriate
17227   // values for large shift amounts.
17228   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
17229                                 DAG.getConstant(VTBits, dl, MVT::i8));
17230   SDValue Cond = DAG.getSetCC(dl, MVT::i8, AndNode,
17231                              DAG.getConstant(0, dl, MVT::i8), ISD::SETNE);
17232 
17233   SDValue Hi, Lo;
17234   if (Op.getOpcode() == ISD::SHL_PARTS) {
17235     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
17236     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
17237   } else {
17238     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
17239     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
17240   }
17241 
17242   return DAG.getMergeValues({ Lo, Hi }, dl);
17243 }
17244 
LowerFunnelShift(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)17245 static SDValue LowerFunnelShift(SDValue Op, const X86Subtarget &Subtarget,
17246                                 SelectionDAG &DAG) {
17247   MVT VT = Op.getSimpleValueType();
17248   assert((Op.getOpcode() == ISD::FSHL || Op.getOpcode() == ISD::FSHR) &&
17249          "Unexpected funnel shift opcode!");
17250 
17251   SDLoc DL(Op);
17252   SDValue Op0 = Op.getOperand(0);
17253   SDValue Op1 = Op.getOperand(1);
17254   SDValue Amt = Op.getOperand(2);
17255 
17256   bool IsFSHR = Op.getOpcode() == ISD::FSHR;
17257 
17258   if (VT.isVector()) {
17259     assert(Subtarget.hasVBMI2() && "Expected VBMI2");
17260 
17261     if (IsFSHR)
17262       std::swap(Op0, Op1);
17263 
17264     APInt APIntShiftAmt;
17265     if (isConstantSplat(Amt, APIntShiftAmt)) {
17266       uint64_t ShiftAmt = APIntShiftAmt.getZExtValue();
17267       return DAG.getNode(IsFSHR ? X86ISD::VSHRD : X86ISD::VSHLD, DL, VT,
17268                          Op0, Op1, DAG.getConstant(ShiftAmt, DL, MVT::i8));
17269     }
17270 
17271     return DAG.getNode(IsFSHR ? X86ISD::VSHRDV : X86ISD::VSHLDV, DL, VT,
17272                        Op0, Op1, Amt);
17273   }
17274 
17275   assert((VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) &&
17276          "Unexpected funnel shift type!");
17277 
17278   // Expand slow SHLD/SHRD cases if we are not optimizing for size.
17279   bool OptForSize = DAG.getMachineFunction().getFunction().optForSize();
17280   if (!OptForSize && Subtarget.isSHLDSlow())
17281     return SDValue();
17282 
17283   if (IsFSHR)
17284     std::swap(Op0, Op1);
17285 
17286   // i16 needs to modulo the shift amount, but i32/i64 have implicit modulo.
17287   if (VT == MVT::i16)
17288     Amt = DAG.getNode(ISD::AND, DL, Amt.getValueType(), Amt,
17289                       DAG.getConstant(15, DL, Amt.getValueType()));
17290 
17291   unsigned SHDOp = (IsFSHR ? X86ISD::SHRD : X86ISD::SHLD);
17292   return DAG.getNode(SHDOp, DL, VT, Op0, Op1, Amt);
17293 }
17294 
17295 // Try to use a packed vector operation to handle i64 on 32-bit targets when
17296 // AVX512DQ is enabled.
LowerI64IntToFP_AVX512DQ(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)17297 static SDValue LowerI64IntToFP_AVX512DQ(SDValue Op, SelectionDAG &DAG,
17298                                         const X86Subtarget &Subtarget) {
17299   assert((Op.getOpcode() == ISD::SINT_TO_FP ||
17300           Op.getOpcode() == ISD::UINT_TO_FP) && "Unexpected opcode!");
17301   SDValue Src = Op.getOperand(0);
17302   MVT SrcVT = Src.getSimpleValueType();
17303   MVT VT = Op.getSimpleValueType();
17304 
17305    if (!Subtarget.hasDQI() || SrcVT != MVT::i64 || Subtarget.is64Bit() ||
17306        (VT != MVT::f32 && VT != MVT::f64))
17307     return SDValue();
17308 
17309   // Pack the i64 into a vector, do the operation and extract.
17310 
17311   // Using 256-bit to ensure result is 128-bits for f32 case.
17312   unsigned NumElts = Subtarget.hasVLX() ? 4 : 8;
17313   MVT VecInVT = MVT::getVectorVT(MVT::i64, NumElts);
17314   MVT VecVT = MVT::getVectorVT(VT, NumElts);
17315 
17316   SDLoc dl(Op);
17317   SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecInVT, Src);
17318   SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, VecVT, InVec);
17319   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
17320                      DAG.getIntPtrConstant(0, dl));
17321 }
17322 
LowerSINT_TO_FP(SDValue Op,SelectionDAG & DAG) const17323 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
17324                                            SelectionDAG &DAG) const {
17325   SDValue Src = Op.getOperand(0);
17326   MVT SrcVT = Src.getSimpleValueType();
17327   MVT VT = Op.getSimpleValueType();
17328   SDLoc dl(Op);
17329 
17330   if (SrcVT.isVector()) {
17331     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
17332       return DAG.getNode(X86ISD::CVTSI2P, dl, VT,
17333                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
17334                                      DAG.getUNDEF(SrcVT)));
17335     }
17336     return SDValue();
17337   }
17338 
17339   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
17340          "Unknown SINT_TO_FP to lower!");
17341 
17342   // These are really Legal; return the operand so the caller accepts it as
17343   // Legal.
17344   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(VT))
17345     return Op;
17346   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(VT) && Subtarget.is64Bit())
17347     return Op;
17348 
17349   if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, DAG, Subtarget))
17350     return V;
17351 
17352   SDValue ValueToStore = Op.getOperand(0);
17353   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(VT) &&
17354       !Subtarget.is64Bit())
17355     // Bitcasting to f64 here allows us to do a single 64-bit store from
17356     // an SSE register, avoiding the store forwarding penalty that would come
17357     // with two 32-bit stores.
17358     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
17359 
17360   unsigned Size = SrcVT.getSizeInBits()/8;
17361   MachineFunction &MF = DAG.getMachineFunction();
17362   auto PtrVT = getPointerTy(MF.getDataLayout());
17363   int SSFI = MF.getFrameInfo().CreateStackObject(Size, Size, false);
17364   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
17365   SDValue Chain = DAG.getStore(
17366       DAG.getEntryNode(), dl, ValueToStore, StackSlot,
17367       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI));
17368   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
17369 }
17370 
BuildFILD(SDValue Op,EVT SrcVT,SDValue Chain,SDValue StackSlot,SelectionDAG & DAG) const17371 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
17372                                      SDValue StackSlot,
17373                                      SelectionDAG &DAG) const {
17374   // Build the FILD
17375   SDLoc DL(Op);
17376   SDVTList Tys;
17377   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
17378   if (useSSE)
17379     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
17380   else
17381     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
17382 
17383   unsigned ByteSize = SrcVT.getSizeInBits()/8;
17384 
17385   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
17386   MachineMemOperand *MMO;
17387   if (FI) {
17388     int SSFI = FI->getIndex();
17389     MMO = DAG.getMachineFunction().getMachineMemOperand(
17390         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
17391         MachineMemOperand::MOLoad, ByteSize, ByteSize);
17392   } else {
17393     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
17394     StackSlot = StackSlot.getOperand(1);
17395   }
17396   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
17397   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
17398                                            X86ISD::FILD, DL,
17399                                            Tys, Ops, SrcVT, MMO);
17400 
17401   if (useSSE) {
17402     Chain = Result.getValue(1);
17403     SDValue InFlag = Result.getValue(2);
17404 
17405     // FIXME: Currently the FST is glued to the FILD_FLAG. This
17406     // shouldn't be necessary except that RFP cannot be live across
17407     // multiple blocks. When stackifier is fixed, they can be uncoupled.
17408     MachineFunction &MF = DAG.getMachineFunction();
17409     unsigned SSFISize = Op.getValueSizeInBits()/8;
17410     int SSFI = MF.getFrameInfo().CreateStackObject(SSFISize, SSFISize, false);
17411     auto PtrVT = getPointerTy(MF.getDataLayout());
17412     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
17413     Tys = DAG.getVTList(MVT::Other);
17414     SDValue Ops[] = {
17415       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
17416     };
17417     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
17418         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
17419         MachineMemOperand::MOStore, SSFISize, SSFISize);
17420 
17421     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
17422                                     Ops, Op.getValueType(), MMO);
17423     Result = DAG.getLoad(
17424         Op.getValueType(), DL, Chain, StackSlot,
17425         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI));
17426   }
17427 
17428   return Result;
17429 }
17430 
17431 /// 64-bit unsigned integer to double expansion.
LowerUINT_TO_FP_i64(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)17432 static SDValue LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG,
17433                                    const X86Subtarget &Subtarget) {
17434   // This algorithm is not obvious. Here it is what we're trying to output:
17435   /*
17436      movq       %rax,  %xmm0
17437      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
17438      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
17439      #ifdef __SSE3__
17440        haddpd   %xmm0, %xmm0
17441      #else
17442        pshufd   $0x4e, %xmm0, %xmm1
17443        addpd    %xmm1, %xmm0
17444      #endif
17445   */
17446 
17447   SDLoc dl(Op);
17448   LLVMContext *Context = DAG.getContext();
17449 
17450   // Build some magic constants.
17451   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
17452   Constant *C0 = ConstantDataVector::get(*Context, CV0);
17453   auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
17454   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
17455 
17456   SmallVector<Constant*,2> CV1;
17457   CV1.push_back(
17458     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
17459                                       APInt(64, 0x4330000000000000ULL))));
17460   CV1.push_back(
17461     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
17462                                       APInt(64, 0x4530000000000000ULL))));
17463   Constant *C1 = ConstantVector::get(CV1);
17464   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
17465 
17466   // Load the 64-bit value into an XMM register.
17467   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
17468                             Op.getOperand(0));
17469   SDValue CLod0 =
17470       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
17471                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
17472                   /* Alignment = */ 16);
17473   SDValue Unpck1 =
17474       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
17475 
17476   SDValue CLod1 =
17477       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
17478                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
17479                   /* Alignment = */ 16);
17480   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
17481   // TODO: Are there any fast-math-flags to propagate here?
17482   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
17483   SDValue Result;
17484 
17485   if (Subtarget.hasSSE3()) {
17486     // FIXME: The 'haddpd' instruction may be slower than 'shuffle + addsd'.
17487     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
17488   } else {
17489     SDValue Shuffle = DAG.getVectorShuffle(MVT::v2f64, dl, Sub, Sub, {1,-1});
17490     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuffle, Sub);
17491   }
17492 
17493   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
17494                      DAG.getIntPtrConstant(0, dl));
17495 }
17496 
17497 /// 32-bit unsigned integer to float expansion.
LowerUINT_TO_FP_i32(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)17498 static SDValue LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG,
17499                                    const X86Subtarget &Subtarget) {
17500   SDLoc dl(Op);
17501   // FP constant to bias correct the final result.
17502   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17503                                    MVT::f64);
17504 
17505   // Load the 32-bit value into an XMM register.
17506   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
17507                              Op.getOperand(0));
17508 
17509   // Zero out the upper parts of the register.
17510   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
17511 
17512   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
17513                      DAG.getBitcast(MVT::v2f64, Load),
17514                      DAG.getIntPtrConstant(0, dl));
17515 
17516   // Or the load with the bias.
17517   SDValue Or = DAG.getNode(
17518       ISD::OR, dl, MVT::v2i64,
17519       DAG.getBitcast(MVT::v2i64,
17520                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
17521       DAG.getBitcast(MVT::v2i64,
17522                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
17523   Or =
17524       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
17525                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
17526 
17527   // Subtract the bias.
17528   // TODO: Are there any fast-math-flags to propagate here?
17529   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
17530 
17531   // Handle final rounding.
17532   return DAG.getFPExtendOrRound(Sub, dl, Op.getSimpleValueType());
17533 }
17534 
lowerUINT_TO_FP_v2i32(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & DL)17535 static SDValue lowerUINT_TO_FP_v2i32(SDValue Op, SelectionDAG &DAG,
17536                                      const X86Subtarget &Subtarget,
17537                                      const SDLoc &DL) {
17538   if (Op.getSimpleValueType() != MVT::v2f64)
17539     return SDValue();
17540 
17541   SDValue N0 = Op.getOperand(0);
17542   assert(N0.getSimpleValueType() == MVT::v2i32 && "Unexpected input type");
17543 
17544   // Legalize to v4i32 type.
17545   N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
17546                    DAG.getUNDEF(MVT::v2i32));
17547 
17548   if (Subtarget.hasAVX512())
17549     return DAG.getNode(X86ISD::CVTUI2P, DL, MVT::v2f64, N0);
17550 
17551   // Same implementation as VectorLegalizer::ExpandUINT_TO_FLOAT,
17552   // but using v2i32 to v2f64 with X86ISD::CVTSI2P.
17553   SDValue HalfWord = DAG.getConstant(16, DL, MVT::v4i32);
17554   SDValue HalfWordMask = DAG.getConstant(0x0000FFFF, DL, MVT::v4i32);
17555 
17556   // Two to the power of half-word-size.
17557   SDValue TWOHW = DAG.getConstantFP(1 << 16, DL, MVT::v2f64);
17558 
17559   // Clear upper part of LO, lower HI.
17560   SDValue HI = DAG.getNode(ISD::SRL, DL, MVT::v4i32, N0, HalfWord);
17561   SDValue LO = DAG.getNode(ISD::AND, DL, MVT::v4i32, N0, HalfWordMask);
17562 
17563   SDValue fHI = DAG.getNode(X86ISD::CVTSI2P, DL, MVT::v2f64, HI);
17564           fHI = DAG.getNode(ISD::FMUL, DL, MVT::v2f64, fHI, TWOHW);
17565   SDValue fLO = DAG.getNode(X86ISD::CVTSI2P, DL, MVT::v2f64, LO);
17566 
17567   // Add the two halves.
17568   return DAG.getNode(ISD::FADD, DL, MVT::v2f64, fHI, fLO);
17569 }
17570 
lowerUINT_TO_FP_vXi32(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)17571 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
17572                                      const X86Subtarget &Subtarget) {
17573   // The algorithm is the following:
17574   // #ifdef __SSE4_1__
17575   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
17576   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
17577   //                                 (uint4) 0x53000000, 0xaa);
17578   // #else
17579   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
17580   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
17581   // #endif
17582   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
17583   //     return (float4) lo + fhi;
17584 
17585   // We shouldn't use it when unsafe-fp-math is enabled though: we might later
17586   // reassociate the two FADDs, and if we do that, the algorithm fails
17587   // spectacularly (PR24512).
17588   // FIXME: If we ever have some kind of Machine FMF, this should be marked
17589   // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
17590   // there's also the MachineCombiner reassociations happening on Machine IR.
17591   if (DAG.getTarget().Options.UnsafeFPMath)
17592     return SDValue();
17593 
17594   SDLoc DL(Op);
17595   SDValue V = Op->getOperand(0);
17596   MVT VecIntVT = V.getSimpleValueType();
17597   bool Is128 = VecIntVT == MVT::v4i32;
17598   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
17599   // If we convert to something else than the supported type, e.g., to v4f64,
17600   // abort early.
17601   if (VecFloatVT != Op->getSimpleValueType(0))
17602     return SDValue();
17603 
17604   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
17605          "Unsupported custom type");
17606 
17607   // In the #idef/#else code, we have in common:
17608   // - The vector of constants:
17609   // -- 0x4b000000
17610   // -- 0x53000000
17611   // - A shift:
17612   // -- v >> 16
17613 
17614   // Create the splat vector for 0x4b000000.
17615   SDValue VecCstLow = DAG.getConstant(0x4b000000, DL, VecIntVT);
17616   // Create the splat vector for 0x53000000.
17617   SDValue VecCstHigh = DAG.getConstant(0x53000000, DL, VecIntVT);
17618 
17619   // Create the right shift.
17620   SDValue VecCstShift = DAG.getConstant(16, DL, VecIntVT);
17621   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
17622 
17623   SDValue Low, High;
17624   if (Subtarget.hasSSE41()) {
17625     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
17626     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
17627     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
17628     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
17629     // Low will be bitcasted right away, so do not bother bitcasting back to its
17630     // original type.
17631     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
17632                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
17633     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
17634     //                                 (uint4) 0x53000000, 0xaa);
17635     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
17636     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
17637     // High will be bitcasted right away, so do not bother bitcasting back to
17638     // its original type.
17639     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
17640                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
17641   } else {
17642     SDValue VecCstMask = DAG.getConstant(0xffff, DL, VecIntVT);
17643     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
17644     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
17645     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
17646 
17647     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
17648     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
17649   }
17650 
17651   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
17652   SDValue VecCstFAdd = DAG.getConstantFP(
17653       APFloat(APFloat::IEEEsingle(), APInt(32, 0xD3000080)), DL, VecFloatVT);
17654 
17655   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
17656   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
17657   // TODO: Are there any fast-math-flags to propagate here?
17658   SDValue FHigh =
17659       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
17660   //     return (float4) lo + fhi;
17661   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
17662   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
17663 }
17664 
lowerUINT_TO_FP_vec(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)17665 static SDValue lowerUINT_TO_FP_vec(SDValue Op, SelectionDAG &DAG,
17666                                    const X86Subtarget &Subtarget) {
17667   SDValue N0 = Op.getOperand(0);
17668   MVT SrcVT = N0.getSimpleValueType();
17669   SDLoc dl(Op);
17670 
17671   switch (SrcVT.SimpleTy) {
17672   default:
17673     llvm_unreachable("Custom UINT_TO_FP is not supported!");
17674   case MVT::v2i32:
17675     return lowerUINT_TO_FP_v2i32(Op, DAG, Subtarget, dl);
17676   case MVT::v4i32:
17677   case MVT::v8i32:
17678     assert(!Subtarget.hasAVX512());
17679     return lowerUINT_TO_FP_vXi32(Op, DAG, Subtarget);
17680   }
17681 }
17682 
LowerUINT_TO_FP(SDValue Op,SelectionDAG & DAG) const17683 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
17684                                            SelectionDAG &DAG) const {
17685   SDValue N0 = Op.getOperand(0);
17686   SDLoc dl(Op);
17687   auto PtrVT = getPointerTy(DAG.getDataLayout());
17688 
17689   if (Op.getSimpleValueType().isVector())
17690     return lowerUINT_TO_FP_vec(Op, DAG, Subtarget);
17691 
17692   MVT SrcVT = N0.getSimpleValueType();
17693   MVT DstVT = Op.getSimpleValueType();
17694 
17695   if (Subtarget.hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
17696       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget.is64Bit()))) {
17697     // Conversions from unsigned i32 to f32/f64 are legal,
17698     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
17699     return Op;
17700   }
17701 
17702   if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, DAG, Subtarget))
17703     return V;
17704 
17705   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
17706     return LowerUINT_TO_FP_i64(Op, DAG, Subtarget);
17707   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
17708     return LowerUINT_TO_FP_i32(Op, DAG, Subtarget);
17709   if (Subtarget.is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
17710     return SDValue();
17711 
17712   // Make a 64-bit buffer, and use it to build an FILD.
17713   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
17714   if (SrcVT == MVT::i32) {
17715     SDValue OffsetSlot = DAG.getMemBasePlusOffset(StackSlot, 4, dl);
17716     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
17717                                   StackSlot, MachinePointerInfo());
17718     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
17719                                   OffsetSlot, MachinePointerInfo());
17720     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
17721     return Fild;
17722   }
17723 
17724   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
17725   SDValue ValueToStore = Op.getOperand(0);
17726   if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget.is64Bit())
17727     // Bitcasting to f64 here allows us to do a single 64-bit store from
17728     // an SSE register, avoiding the store forwarding penalty that would come
17729     // with two 32-bit stores.
17730     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
17731   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, ValueToStore, StackSlot,
17732                                MachinePointerInfo());
17733   // For i64 source, we need to add the appropriate power of 2 if the input
17734   // was negative.  This is the same as the optimization in
17735   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
17736   // we must be careful to do the computation in x87 extended precision, not
17737   // in SSE. (The generic code can't know it's OK to do this, or how to.)
17738   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
17739   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
17740       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
17741       MachineMemOperand::MOLoad, 8, 8);
17742 
17743   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
17744   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
17745   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
17746                                          MVT::i64, MMO);
17747 
17748   APInt FF(32, 0x5F800000ULL);
17749 
17750   // Check whether the sign bit is set.
17751   SDValue SignSet = DAG.getSetCC(
17752       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
17753       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
17754 
17755   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
17756   SDValue FudgePtr = DAG.getConstantPool(
17757       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
17758 
17759   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
17760   SDValue Zero = DAG.getIntPtrConstant(0, dl);
17761   SDValue Four = DAG.getIntPtrConstant(4, dl);
17762   SDValue Offset = DAG.getSelect(dl, Zero.getValueType(), SignSet, Zero, Four);
17763   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
17764 
17765   // Load the value out, extending it from f32 to f80.
17766   // FIXME: Avoid the extend by constructing the right constant pool?
17767   SDValue Fudge = DAG.getExtLoad(
17768       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
17769       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
17770       /* Alignment = */ 4);
17771   // Extend everything to 80 bits to force it to be done on x87.
17772   // TODO: Are there any fast-math-flags to propagate here?
17773   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
17774   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
17775                      DAG.getIntPtrConstant(0, dl));
17776 }
17777 
17778 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
17779 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
17780 // just return an <SDValue(), SDValue()> pair.
17781 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
17782 // to i16, i32 or i64, and we lower it to a legal sequence.
17783 // If lowered to the final integer result we return a <result, SDValue()> pair.
17784 // Otherwise we lower it to a sequence ending with a FIST, return a
17785 // <FIST, StackSlot> pair, and the caller is responsible for loading
17786 // the final integer result from StackSlot.
17787 std::pair<SDValue,SDValue>
FP_TO_INTHelper(SDValue Op,SelectionDAG & DAG,bool IsSigned,bool IsReplace) const17788 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
17789                                    bool IsSigned, bool IsReplace) const {
17790   SDLoc DL(Op);
17791 
17792   EVT DstTy = Op.getValueType();
17793   EVT TheVT = Op.getOperand(0).getValueType();
17794   auto PtrVT = getPointerTy(DAG.getDataLayout());
17795 
17796   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
17797     // f16 must be promoted before using the lowering in this routine.
17798     // fp128 does not use this lowering.
17799     return std::make_pair(SDValue(), SDValue());
17800   }
17801 
17802   // If using FIST to compute an unsigned i64, we'll need some fixup
17803   // to handle values above the maximum signed i64.  A FIST is always
17804   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
17805   bool UnsignedFixup = !IsSigned &&
17806                        DstTy == MVT::i64 &&
17807                        (!Subtarget.is64Bit() ||
17808                         !isScalarFPTypeInSSEReg(TheVT));
17809 
17810   if (!IsSigned && DstTy != MVT::i64 && !Subtarget.hasAVX512()) {
17811     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
17812     // The low 32 bits of the fist result will have the correct uint32 result.
17813     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
17814     DstTy = MVT::i64;
17815   }
17816 
17817   assert(DstTy.getSimpleVT() <= MVT::i64 &&
17818          DstTy.getSimpleVT() >= MVT::i16 &&
17819          "Unknown FP_TO_INT to lower!");
17820 
17821   // These are really Legal.
17822   if (DstTy == MVT::i32 &&
17823       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
17824     return std::make_pair(SDValue(), SDValue());
17825   if (Subtarget.is64Bit() &&
17826       DstTy == MVT::i64 &&
17827       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
17828     return std::make_pair(SDValue(), SDValue());
17829 
17830   // We lower FP->int64 into FISTP64 followed by a load from a temporary
17831   // stack slot.
17832   MachineFunction &MF = DAG.getMachineFunction();
17833   unsigned MemSize = DstTy.getSizeInBits()/8;
17834   int SSFI = MF.getFrameInfo().CreateStackObject(MemSize, MemSize, false);
17835   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
17836 
17837   unsigned Opc;
17838   switch (DstTy.getSimpleVT().SimpleTy) {
17839   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
17840   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
17841   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
17842   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
17843   }
17844 
17845   SDValue Chain = DAG.getEntryNode();
17846   SDValue Value = Op.getOperand(0);
17847   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
17848 
17849   if (UnsignedFixup) {
17850     //
17851     // Conversion to unsigned i64 is implemented with a select,
17852     // depending on whether the source value fits in the range
17853     // of a signed i64.  Let Thresh be the FP equivalent of
17854     // 0x8000000000000000ULL.
17855     //
17856     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
17857     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
17858     //  Fist-to-mem64 FistSrc
17859     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
17860     //  to XOR'ing the high 32 bits with Adjust.
17861     //
17862     // Being a power of 2, Thresh is exactly representable in all FP formats.
17863     // For X87 we'd like to use the smallest FP type for this constant, but
17864     // for DAG type consistency we have to match the FP operand type.
17865 
17866     APFloat Thresh(APFloat::IEEEsingle(), APInt(32, 0x5f000000));
17867     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
17868     bool LosesInfo = false;
17869     if (TheVT == MVT::f64)
17870       // The rounding mode is irrelevant as the conversion should be exact.
17871       Status = Thresh.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
17872                               &LosesInfo);
17873     else if (TheVT == MVT::f80)
17874       Status = Thresh.convert(APFloat::x87DoubleExtended(),
17875                               APFloat::rmNearestTiesToEven, &LosesInfo);
17876 
17877     assert(Status == APFloat::opOK && !LosesInfo &&
17878            "FP conversion should have been exact");
17879 
17880     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
17881 
17882     SDValue Cmp = DAG.getSetCC(DL,
17883                                getSetCCResultType(DAG.getDataLayout(),
17884                                                   *DAG.getContext(), TheVT),
17885                                Value, ThreshVal, ISD::SETLT);
17886     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
17887                            DAG.getConstant(0, DL, MVT::i32),
17888                            DAG.getConstant(0x80000000, DL, MVT::i32));
17889     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
17890     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
17891                                               *DAG.getContext(), TheVT),
17892                        Value, ThreshVal, ISD::SETLT);
17893     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
17894   }
17895 
17896   // FIXME This causes a redundant load/store if the SSE-class value is already
17897   // in memory, such as if it is on the callstack.
17898   if (isScalarFPTypeInSSEReg(TheVT)) {
17899     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
17900     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
17901                          MachinePointerInfo::getFixedStack(MF, SSFI));
17902     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
17903     SDValue Ops[] = {
17904       Chain, StackSlot, DAG.getValueType(TheVT)
17905     };
17906 
17907     MachineMemOperand *MMO =
17908         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17909                                 MachineMemOperand::MOLoad, MemSize, MemSize);
17910     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
17911     Chain = Value.getValue(1);
17912     SSFI = MF.getFrameInfo().CreateStackObject(MemSize, MemSize, false);
17913     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
17914   }
17915 
17916   MachineMemOperand *MMO =
17917       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17918                               MachineMemOperand::MOStore, MemSize, MemSize);
17919 
17920   if (UnsignedFixup) {
17921 
17922     // Insert the FIST, load its result as two i32's,
17923     // and XOR the high i32 with Adjust.
17924 
17925     SDValue FistOps[] = { Chain, Value, StackSlot };
17926     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
17927                                            FistOps, DstTy, MMO);
17928 
17929     SDValue Low32 =
17930         DAG.getLoad(MVT::i32, DL, FIST, StackSlot, MachinePointerInfo());
17931     SDValue HighAddr = DAG.getMemBasePlusOffset(StackSlot, 4, DL);
17932 
17933     SDValue High32 =
17934         DAG.getLoad(MVT::i32, DL, FIST, HighAddr, MachinePointerInfo());
17935     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
17936 
17937     if (Subtarget.is64Bit()) {
17938       // Join High32 and Low32 into a 64-bit result.
17939       // (High32 << 32) | Low32
17940       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
17941       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
17942       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
17943                            DAG.getConstant(32, DL, MVT::i8));
17944       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
17945       return std::make_pair(Result, SDValue());
17946     }
17947 
17948     SDValue ResultOps[] = { Low32, High32 };
17949 
17950     SDValue pair = IsReplace
17951       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
17952       : DAG.getMergeValues(ResultOps, DL);
17953     return std::make_pair(pair, SDValue());
17954   } else {
17955     // Build the FP_TO_INT*_IN_MEM
17956     SDValue Ops[] = { Chain, Value, StackSlot };
17957     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
17958                                            Ops, DstTy, MMO);
17959     return std::make_pair(FIST, StackSlot);
17960   }
17961 }
17962 
LowerAVXExtend(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)17963 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
17964                               const X86Subtarget &Subtarget) {
17965   MVT VT = Op->getSimpleValueType(0);
17966   SDValue In = Op->getOperand(0);
17967   MVT InVT = In.getSimpleValueType();
17968   SDLoc dl(Op);
17969 
17970   assert(VT.isVector() && InVT.isVector() && "Expected vector type");
17971   assert(VT.getVectorNumElements() == VT.getVectorNumElements() &&
17972          "Expected same number of elements");
17973   assert((VT.getVectorElementType() == MVT::i16 ||
17974           VT.getVectorElementType() == MVT::i32 ||
17975           VT.getVectorElementType() == MVT::i64) &&
17976          "Unexpected element type");
17977   assert((InVT.getVectorElementType() == MVT::i8 ||
17978           InVT.getVectorElementType() == MVT::i16 ||
17979           InVT.getVectorElementType() == MVT::i32) &&
17980          "Unexpected element type");
17981 
17982   // Custom legalize v8i8->v8i64 on CPUs without avx512bw.
17983   if (InVT == MVT::v8i8) {
17984     if (!ExperimentalVectorWideningLegalization || VT != MVT::v8i64)
17985       return SDValue();
17986 
17987     In = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op),
17988                      MVT::v16i8, In, DAG.getUNDEF(MVT::v8i8));
17989     // FIXME: This should be ANY_EXTEND_VECTOR_INREG for ANY_EXTEND input.
17990     return DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, dl, VT, In);
17991   }
17992 
17993   if (Subtarget.hasInt256())
17994     return Op;
17995 
17996   // Optimize vectors in AVX mode:
17997   //
17998   //   v8i16 -> v8i32
17999   //   Use vpmovzwd for 4 lower elements  v8i16 -> v4i32.
18000   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
18001   //   Concat upper and lower parts.
18002   //
18003   //   v4i32 -> v4i64
18004   //   Use vpmovzdq for 4 lower elements  v4i32 -> v2i64.
18005   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
18006   //   Concat upper and lower parts.
18007   //
18008 
18009   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
18010                                 VT.getVectorNumElements() / 2);
18011 
18012   SDValue OpLo = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, dl, HalfVT, In);
18013 
18014   SDValue ZeroVec = DAG.getConstant(0, dl, InVT);
18015   SDValue Undef = DAG.getUNDEF(InVT);
18016   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
18017   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
18018   OpHi = DAG.getBitcast(HalfVT, OpHi);
18019 
18020   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
18021 }
18022 
18023 // Helper to split and extend a v16i1 mask to v16i8 or v16i16.
SplitAndExtendv16i1(unsigned ExtOpc,MVT VT,SDValue In,const SDLoc & dl,SelectionDAG & DAG)18024 static SDValue SplitAndExtendv16i1(unsigned ExtOpc, MVT VT, SDValue In,
18025                                    const SDLoc &dl, SelectionDAG &DAG) {
18026   assert((VT == MVT::v16i8 || VT == MVT::v16i16) && "Unexpected VT.");
18027   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
18028                            DAG.getIntPtrConstant(0, dl));
18029   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
18030                            DAG.getIntPtrConstant(8, dl));
18031   Lo = DAG.getNode(ExtOpc, dl, MVT::v8i16, Lo);
18032   Hi = DAG.getNode(ExtOpc, dl, MVT::v8i16, Hi);
18033   SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i16, Lo, Hi);
18034   return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
18035 }
18036 
LowerZERO_EXTEND_Mask(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)18037 static  SDValue LowerZERO_EXTEND_Mask(SDValue Op,
18038                                       const X86Subtarget &Subtarget,
18039                                       SelectionDAG &DAG) {
18040   MVT VT = Op->getSimpleValueType(0);
18041   SDValue In = Op->getOperand(0);
18042   MVT InVT = In.getSimpleValueType();
18043   assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!");
18044   SDLoc DL(Op);
18045   unsigned NumElts = VT.getVectorNumElements();
18046 
18047   // For all vectors, but vXi8 we can just emit a sign_extend and a shift. This
18048   // avoids a constant pool load.
18049   if (VT.getVectorElementType() != MVT::i8) {
18050     SDValue Extend = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, In);
18051     return DAG.getNode(ISD::SRL, DL, VT, Extend,
18052                        DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
18053   }
18054 
18055   // Extend VT if BWI is not supported.
18056   MVT ExtVT = VT;
18057   if (!Subtarget.hasBWI()) {
18058     // If v16i32 is to be avoided, we'll need to split and concatenate.
18059     if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
18060       return SplitAndExtendv16i1(ISD::ZERO_EXTEND, VT, In, DL, DAG);
18061 
18062     ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
18063   }
18064 
18065   // Widen to 512-bits if VLX is not supported.
18066   MVT WideVT = ExtVT;
18067   if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
18068     NumElts *= 512 / ExtVT.getSizeInBits();
18069     InVT = MVT::getVectorVT(MVT::i1, NumElts);
18070     In = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT, DAG.getUNDEF(InVT),
18071                      In, DAG.getIntPtrConstant(0, DL));
18072     WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(),
18073                               NumElts);
18074   }
18075 
18076   SDValue One = DAG.getConstant(1, DL, WideVT);
18077   SDValue Zero = DAG.getConstant(0, DL, WideVT);
18078 
18079   SDValue SelectedVal = DAG.getSelect(DL, WideVT, In, One, Zero);
18080 
18081   // Truncate if we had to extend above.
18082   if (VT != ExtVT) {
18083     WideVT = MVT::getVectorVT(MVT::i8, NumElts);
18084     SelectedVal = DAG.getNode(ISD::TRUNCATE, DL, WideVT, SelectedVal);
18085   }
18086 
18087   // Extract back to 128/256-bit if we widened.
18088   if (WideVT != VT)
18089     SelectedVal = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SelectedVal,
18090                               DAG.getIntPtrConstant(0, DL));
18091 
18092   return SelectedVal;
18093 }
18094 
LowerZERO_EXTEND(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)18095 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
18096                                 SelectionDAG &DAG) {
18097   SDValue In = Op.getOperand(0);
18098   MVT SVT = In.getSimpleValueType();
18099 
18100   if (SVT.getVectorElementType() == MVT::i1)
18101     return LowerZERO_EXTEND_Mask(Op, Subtarget, DAG);
18102 
18103   assert(Subtarget.hasAVX() && "Expected AVX support");
18104   return LowerAVXExtend(Op, DAG, Subtarget);
18105 }
18106 
18107 /// Helper to recursively truncate vector elements in half with PACKSS/PACKUS.
18108 /// It makes use of the fact that vectors with enough leading sign/zero bits
18109 /// prevent the PACKSS/PACKUS from saturating the results.
18110 /// AVX2 (Int256) sub-targets require extra shuffling as the PACK*S operates
18111 /// within each 128-bit lane.
truncateVectorWithPACK(unsigned Opcode,EVT DstVT,SDValue In,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)18112 static SDValue truncateVectorWithPACK(unsigned Opcode, EVT DstVT, SDValue In,
18113                                       const SDLoc &DL, SelectionDAG &DAG,
18114                                       const X86Subtarget &Subtarget) {
18115   assert((Opcode == X86ISD::PACKSS || Opcode == X86ISD::PACKUS) &&
18116          "Unexpected PACK opcode");
18117   assert(DstVT.isVector() && "VT not a vector?");
18118 
18119   // Requires SSE2 but AVX512 has fast vector truncate.
18120   if (!Subtarget.hasSSE2())
18121     return SDValue();
18122 
18123   EVT SrcVT = In.getValueType();
18124 
18125   // No truncation required, we might get here due to recursive calls.
18126   if (SrcVT == DstVT)
18127     return In;
18128 
18129   // We only support vector truncation to 64bits or greater from a
18130   // 128bits or greater source.
18131   unsigned DstSizeInBits = DstVT.getSizeInBits();
18132   unsigned SrcSizeInBits = SrcVT.getSizeInBits();
18133   if ((DstSizeInBits % 64) != 0 || (SrcSizeInBits % 128) != 0)
18134     return SDValue();
18135 
18136   unsigned NumElems = SrcVT.getVectorNumElements();
18137   if (!isPowerOf2_32(NumElems))
18138     return SDValue();
18139 
18140   LLVMContext &Ctx = *DAG.getContext();
18141   assert(DstVT.getVectorNumElements() == NumElems && "Illegal truncation");
18142   assert(SrcSizeInBits > DstSizeInBits && "Illegal truncation");
18143 
18144   EVT PackedSVT = EVT::getIntegerVT(Ctx, SrcVT.getScalarSizeInBits() / 2);
18145 
18146   // Pack to the largest type possible:
18147   // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
18148   EVT InVT = MVT::i16, OutVT = MVT::i8;
18149   if (SrcVT.getScalarSizeInBits() > 16 &&
18150       (Opcode == X86ISD::PACKSS || Subtarget.hasSSE41())) {
18151     InVT = MVT::i32;
18152     OutVT = MVT::i16;
18153   }
18154 
18155   // 128bit -> 64bit truncate - PACK 128-bit src in the lower subvector.
18156   if (SrcVT.is128BitVector()) {
18157     InVT = EVT::getVectorVT(Ctx, InVT, 128 / InVT.getSizeInBits());
18158     OutVT = EVT::getVectorVT(Ctx, OutVT, 128 / OutVT.getSizeInBits());
18159     In = DAG.getBitcast(InVT, In);
18160     SDValue Res = DAG.getNode(Opcode, DL, OutVT, In, In);
18161     Res = extractSubVector(Res, 0, DAG, DL, 64);
18162     return DAG.getBitcast(DstVT, Res);
18163   }
18164 
18165   // Extract lower/upper subvectors.
18166   unsigned NumSubElts = NumElems / 2;
18167   SDValue Lo = extractSubVector(In, 0 * NumSubElts, DAG, DL, SrcSizeInBits / 2);
18168   SDValue Hi = extractSubVector(In, 1 * NumSubElts, DAG, DL, SrcSizeInBits / 2);
18169 
18170   unsigned SubSizeInBits = SrcSizeInBits / 2;
18171   InVT = EVT::getVectorVT(Ctx, InVT, SubSizeInBits / InVT.getSizeInBits());
18172   OutVT = EVT::getVectorVT(Ctx, OutVT, SubSizeInBits / OutVT.getSizeInBits());
18173 
18174   // 256bit -> 128bit truncate - PACK lower/upper 128-bit subvectors.
18175   if (SrcVT.is256BitVector() && DstVT.is128BitVector()) {
18176     Lo = DAG.getBitcast(InVT, Lo);
18177     Hi = DAG.getBitcast(InVT, Hi);
18178     SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
18179     return DAG.getBitcast(DstVT, Res);
18180   }
18181 
18182   // AVX2: 512bit -> 256bit truncate - PACK lower/upper 256-bit subvectors.
18183   // AVX2: 512bit -> 128bit truncate - PACK(PACK, PACK).
18184   if (SrcVT.is512BitVector() && Subtarget.hasInt256()) {
18185     Lo = DAG.getBitcast(InVT, Lo);
18186     Hi = DAG.getBitcast(InVT, Hi);
18187     SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
18188 
18189     // 256-bit PACK(ARG0, ARG1) leaves us with ((LO0,LO1),(HI0,HI1)),
18190     // so we need to shuffle to get ((LO0,HI0),(LO1,HI1)).
18191     Res = DAG.getBitcast(MVT::v4i64, Res);
18192     Res = DAG.getVectorShuffle(MVT::v4i64, DL, Res, Res, {0, 2, 1, 3});
18193 
18194     if (DstVT.is256BitVector())
18195       return DAG.getBitcast(DstVT, Res);
18196 
18197     // If 512bit -> 128bit truncate another stage.
18198     EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
18199     Res = DAG.getBitcast(PackedVT, Res);
18200     return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
18201   }
18202 
18203   // Recursively pack lower/upper subvectors, concat result and pack again.
18204   assert(SrcSizeInBits >= 256 && "Expected 256-bit vector or greater");
18205   EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumSubElts);
18206   Lo = truncateVectorWithPACK(Opcode, PackedVT, Lo, DL, DAG, Subtarget);
18207   Hi = truncateVectorWithPACK(Opcode, PackedVT, Hi, DL, DAG, Subtarget);
18208 
18209   PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
18210   SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, PackedVT, Lo, Hi);
18211   return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
18212 }
18213 
LowerTruncateVecI1(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)18214 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
18215                                   const X86Subtarget &Subtarget) {
18216 
18217   SDLoc DL(Op);
18218   MVT VT = Op.getSimpleValueType();
18219   SDValue In = Op.getOperand(0);
18220   MVT InVT = In.getSimpleValueType();
18221 
18222   assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type.");
18223 
18224   // Shift LSB to MSB and use VPMOVB/W2M or TESTD/Q.
18225   unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
18226   if (InVT.getScalarSizeInBits() <= 16) {
18227     if (Subtarget.hasBWI()) {
18228       // legal, will go to VPMOVB2M, VPMOVW2M
18229       if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
18230         // We need to shift to get the lsb into sign position.
18231         // Shift packed bytes not supported natively, bitcast to word
18232         MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
18233         In = DAG.getNode(ISD::SHL, DL, ExtVT,
18234                          DAG.getBitcast(ExtVT, In),
18235                          DAG.getConstant(ShiftInx, DL, ExtVT));
18236         In = DAG.getBitcast(InVT, In);
18237       }
18238       return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT),
18239                           In, ISD::SETGT);
18240     }
18241     // Use TESTD/Q, extended vector to packed dword/qword.
18242     assert((InVT.is256BitVector() || InVT.is128BitVector()) &&
18243            "Unexpected vector type.");
18244     unsigned NumElts = InVT.getVectorNumElements();
18245     assert((NumElts == 8 || NumElts == 16) && "Unexpected number of elements");
18246     // We need to change to a wider element type that we have support for.
18247     // For 8 element vectors this is easy, we either extend to v8i32 or v8i64.
18248     // For 16 element vectors we extend to v16i32 unless we are explicitly
18249     // trying to avoid 512-bit vectors. If we are avoiding 512-bit vectors
18250     // we need to split into two 8 element vectors which we can extend to v8i32,
18251     // truncate and concat the results. There's an additional complication if
18252     // the original type is v16i8. In that case we can't split the v16i8 so
18253     // first we pre-extend it to v16i16 which we can split to v8i16, then extend
18254     // to v8i32, truncate that to v8i1 and concat the two halves.
18255     if (NumElts == 16 && !Subtarget.canExtendTo512DQ()) {
18256       if (InVT == MVT::v16i8) {
18257         // First we need to sign extend up to 256-bits so we can split that.
18258         InVT = MVT::v16i16;
18259         In = DAG.getNode(ISD::SIGN_EXTEND, DL, InVT, In);
18260       }
18261       SDValue Lo = extract128BitVector(In, 0, DAG, DL);
18262       SDValue Hi = extract128BitVector(In, 8, DAG, DL);
18263       // We're split now, just emit two truncates and a concat. The two
18264       // truncates will trigger legalization to come back to this function.
18265       Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Lo);
18266       Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Hi);
18267       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
18268     }
18269     // We either have 8 elements or we're allowed to use 512-bit vectors.
18270     // If we have VLX, we want to use the narrowest vector that can get the
18271     // job done so we use vXi32.
18272     MVT EltVT = Subtarget.hasVLX() ? MVT::i32 : MVT::getIntegerVT(512/NumElts);
18273     MVT ExtVT = MVT::getVectorVT(EltVT, NumElts);
18274     In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
18275     InVT = ExtVT;
18276     ShiftInx = InVT.getScalarSizeInBits() - 1;
18277   }
18278 
18279   if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
18280     // We need to shift to get the lsb into sign position.
18281     In = DAG.getNode(ISD::SHL, DL, InVT, In,
18282                      DAG.getConstant(ShiftInx, DL, InVT));
18283   }
18284   // If we have DQI, emit a pattern that will be iseled as vpmovq2m/vpmovd2m.
18285   if (Subtarget.hasDQI())
18286     return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT), In, ISD::SETGT);
18287   return DAG.getSetCC(DL, VT, In, DAG.getConstant(0, DL, InVT), ISD::SETNE);
18288 }
18289 
LowerTRUNCATE(SDValue Op,SelectionDAG & DAG) const18290 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
18291   SDLoc DL(Op);
18292   MVT VT = Op.getSimpleValueType();
18293   SDValue In = Op.getOperand(0);
18294   MVT InVT = In.getSimpleValueType();
18295   unsigned InNumEltBits = InVT.getScalarSizeInBits();
18296 
18297   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
18298          "Invalid TRUNCATE operation");
18299 
18300   // If called by the legalizer just return.
18301   if (!DAG.getTargetLoweringInfo().isTypeLegal(InVT))
18302     return SDValue();
18303 
18304   if (VT.getVectorElementType() == MVT::i1)
18305     return LowerTruncateVecI1(Op, DAG, Subtarget);
18306 
18307   // vpmovqb/w/d, vpmovdb/w, vpmovwb
18308   if (Subtarget.hasAVX512()) {
18309     // word to byte only under BWI. Otherwise we have to promoted to v16i32
18310     // and then truncate that. But we should only do that if we haven't been
18311     // asked to avoid 512-bit vectors. The actual promotion to v16i32 will be
18312     // handled by isel patterns.
18313     if (InVT != MVT::v16i16 || Subtarget.hasBWI() ||
18314         Subtarget.canExtendTo512DQ())
18315       return Op;
18316   }
18317 
18318   unsigned NumPackedSignBits = std::min<unsigned>(VT.getScalarSizeInBits(), 16);
18319   unsigned NumPackedZeroBits = Subtarget.hasSSE41() ? NumPackedSignBits : 8;
18320 
18321   // Truncate with PACKUS if we are truncating a vector with leading zero bits
18322   // that extend all the way to the packed/truncated value.
18323   // Pre-SSE41 we can only use PACKUSWB.
18324   KnownBits Known = DAG.computeKnownBits(In);
18325   if ((InNumEltBits - NumPackedZeroBits) <= Known.countMinLeadingZeros())
18326     if (SDValue V =
18327             truncateVectorWithPACK(X86ISD::PACKUS, VT, In, DL, DAG, Subtarget))
18328       return V;
18329 
18330   // Truncate with PACKSS if we are truncating a vector with sign-bits that
18331   // extend all the way to the packed/truncated value.
18332   if ((InNumEltBits - NumPackedSignBits) < DAG.ComputeNumSignBits(In))
18333     if (SDValue V =
18334             truncateVectorWithPACK(X86ISD::PACKSS, VT, In, DL, DAG, Subtarget))
18335       return V;
18336 
18337   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
18338     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
18339     if (Subtarget.hasInt256()) {
18340       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
18341       In = DAG.getBitcast(MVT::v8i32, In);
18342       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, In, ShufMask);
18343       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
18344                          DAG.getIntPtrConstant(0, DL));
18345     }
18346 
18347     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
18348                                DAG.getIntPtrConstant(0, DL));
18349     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
18350                                DAG.getIntPtrConstant(2, DL));
18351     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
18352     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
18353     static const int ShufMask[] = {0, 2, 4, 6};
18354     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
18355   }
18356 
18357   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
18358     // On AVX2, v8i32 -> v8i16 becomes PSHUFB.
18359     if (Subtarget.hasInt256()) {
18360       In = DAG.getBitcast(MVT::v32i8, In);
18361 
18362       // The PSHUFB mask:
18363       static const int ShufMask1[] = { 0,  1,  4,  5,  8,  9, 12, 13,
18364                                       -1, -1, -1, -1, -1, -1, -1, -1,
18365                                       16, 17, 20, 21, 24, 25, 28, 29,
18366                                       -1, -1, -1, -1, -1, -1, -1, -1 };
18367       In = DAG.getVectorShuffle(MVT::v32i8, DL, In, In, ShufMask1);
18368       In = DAG.getBitcast(MVT::v4i64, In);
18369 
18370       static const int ShufMask2[] = {0,  2,  -1,  -1};
18371       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, In, ShufMask2);
18372       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
18373                        DAG.getIntPtrConstant(0, DL));
18374       return DAG.getBitcast(VT, In);
18375     }
18376 
18377     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
18378                                DAG.getIntPtrConstant(0, DL));
18379 
18380     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
18381                                DAG.getIntPtrConstant(4, DL));
18382 
18383     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
18384     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
18385 
18386     // The PSHUFB mask:
18387     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
18388                                    -1, -1, -1, -1, -1, -1, -1, -1};
18389 
18390     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, OpLo, ShufMask1);
18391     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, OpHi, ShufMask1);
18392 
18393     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
18394     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
18395 
18396     // The MOVLHPS Mask:
18397     static const int ShufMask2[] = {0, 1, 4, 5};
18398     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
18399     return DAG.getBitcast(MVT::v8i16, res);
18400   }
18401 
18402   if (VT == MVT::v16i8 && InVT == MVT::v16i16) {
18403     // Use an AND to zero uppper bits for PACKUS.
18404     In = DAG.getNode(ISD::AND, DL, InVT, In, DAG.getConstant(255, DL, InVT));
18405 
18406     SDValue InLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i16, In,
18407                                DAG.getIntPtrConstant(0, DL));
18408     SDValue InHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i16, In,
18409                                DAG.getIntPtrConstant(8, DL));
18410     return DAG.getNode(X86ISD::PACKUS, DL, VT, InLo, InHi);
18411   }
18412 
18413   // Handle truncation of V256 to V128 using shuffles.
18414   assert(VT.is128BitVector() && InVT.is256BitVector() && "Unexpected types!");
18415 
18416   assert(Subtarget.hasAVX() && "256-bit vector without AVX!");
18417 
18418   unsigned NumElems = VT.getVectorNumElements();
18419   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
18420 
18421   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
18422   // Prepare truncation shuffle mask
18423   for (unsigned i = 0; i != NumElems; ++i)
18424     MaskVec[i] = i * 2;
18425   In = DAG.getBitcast(NVT, In);
18426   SDValue V = DAG.getVectorShuffle(NVT, DL, In, In, MaskVec);
18427   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
18428                      DAG.getIntPtrConstant(0, DL));
18429 }
18430 
LowerFP_TO_INT(SDValue Op,SelectionDAG & DAG) const18431 SDValue X86TargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
18432   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT;
18433   MVT VT = Op.getSimpleValueType();
18434 
18435   if (VT.isVector()) {
18436     SDValue Src = Op.getOperand(0);
18437     SDLoc dl(Op);
18438 
18439     if (VT == MVT::v2i1 && Src.getSimpleValueType() == MVT::v2f64) {
18440       MVT ResVT = MVT::v4i32;
18441       MVT TruncVT = MVT::v4i1;
18442       unsigned Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
18443       if (!IsSigned && !Subtarget.hasVLX()) {
18444         // Widen to 512-bits.
18445         ResVT = MVT::v8i32;
18446         TruncVT = MVT::v8i1;
18447         Opc = ISD::FP_TO_UINT;
18448         Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8f64,
18449                           DAG.getUNDEF(MVT::v8f64),
18450                           Src, DAG.getIntPtrConstant(0, dl));
18451       }
18452       SDValue Res = DAG.getNode(Opc, dl, ResVT, Src);
18453       Res = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Res);
18454       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i1, Res,
18455                          DAG.getIntPtrConstant(0, dl));
18456     }
18457 
18458     assert(Subtarget.hasDQI() && Subtarget.hasVLX() && "Requires AVX512DQVL!");
18459     if (VT == MVT::v2i64 && Src.getSimpleValueType() == MVT::v2f32) {
18460       return DAG.getNode(IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI, dl, VT,
18461                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
18462                                      DAG.getUNDEF(MVT::v2f32)));
18463     }
18464 
18465     return SDValue();
18466   }
18467 
18468   assert(!VT.isVector());
18469 
18470   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
18471     IsSigned, /*IsReplace=*/ false);
18472   SDValue FIST = Vals.first, StackSlot = Vals.second;
18473   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
18474   if (!FIST.getNode())
18475     return Op;
18476 
18477   if (StackSlot.getNode())
18478     // Load the result.
18479     return DAG.getLoad(VT, SDLoc(Op), FIST, StackSlot, MachinePointerInfo());
18480 
18481   // The node is the result.
18482   return FIST;
18483 }
18484 
LowerFP_EXTEND(SDValue Op,SelectionDAG & DAG)18485 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
18486   SDLoc DL(Op);
18487   MVT VT = Op.getSimpleValueType();
18488   SDValue In = Op.getOperand(0);
18489   MVT SVT = In.getSimpleValueType();
18490 
18491   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
18492 
18493   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
18494                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
18495                                  In, DAG.getUNDEF(SVT)));
18496 }
18497 
18498 /// Horizontal vector math instructions may be slower than normal math with
18499 /// shuffles. Limit horizontal op codegen based on size/speed trade-offs, uarch
18500 /// implementation, and likely shuffle complexity of the alternate sequence.
shouldUseHorizontalOp(bool IsSingleSource,SelectionDAG & DAG,const X86Subtarget & Subtarget)18501 static bool shouldUseHorizontalOp(bool IsSingleSource, SelectionDAG &DAG,
18502                                   const X86Subtarget &Subtarget) {
18503   bool IsOptimizingSize = DAG.getMachineFunction().getFunction().optForSize();
18504   bool HasFastHOps = Subtarget.hasFastHorizontalOps();
18505   return !IsSingleSource || IsOptimizingSize || HasFastHOps;
18506 }
18507 
18508 /// Depending on uarch and/or optimizing for size, we might prefer to use a
18509 /// vector operation in place of the typical scalar operation.
lowerAddSubToHorizontalOp(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)18510 static SDValue lowerAddSubToHorizontalOp(SDValue Op, SelectionDAG &DAG,
18511                                          const X86Subtarget &Subtarget) {
18512   // If both operands have other uses, this is probably not profitable.
18513   SDValue LHS = Op.getOperand(0);
18514   SDValue RHS = Op.getOperand(1);
18515   if (!LHS.hasOneUse() && !RHS.hasOneUse())
18516     return Op;
18517 
18518   // FP horizontal add/sub were added with SSE3. Integer with SSSE3.
18519   bool IsFP = Op.getSimpleValueType().isFloatingPoint();
18520   if (IsFP && !Subtarget.hasSSE3())
18521     return Op;
18522   if (!IsFP && !Subtarget.hasSSSE3())
18523     return Op;
18524 
18525   // Defer forming the minimal horizontal op if the vector source has more than
18526   // the 2 extract element uses that we're matching here. In that case, we might
18527   // form a horizontal op that includes more than 1 add/sub op.
18528   if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
18529       RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
18530       LHS.getOperand(0) != RHS.getOperand(0) ||
18531       !LHS.getOperand(0)->hasNUsesOfValue(2, 0))
18532     return Op;
18533 
18534   if (!isa<ConstantSDNode>(LHS.getOperand(1)) ||
18535       !isa<ConstantSDNode>(RHS.getOperand(1)) ||
18536       !shouldUseHorizontalOp(true, DAG, Subtarget))
18537     return Op;
18538 
18539   // Allow commuted 'hadd' ops.
18540   // TODO: Allow commuted (f)sub by negating the result of (F)HSUB?
18541   unsigned HOpcode;
18542   switch (Op.getOpcode()) {
18543     case ISD::ADD: HOpcode = X86ISD::HADD; break;
18544     case ISD::SUB: HOpcode = X86ISD::HSUB; break;
18545     case ISD::FADD: HOpcode = X86ISD::FHADD; break;
18546     case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
18547     default:
18548       llvm_unreachable("Trying to lower unsupported opcode to horizontal op");
18549   }
18550   unsigned LExtIndex = LHS.getConstantOperandVal(1);
18551   unsigned RExtIndex = RHS.getConstantOperandVal(1);
18552   if (LExtIndex == 1 && RExtIndex == 0 &&
18553       (HOpcode == X86ISD::HADD || HOpcode == X86ISD::FHADD))
18554     std::swap(LExtIndex, RExtIndex);
18555 
18556   // TODO: This can be extended to handle other adjacent extract pairs.
18557   if (LExtIndex != 0 || RExtIndex != 1)
18558     return Op;
18559 
18560   SDValue X = LHS.getOperand(0);
18561   EVT VecVT = X.getValueType();
18562   unsigned BitWidth = VecVT.getSizeInBits();
18563   assert((BitWidth == 128 || BitWidth == 256 || BitWidth == 512) &&
18564          "Not expecting illegal vector widths here");
18565 
18566   // Creating a 256-bit horizontal op would be wasteful, and there is no 512-bit
18567   // equivalent, so extract the 256/512-bit source op to 128-bit.
18568   // This is free: ymm/zmm -> xmm.
18569   SDLoc DL(Op);
18570   if (BitWidth == 256 || BitWidth == 512)
18571     X = extract128BitVector(X, 0, DAG, DL);
18572 
18573   // add (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hadd X, X), 0
18574   // add (extractelt (X, 1), extractelt (X, 0)) --> extractelt (hadd X, X), 0
18575   // sub (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hsub X, X), 0
18576   SDValue HOp = DAG.getNode(HOpcode, DL, X.getValueType(), X, X);
18577   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, Op.getSimpleValueType(), HOp,
18578                      DAG.getIntPtrConstant(0, DL));
18579 }
18580 
18581 /// Depending on uarch and/or optimizing for size, we might prefer to use a
18582 /// vector operation in place of the typical scalar operation.
lowerFaddFsub(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)18583 static SDValue lowerFaddFsub(SDValue Op, SelectionDAG &DAG,
18584                              const X86Subtarget &Subtarget) {
18585   assert((Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::f64) &&
18586          "Only expecting float/double");
18587   return lowerAddSubToHorizontalOp(Op, DAG, Subtarget);
18588 }
18589 
18590 /// The only differences between FABS and FNEG are the mask and the logic op.
18591 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
LowerFABSorFNEG(SDValue Op,SelectionDAG & DAG)18592 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
18593   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
18594          "Wrong opcode for lowering FABS or FNEG.");
18595 
18596   bool IsFABS = (Op.getOpcode() == ISD::FABS);
18597 
18598   // If this is a FABS and it has an FNEG user, bail out to fold the combination
18599   // into an FNABS. We'll lower the FABS after that if it is still in use.
18600   if (IsFABS)
18601     for (SDNode *User : Op->uses())
18602       if (User->getOpcode() == ISD::FNEG)
18603         return Op;
18604 
18605   SDLoc dl(Op);
18606   MVT VT = Op.getSimpleValueType();
18607 
18608   bool IsF128 = (VT == MVT::f128);
18609   assert((VT == MVT::f64 || VT == MVT::f32 || VT == MVT::f128 ||
18610           VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
18611           VT == MVT::v8f32 || VT == MVT::v8f64 || VT == MVT::v16f32) &&
18612          "Unexpected type in LowerFABSorFNEG");
18613 
18614   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
18615   // decide if we should generate a 16-byte constant mask when we only need 4 or
18616   // 8 bytes for the scalar case.
18617 
18618   // There are no scalar bitwise logical SSE/AVX instructions, so we
18619   // generate a 16-byte vector constant and logic op even for the scalar case.
18620   // Using a 16-byte mask allows folding the load of the mask with
18621   // the logic op, so it can save (~4 bytes) on code size.
18622   bool IsFakeVector = !VT.isVector() && !IsF128;
18623   MVT LogicVT = VT;
18624   if (IsFakeVector)
18625     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
18626 
18627   unsigned EltBits = VT.getScalarSizeInBits();
18628   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
18629   APInt MaskElt = IsFABS ? APInt::getSignedMaxValue(EltBits) :
18630                            APInt::getSignMask(EltBits);
18631   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
18632   SDValue Mask = DAG.getConstantFP(APFloat(Sem, MaskElt), dl, LogicVT);
18633 
18634   SDValue Op0 = Op.getOperand(0);
18635   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
18636   unsigned LogicOp = IsFABS  ? X86ISD::FAND :
18637                      IsFNABS ? X86ISD::FOR  :
18638                                X86ISD::FXOR;
18639   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
18640 
18641   if (VT.isVector() || IsF128)
18642     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
18643 
18644   // For the scalar case extend to a 128-bit vector, perform the logic op,
18645   // and extract the scalar result back out.
18646   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
18647   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
18648   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
18649                      DAG.getIntPtrConstant(0, dl));
18650 }
18651 
LowerFCOPYSIGN(SDValue Op,SelectionDAG & DAG)18652 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
18653   SDValue Mag = Op.getOperand(0);
18654   SDValue Sign = Op.getOperand(1);
18655   SDLoc dl(Op);
18656 
18657   // If the sign operand is smaller, extend it first.
18658   MVT VT = Op.getSimpleValueType();
18659   if (Sign.getSimpleValueType().bitsLT(VT))
18660     Sign = DAG.getNode(ISD::FP_EXTEND, dl, VT, Sign);
18661 
18662   // And if it is bigger, shrink it first.
18663   if (Sign.getSimpleValueType().bitsGT(VT))
18664     Sign = DAG.getNode(ISD::FP_ROUND, dl, VT, Sign, DAG.getIntPtrConstant(1, dl));
18665 
18666   // At this point the operands and the result should have the same
18667   // type, and that won't be f80 since that is not custom lowered.
18668   bool IsF128 = (VT == MVT::f128);
18669   assert((VT == MVT::f64 || VT == MVT::f32 || VT == MVT::f128 ||
18670           VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
18671           VT == MVT::v8f32 || VT == MVT::v8f64 || VT == MVT::v16f32) &&
18672          "Unexpected type in LowerFCOPYSIGN");
18673 
18674   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
18675 
18676   // Perform all scalar logic operations as 16-byte vectors because there are no
18677   // scalar FP logic instructions in SSE.
18678   // TODO: This isn't necessary. If we used scalar types, we might avoid some
18679   // unnecessary splats, but we might miss load folding opportunities. Should
18680   // this decision be based on OptimizeForSize?
18681   bool IsFakeVector = !VT.isVector() && !IsF128;
18682   MVT LogicVT = VT;
18683   if (IsFakeVector)
18684     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
18685 
18686   // The mask constants are automatically splatted for vector types.
18687   unsigned EltSizeInBits = VT.getScalarSizeInBits();
18688   SDValue SignMask = DAG.getConstantFP(
18689       APFloat(Sem, APInt::getSignMask(EltSizeInBits)), dl, LogicVT);
18690   SDValue MagMask = DAG.getConstantFP(
18691       APFloat(Sem, APInt::getSignedMaxValue(EltSizeInBits)), dl, LogicVT);
18692 
18693   // First, clear all bits but the sign bit from the second operand (sign).
18694   if (IsFakeVector)
18695     Sign = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Sign);
18696   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Sign, SignMask);
18697 
18698   // Next, clear the sign bit from the first operand (magnitude).
18699   // TODO: If we had general constant folding for FP logic ops, this check
18700   // wouldn't be necessary.
18701   SDValue MagBits;
18702   if (ConstantFPSDNode *Op0CN = isConstOrConstSplatFP(Mag)) {
18703     APFloat APF = Op0CN->getValueAPF();
18704     APF.clearSign();
18705     MagBits = DAG.getConstantFP(APF, dl, LogicVT);
18706   } else {
18707     // If the magnitude operand wasn't a constant, we need to AND out the sign.
18708     if (IsFakeVector)
18709       Mag = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Mag);
18710     MagBits = DAG.getNode(X86ISD::FAND, dl, LogicVT, Mag, MagMask);
18711   }
18712 
18713   // OR the magnitude value with the sign bit.
18714   SDValue Or = DAG.getNode(X86ISD::FOR, dl, LogicVT, MagBits, SignBit);
18715   return !IsFakeVector ? Or : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Or,
18716                                           DAG.getIntPtrConstant(0, dl));
18717 }
18718 
LowerFGETSIGN(SDValue Op,SelectionDAG & DAG)18719 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
18720   SDValue N0 = Op.getOperand(0);
18721   SDLoc dl(Op);
18722   MVT VT = Op.getSimpleValueType();
18723 
18724   MVT OpVT = N0.getSimpleValueType();
18725   assert((OpVT == MVT::f32 || OpVT == MVT::f64) &&
18726          "Unexpected type for FGETSIGN");
18727 
18728   // Lower ISD::FGETSIGN to (AND (X86ISD::MOVMSK ...) 1).
18729   MVT VecVT = (OpVT == MVT::f32 ? MVT::v4f32 : MVT::v2f64);
18730   SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, N0);
18731   Res = DAG.getNode(X86ISD::MOVMSK, dl, MVT::i32, Res);
18732   Res = DAG.getZExtOrTrunc(Res, dl, VT);
18733   Res = DAG.getNode(ISD::AND, dl, VT, Res, DAG.getConstant(1, dl, VT));
18734   return Res;
18735 }
18736 
18737 /// Helper for creating a X86ISD::SETCC node.
getSETCC(X86::CondCode Cond,SDValue EFLAGS,const SDLoc & dl,SelectionDAG & DAG)18738 static SDValue getSETCC(X86::CondCode Cond, SDValue EFLAGS, const SDLoc &dl,
18739                         SelectionDAG &DAG) {
18740   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18741                      DAG.getConstant(Cond, dl, MVT::i8), EFLAGS);
18742 }
18743 
18744 // Check whether an OR'd tree is PTEST-able.
LowerVectorAllZeroTest(SDValue Op,ISD::CondCode CC,const X86Subtarget & Subtarget,SelectionDAG & DAG,SDValue & X86CC)18745 static SDValue LowerVectorAllZeroTest(SDValue Op, ISD::CondCode CC,
18746                                       const X86Subtarget &Subtarget,
18747                                       SelectionDAG &DAG,
18748                                       SDValue &X86CC) {
18749   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
18750 
18751   if (!Subtarget.hasSSE41())
18752     return SDValue();
18753 
18754   if (!Op->hasOneUse())
18755     return SDValue();
18756 
18757   SDNode *N = Op.getNode();
18758   SDLoc DL(N);
18759 
18760   SmallVector<SDValue, 8> Opnds;
18761   DenseMap<SDValue, unsigned> VecInMap;
18762   SmallVector<SDValue, 8> VecIns;
18763   EVT VT = MVT::Other;
18764 
18765   // Recognize a special case where a vector is casted into wide integer to
18766   // test all 0s.
18767   Opnds.push_back(N->getOperand(0));
18768   Opnds.push_back(N->getOperand(1));
18769 
18770   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
18771     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
18772     // BFS traverse all OR'd operands.
18773     if (I->getOpcode() == ISD::OR) {
18774       Opnds.push_back(I->getOperand(0));
18775       Opnds.push_back(I->getOperand(1));
18776       // Re-evaluate the number of nodes to be traversed.
18777       e += 2; // 2 more nodes (LHS and RHS) are pushed.
18778       continue;
18779     }
18780 
18781     // Quit if a non-EXTRACT_VECTOR_ELT
18782     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
18783       return SDValue();
18784 
18785     // Quit if without a constant index.
18786     SDValue Idx = I->getOperand(1);
18787     if (!isa<ConstantSDNode>(Idx))
18788       return SDValue();
18789 
18790     SDValue ExtractedFromVec = I->getOperand(0);
18791     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
18792     if (M == VecInMap.end()) {
18793       VT = ExtractedFromVec.getValueType();
18794       // Quit if not 128/256-bit vector.
18795       if (!VT.is128BitVector() && !VT.is256BitVector())
18796         return SDValue();
18797       // Quit if not the same type.
18798       if (VecInMap.begin() != VecInMap.end() &&
18799           VT != VecInMap.begin()->first.getValueType())
18800         return SDValue();
18801       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
18802       VecIns.push_back(ExtractedFromVec);
18803     }
18804     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
18805   }
18806 
18807   assert((VT.is128BitVector() || VT.is256BitVector()) &&
18808          "Not extracted from 128-/256-bit vector.");
18809 
18810   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
18811 
18812   for (DenseMap<SDValue, unsigned>::const_iterator
18813         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
18814     // Quit if not all elements are used.
18815     if (I->second != FullMask)
18816       return SDValue();
18817   }
18818 
18819   MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
18820 
18821   // Cast all vectors into TestVT for PTEST.
18822   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
18823     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
18824 
18825   // If more than one full vector is evaluated, OR them first before PTEST.
18826   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
18827     // Each iteration will OR 2 nodes and append the result until there is only
18828     // 1 node left, i.e. the final OR'd value of all vectors.
18829     SDValue LHS = VecIns[Slot];
18830     SDValue RHS = VecIns[Slot + 1];
18831     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
18832   }
18833 
18834   X86CC = DAG.getConstant(CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE,
18835                           DL, MVT::i8);
18836   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
18837                      VecIns.back(), VecIns.back());
18838 }
18839 
18840 /// return true if \c Op has a use that doesn't just read flags.
hasNonFlagsUse(SDValue Op)18841 static bool hasNonFlagsUse(SDValue Op) {
18842   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
18843        ++UI) {
18844     SDNode *User = *UI;
18845     unsigned UOpNo = UI.getOperandNo();
18846     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
18847       // Look pass truncate.
18848       UOpNo = User->use_begin().getOperandNo();
18849       User = *User->use_begin();
18850     }
18851 
18852     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
18853         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
18854       return true;
18855   }
18856   return false;
18857 }
18858 
18859 /// Emit nodes that will be selected as "test Op0,Op0", or something
18860 /// equivalent.
EmitTest(SDValue Op,unsigned X86CC,const SDLoc & dl,SelectionDAG & DAG,const X86Subtarget & Subtarget)18861 static SDValue EmitTest(SDValue Op, unsigned X86CC, const SDLoc &dl,
18862                         SelectionDAG &DAG, const X86Subtarget &Subtarget) {
18863   // CF and OF aren't always set the way we want. Determine which
18864   // of these we need.
18865   bool NeedCF = false;
18866   bool NeedOF = false;
18867   switch (X86CC) {
18868   default: break;
18869   case X86::COND_A: case X86::COND_AE:
18870   case X86::COND_B: case X86::COND_BE:
18871     NeedCF = true;
18872     break;
18873   case X86::COND_G: case X86::COND_GE:
18874   case X86::COND_L: case X86::COND_LE:
18875   case X86::COND_O: case X86::COND_NO: {
18876     // Check if we really need to set the
18877     // Overflow flag. If NoSignedWrap is present
18878     // that is not actually needed.
18879     switch (Op->getOpcode()) {
18880     case ISD::ADD:
18881     case ISD::SUB:
18882     case ISD::MUL:
18883     case ISD::SHL:
18884       if (Op.getNode()->getFlags().hasNoSignedWrap())
18885         break;
18886       LLVM_FALLTHROUGH;
18887     default:
18888       NeedOF = true;
18889       break;
18890     }
18891     break;
18892   }
18893   }
18894   // See if we can use the EFLAGS value from the operand instead of
18895   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
18896   // we prove that the arithmetic won't overflow, we can't use OF or CF.
18897   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
18898     // Emit a CMP with 0, which is the TEST pattern.
18899     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
18900                        DAG.getConstant(0, dl, Op.getValueType()));
18901   }
18902   unsigned Opcode = 0;
18903   unsigned NumOperands = 0;
18904 
18905   SDValue ArithOp = Op;
18906 
18907   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
18908   // which may be the result of a CAST.  We use the variable 'Op', which is the
18909   // non-casted variable when we check for possible users.
18910   switch (ArithOp.getOpcode()) {
18911   case ISD::AND:
18912     // If the primary 'and' result isn't used, don't bother using X86ISD::AND,
18913     // because a TEST instruction will be better.
18914     if (!hasNonFlagsUse(Op))
18915       break;
18916 
18917     LLVM_FALLTHROUGH;
18918   case ISD::ADD:
18919   case ISD::SUB:
18920   case ISD::OR:
18921   case ISD::XOR:
18922     // Transform to an x86-specific ALU node with flags if there is a chance of
18923     // using an RMW op or only the flags are used. Otherwise, leave
18924     // the node alone and emit a 'test' instruction.
18925     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
18926            UE = Op.getNode()->use_end(); UI != UE; ++UI)
18927       if (UI->getOpcode() != ISD::CopyToReg &&
18928           UI->getOpcode() != ISD::SETCC &&
18929           UI->getOpcode() != ISD::STORE)
18930         goto default_case;
18931 
18932     // Otherwise use a regular EFLAGS-setting instruction.
18933     switch (ArithOp.getOpcode()) {
18934     default: llvm_unreachable("unexpected operator!");
18935     case ISD::ADD: Opcode = X86ISD::ADD; break;
18936     case ISD::SUB: Opcode = X86ISD::SUB; break;
18937     case ISD::XOR: Opcode = X86ISD::XOR; break;
18938     case ISD::AND: Opcode = X86ISD::AND; break;
18939     case ISD::OR:  Opcode = X86ISD::OR;  break;
18940     }
18941 
18942     NumOperands = 2;
18943     break;
18944   case X86ISD::ADD:
18945   case X86ISD::SUB:
18946   case X86ISD::OR:
18947   case X86ISD::XOR:
18948   case X86ISD::AND:
18949     return SDValue(Op.getNode(), 1);
18950   default:
18951   default_case:
18952     break;
18953   }
18954 
18955   if (Opcode == 0) {
18956     // Emit a CMP with 0, which is the TEST pattern.
18957     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
18958                        DAG.getConstant(0, dl, Op.getValueType()));
18959   }
18960   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
18961   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
18962 
18963   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
18964   DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), New);
18965   return SDValue(New.getNode(), 1);
18966 }
18967 
18968 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
18969 /// equivalent.
EmitCmp(SDValue Op0,SDValue Op1,unsigned X86CC,const SDLoc & dl,SelectionDAG & DAG) const18970 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
18971                                    const SDLoc &dl, SelectionDAG &DAG) const {
18972   if (isNullConstant(Op1))
18973     return EmitTest(Op0, X86CC, dl, DAG, Subtarget);
18974 
18975   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
18976        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
18977     // Only promote the compare up to I32 if it is a 16 bit operation
18978     // with an immediate.  16 bit immediates are to be avoided.
18979     if (Op0.getValueType() == MVT::i16 &&
18980         ((isa<ConstantSDNode>(Op0) &&
18981           !cast<ConstantSDNode>(Op0)->getAPIntValue().isSignedIntN(8)) ||
18982          (isa<ConstantSDNode>(Op1) &&
18983           !cast<ConstantSDNode>(Op1)->getAPIntValue().isSignedIntN(8))) &&
18984         !DAG.getMachineFunction().getFunction().optForMinSize() &&
18985         !Subtarget.isAtom()) {
18986       unsigned ExtendOp =
18987           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
18988       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
18989       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
18990     }
18991     // Use SUB instead of CMP to enable CSE between SUB and CMP.
18992     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
18993     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs, Op0, Op1);
18994     return SDValue(Sub.getNode(), 1);
18995   }
18996   assert(Op0.getValueType().isFloatingPoint() && "Unexpected VT!");
18997   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
18998 }
18999 
19000 /// Convert a comparison if required by the subtarget.
ConvertCmpIfNecessary(SDValue Cmp,SelectionDAG & DAG) const19001 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
19002                                                  SelectionDAG &DAG) const {
19003   // If the subtarget does not support the FUCOMI instruction, floating-point
19004   // comparisons have to be converted.
19005   if (Subtarget.hasCMov() ||
19006       Cmp.getOpcode() != X86ISD::CMP ||
19007       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
19008       !Cmp.getOperand(1).getValueType().isFloatingPoint())
19009     return Cmp;
19010 
19011   // The instruction selector will select an FUCOM instruction instead of
19012   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
19013   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
19014   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
19015   SDLoc dl(Cmp);
19016   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
19017   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
19018   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
19019                             DAG.getConstant(8, dl, MVT::i8));
19020   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
19021 
19022   // Some 64-bit targets lack SAHF support, but they do support FCOMI.
19023   assert(Subtarget.hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?");
19024   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
19025 }
19026 
19027 /// Check if replacement of SQRT with RSQRT should be disabled.
isFsqrtCheap(SDValue Op,SelectionDAG & DAG) const19028 bool X86TargetLowering::isFsqrtCheap(SDValue Op, SelectionDAG &DAG) const {
19029   EVT VT = Op.getValueType();
19030 
19031   // We never want to use both SQRT and RSQRT instructions for the same input.
19032   if (DAG.getNodeIfExists(X86ISD::FRSQRT, DAG.getVTList(VT), Op))
19033     return false;
19034 
19035   if (VT.isVector())
19036     return Subtarget.hasFastVectorFSQRT();
19037   return Subtarget.hasFastScalarFSQRT();
19038 }
19039 
19040 /// The minimum architected relative accuracy is 2^-12. We need one
19041 /// Newton-Raphson step to have a good float result (24 bits of precision).
getSqrtEstimate(SDValue Op,SelectionDAG & DAG,int Enabled,int & RefinementSteps,bool & UseOneConstNR,bool Reciprocal) const19042 SDValue X86TargetLowering::getSqrtEstimate(SDValue Op,
19043                                            SelectionDAG &DAG, int Enabled,
19044                                            int &RefinementSteps,
19045                                            bool &UseOneConstNR,
19046                                            bool Reciprocal) const {
19047   EVT VT = Op.getValueType();
19048 
19049   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
19050   // It is likely not profitable to do this for f64 because a double-precision
19051   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
19052   // instructions: convert to single, rsqrtss, convert back to double, refine
19053   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
19054   // along with FMA, this could be a throughput win.
19055   // TODO: SQRT requires SSE2 to prevent the introduction of an illegal v4i32
19056   // after legalize types.
19057   if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
19058       (VT == MVT::v4f32 && Subtarget.hasSSE1() && Reciprocal) ||
19059       (VT == MVT::v4f32 && Subtarget.hasSSE2() && !Reciprocal) ||
19060       (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
19061       (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
19062     if (RefinementSteps == ReciprocalEstimate::Unspecified)
19063       RefinementSteps = 1;
19064 
19065     UseOneConstNR = false;
19066     // There is no FSQRT for 512-bits, but there is RSQRT14.
19067     unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RSQRT14 : X86ISD::FRSQRT;
19068     return DAG.getNode(Opcode, SDLoc(Op), VT, Op);
19069   }
19070   return SDValue();
19071 }
19072 
19073 /// The minimum architected relative accuracy is 2^-12. We need one
19074 /// Newton-Raphson step to have a good float result (24 bits of precision).
getRecipEstimate(SDValue Op,SelectionDAG & DAG,int Enabled,int & RefinementSteps) const19075 SDValue X86TargetLowering::getRecipEstimate(SDValue Op, SelectionDAG &DAG,
19076                                             int Enabled,
19077                                             int &RefinementSteps) const {
19078   EVT VT = Op.getValueType();
19079 
19080   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
19081   // It is likely not profitable to do this for f64 because a double-precision
19082   // reciprocal estimate with refinement on x86 prior to FMA requires
19083   // 15 instructions: convert to single, rcpss, convert back to double, refine
19084   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
19085   // along with FMA, this could be a throughput win.
19086 
19087   if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
19088       (VT == MVT::v4f32 && Subtarget.hasSSE1()) ||
19089       (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
19090       (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
19091     // Enable estimate codegen with 1 refinement step for vector division.
19092     // Scalar division estimates are disabled because they break too much
19093     // real-world code. These defaults are intended to match GCC behavior.
19094     if (VT == MVT::f32 && Enabled == ReciprocalEstimate::Unspecified)
19095       return SDValue();
19096 
19097     if (RefinementSteps == ReciprocalEstimate::Unspecified)
19098       RefinementSteps = 1;
19099 
19100     // There is no FSQRT for 512-bits, but there is RCP14.
19101     unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RCP14 : X86ISD::FRCP;
19102     return DAG.getNode(Opcode, SDLoc(Op), VT, Op);
19103   }
19104   return SDValue();
19105 }
19106 
19107 /// If we have at least two divisions that use the same divisor, convert to
19108 /// multiplication by a reciprocal. This may need to be adjusted for a given
19109 /// CPU if a division's cost is not at least twice the cost of a multiplication.
19110 /// This is because we still need one division to calculate the reciprocal and
19111 /// then we need two multiplies by that reciprocal as replacements for the
19112 /// original divisions.
combineRepeatedFPDivisors() const19113 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
19114   return 2;
19115 }
19116 
19117 /// Result of 'and' is compared against zero. Change to a BT node if possible.
19118 /// Returns the BT node and the condition code needed to use it.
LowerAndToBT(SDValue And,ISD::CondCode CC,const SDLoc & dl,SelectionDAG & DAG,SDValue & X86CC)19119 static SDValue LowerAndToBT(SDValue And, ISD::CondCode CC,
19120                             const SDLoc &dl, SelectionDAG &DAG,
19121                             SDValue &X86CC) {
19122   assert(And.getOpcode() == ISD::AND && "Expected AND node!");
19123   SDValue Op0 = And.getOperand(0);
19124   SDValue Op1 = And.getOperand(1);
19125   if (Op0.getOpcode() == ISD::TRUNCATE)
19126     Op0 = Op0.getOperand(0);
19127   if (Op1.getOpcode() == ISD::TRUNCATE)
19128     Op1 = Op1.getOperand(0);
19129 
19130   SDValue Src, BitNo;
19131   if (Op1.getOpcode() == ISD::SHL)
19132     std::swap(Op0, Op1);
19133   if (Op0.getOpcode() == ISD::SHL) {
19134     if (isOneConstant(Op0.getOperand(0))) {
19135       // If we looked past a truncate, check that it's only truncating away
19136       // known zeros.
19137       unsigned BitWidth = Op0.getValueSizeInBits();
19138       unsigned AndBitWidth = And.getValueSizeInBits();
19139       if (BitWidth > AndBitWidth) {
19140         KnownBits Known = DAG.computeKnownBits(Op0);
19141         if (Known.countMinLeadingZeros() < BitWidth - AndBitWidth)
19142           return SDValue();
19143       }
19144       Src = Op1;
19145       BitNo = Op0.getOperand(1);
19146     }
19147   } else if (Op1.getOpcode() == ISD::Constant) {
19148     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
19149     uint64_t AndRHSVal = AndRHS->getZExtValue();
19150     SDValue AndLHS = Op0;
19151 
19152     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
19153       Src = AndLHS.getOperand(0);
19154       BitNo = AndLHS.getOperand(1);
19155     } else {
19156       // Use BT if the immediate can't be encoded in a TEST instruction or we
19157       // are optimizing for size and the immedaite won't fit in a byte.
19158       bool OptForSize = DAG.getMachineFunction().getFunction().optForSize();
19159       if ((!isUInt<32>(AndRHSVal) || (OptForSize && !isUInt<8>(AndRHSVal))) &&
19160           isPowerOf2_64(AndRHSVal)) {
19161         Src = AndLHS;
19162         BitNo = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl,
19163                                 Src.getValueType());
19164       }
19165     }
19166   }
19167 
19168   // No patterns found, give up.
19169   if (!Src.getNode())
19170     return SDValue();
19171 
19172   // If Src is i8, promote it to i32 with any_extend.  There is no i8 BT
19173   // instruction.  Since the shift amount is in-range-or-undefined, we know
19174   // that doing a bittest on the i32 value is ok.  We extend to i32 because
19175   // the encoding for the i16 version is larger than the i32 version.
19176   // Also promote i16 to i32 for performance / code size reason.
19177   if (Src.getValueType() == MVT::i8 || Src.getValueType() == MVT::i16)
19178     Src = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Src);
19179 
19180   // See if we can use the 32-bit instruction instead of the 64-bit one for a
19181   // shorter encoding. Since the former takes the modulo 32 of BitNo and the
19182   // latter takes the modulo 64, this is only valid if the 5th bit of BitNo is
19183   // known to be zero.
19184   if (Src.getValueType() == MVT::i64 &&
19185       DAG.MaskedValueIsZero(BitNo, APInt(BitNo.getValueSizeInBits(), 32)))
19186     Src = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
19187 
19188   // If the operand types disagree, extend the shift amount to match.  Since
19189   // BT ignores high bits (like shifts) we can use anyextend.
19190   if (Src.getValueType() != BitNo.getValueType())
19191     BitNo = DAG.getNode(ISD::ANY_EXTEND, dl, Src.getValueType(), BitNo);
19192 
19193   X86CC = DAG.getConstant(CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B,
19194                           dl, MVT::i8);
19195   return DAG.getNode(X86ISD::BT, dl, MVT::i32, Src, BitNo);
19196 }
19197 
19198 /// Turns an ISD::CondCode into a value suitable for SSE floating-point mask
19199 /// CMPs.
translateX86FSETCC(ISD::CondCode SetCCOpcode,SDValue & Op0,SDValue & Op1)19200 static unsigned translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
19201                                    SDValue &Op1) {
19202   unsigned SSECC;
19203   bool Swap = false;
19204 
19205   // SSE Condition code mapping:
19206   //  0 - EQ
19207   //  1 - LT
19208   //  2 - LE
19209   //  3 - UNORD
19210   //  4 - NEQ
19211   //  5 - NLT
19212   //  6 - NLE
19213   //  7 - ORD
19214   switch (SetCCOpcode) {
19215   default: llvm_unreachable("Unexpected SETCC condition");
19216   case ISD::SETOEQ:
19217   case ISD::SETEQ:  SSECC = 0; break;
19218   case ISD::SETOGT:
19219   case ISD::SETGT:  Swap = true; LLVM_FALLTHROUGH;
19220   case ISD::SETLT:
19221   case ISD::SETOLT: SSECC = 1; break;
19222   case ISD::SETOGE:
19223   case ISD::SETGE:  Swap = true; LLVM_FALLTHROUGH;
19224   case ISD::SETLE:
19225   case ISD::SETOLE: SSECC = 2; break;
19226   case ISD::SETUO:  SSECC = 3; break;
19227   case ISD::SETUNE:
19228   case ISD::SETNE:  SSECC = 4; break;
19229   case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
19230   case ISD::SETUGE: SSECC = 5; break;
19231   case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
19232   case ISD::SETUGT: SSECC = 6; break;
19233   case ISD::SETO:   SSECC = 7; break;
19234   case ISD::SETUEQ: SSECC = 8; break;
19235   case ISD::SETONE: SSECC = 12; break;
19236   }
19237   if (Swap)
19238     std::swap(Op0, Op1);
19239 
19240   return SSECC;
19241 }
19242 
19243 /// Break a VSETCC 256-bit integer VSETCC into two new 128 ones and then
19244 /// concatenate the result back.
Lower256IntVSETCC(SDValue Op,SelectionDAG & DAG)19245 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
19246   MVT VT = Op.getSimpleValueType();
19247 
19248   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
19249          "Unsupported value type for operation");
19250 
19251   unsigned NumElems = VT.getVectorNumElements();
19252   SDLoc dl(Op);
19253   SDValue CC = Op.getOperand(2);
19254 
19255   // Extract the LHS vectors
19256   SDValue LHS = Op.getOperand(0);
19257   SDValue LHS1 = extract128BitVector(LHS, 0, DAG, dl);
19258   SDValue LHS2 = extract128BitVector(LHS, NumElems / 2, DAG, dl);
19259 
19260   // Extract the RHS vectors
19261   SDValue RHS = Op.getOperand(1);
19262   SDValue RHS1 = extract128BitVector(RHS, 0, DAG, dl);
19263   SDValue RHS2 = extract128BitVector(RHS, NumElems / 2, DAG, dl);
19264 
19265   // Issue the operation on the smaller types and concatenate the result back
19266   MVT EltVT = VT.getVectorElementType();
19267   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
19268   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
19269                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
19270                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
19271 }
19272 
LowerIntVSETCC_AVX512(SDValue Op,SelectionDAG & DAG)19273 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
19274 
19275   SDValue Op0 = Op.getOperand(0);
19276   SDValue Op1 = Op.getOperand(1);
19277   SDValue CC = Op.getOperand(2);
19278   MVT VT = Op.getSimpleValueType();
19279   SDLoc dl(Op);
19280 
19281   assert(VT.getVectorElementType() == MVT::i1 &&
19282          "Cannot set masked compare for this operation");
19283 
19284   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
19285 
19286   // If this is a seteq make sure any build vectors of all zeros are on the RHS.
19287   // This helps with vptestm matching.
19288   // TODO: Should we just canonicalize the setcc during DAG combine?
19289   if ((SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE) &&
19290       ISD::isBuildVectorAllZeros(Op0.getNode()))
19291     std::swap(Op0, Op1);
19292 
19293   // Prefer SETGT over SETLT.
19294   if (SetCCOpcode == ISD::SETLT) {
19295     SetCCOpcode = ISD::getSetCCSwappedOperands(SetCCOpcode);
19296     std::swap(Op0, Op1);
19297   }
19298 
19299   return DAG.getSetCC(dl, VT, Op0, Op1, SetCCOpcode);
19300 }
19301 
19302 /// Given a simple buildvector constant, return a new vector constant with each
19303 /// element decremented. If decrementing would result in underflow or this
19304 /// is not a simple vector constant, return an empty value.
decrementVectorConstant(SDValue V,SelectionDAG & DAG)19305 static SDValue decrementVectorConstant(SDValue V, SelectionDAG &DAG) {
19306   auto *BV = dyn_cast<BuildVectorSDNode>(V.getNode());
19307   if (!BV)
19308     return SDValue();
19309 
19310   MVT VT = V.getSimpleValueType();
19311   MVT EltVT = VT.getVectorElementType();
19312   unsigned NumElts = VT.getVectorNumElements();
19313   SmallVector<SDValue, 8> NewVecC;
19314   SDLoc DL(V);
19315   for (unsigned i = 0; i < NumElts; ++i) {
19316     auto *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
19317     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EltVT)
19318       return SDValue();
19319 
19320     // Avoid underflow.
19321     if (Elt->getAPIntValue().isNullValue())
19322       return SDValue();
19323 
19324     NewVecC.push_back(DAG.getConstant(Elt->getAPIntValue() - 1, DL, EltVT));
19325   }
19326 
19327   return DAG.getBuildVector(VT, DL, NewVecC);
19328 }
19329 
19330 /// As another special case, use PSUBUS[BW] when it's profitable. E.g. for
19331 /// Op0 u<= Op1:
19332 ///   t = psubus Op0, Op1
19333 ///   pcmpeq t, <0..0>
LowerVSETCCWithSUBUS(SDValue Op0,SDValue Op1,MVT VT,ISD::CondCode Cond,const SDLoc & dl,const X86Subtarget & Subtarget,SelectionDAG & DAG)19334 static SDValue LowerVSETCCWithSUBUS(SDValue Op0, SDValue Op1, MVT VT,
19335                                     ISD::CondCode Cond, const SDLoc &dl,
19336                                     const X86Subtarget &Subtarget,
19337                                     SelectionDAG &DAG) {
19338   if (!Subtarget.hasSSE2())
19339     return SDValue();
19340 
19341   MVT VET = VT.getVectorElementType();
19342   if (VET != MVT::i8 && VET != MVT::i16)
19343     return SDValue();
19344 
19345   switch (Cond) {
19346   default:
19347     return SDValue();
19348   case ISD::SETULT: {
19349     // If the comparison is against a constant we can turn this into a
19350     // setule.  With psubus, setule does not require a swap.  This is
19351     // beneficial because the constant in the register is no longer
19352     // destructed as the destination so it can be hoisted out of a loop.
19353     // Only do this pre-AVX since vpcmp* is no longer destructive.
19354     if (Subtarget.hasAVX())
19355       return SDValue();
19356     SDValue ULEOp1 = decrementVectorConstant(Op1, DAG);
19357     if (!ULEOp1)
19358       return SDValue();
19359     Op1 = ULEOp1;
19360     break;
19361   }
19362   // Psubus is better than flip-sign because it requires no inversion.
19363   case ISD::SETUGE:
19364     std::swap(Op0, Op1);
19365     break;
19366   case ISD::SETULE:
19367     break;
19368   }
19369 
19370   SDValue Result = DAG.getNode(ISD::USUBSAT, dl, VT, Op0, Op1);
19371   return DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
19372                      DAG.getConstant(0, dl, VT));
19373 }
19374 
LowerVSETCC(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)19375 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget &Subtarget,
19376                            SelectionDAG &DAG) {
19377   SDValue Op0 = Op.getOperand(0);
19378   SDValue Op1 = Op.getOperand(1);
19379   SDValue CC = Op.getOperand(2);
19380   MVT VT = Op.getSimpleValueType();
19381   ISD::CondCode Cond = cast<CondCodeSDNode>(CC)->get();
19382   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
19383   SDLoc dl(Op);
19384 
19385   if (isFP) {
19386 #ifndef NDEBUG
19387     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
19388     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
19389 #endif
19390 
19391     unsigned Opc;
19392     if (Subtarget.hasAVX512() && VT.getVectorElementType() == MVT::i1) {
19393       assert(VT.getVectorNumElements() <= 16);
19394       Opc = X86ISD::CMPM;
19395     } else {
19396       Opc = X86ISD::CMPP;
19397       // The SSE/AVX packed FP comparison nodes are defined with a
19398       // floating-point vector result that matches the operand type. This allows
19399       // them to work with an SSE1 target (integer vector types are not legal).
19400       VT = Op0.getSimpleValueType();
19401     }
19402 
19403     // In the two cases not handled by SSE compare predicates (SETUEQ/SETONE),
19404     // emit two comparisons and a logic op to tie them together.
19405     SDValue Cmp;
19406     unsigned SSECC = translateX86FSETCC(Cond, Op0, Op1);
19407     if (SSECC >= 8 && !Subtarget.hasAVX()) {
19408       // LLVM predicate is SETUEQ or SETONE.
19409       unsigned CC0, CC1;
19410       unsigned CombineOpc;
19411       if (Cond == ISD::SETUEQ) {
19412         CC0 = 3; // UNORD
19413         CC1 = 0; // EQ
19414         CombineOpc = X86ISD::FOR;
19415       } else {
19416         assert(Cond == ISD::SETONE);
19417         CC0 = 7; // ORD
19418         CC1 = 4; // NEQ
19419         CombineOpc = X86ISD::FAND;
19420       }
19421 
19422       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
19423                                  DAG.getConstant(CC0, dl, MVT::i8));
19424       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
19425                                  DAG.getConstant(CC1, dl, MVT::i8));
19426       Cmp = DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
19427     } else {
19428       // Handle all other FP comparisons here.
19429       Cmp = DAG.getNode(Opc, dl, VT, Op0, Op1,
19430                         DAG.getConstant(SSECC, dl, MVT::i8));
19431     }
19432 
19433     // If this is SSE/AVX CMPP, bitcast the result back to integer to match the
19434     // result type of SETCC. The bitcast is expected to be optimized away
19435     // during combining/isel.
19436     if (Opc == X86ISD::CMPP)
19437       Cmp = DAG.getBitcast(Op.getSimpleValueType(), Cmp);
19438 
19439     return Cmp;
19440   }
19441 
19442   MVT VTOp0 = Op0.getSimpleValueType();
19443   assert(VTOp0 == Op1.getSimpleValueType() &&
19444          "Expected operands with same type!");
19445   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
19446          "Invalid number of packed elements for source and destination!");
19447 
19448   // This is being called by type legalization because v2i32 is marked custom
19449   // for result type legalization for v2f32.
19450   if (VTOp0 == MVT::v2i32)
19451     return SDValue();
19452 
19453   // The non-AVX512 code below works under the assumption that source and
19454   // destination types are the same.
19455   assert((Subtarget.hasAVX512() || (VT == VTOp0)) &&
19456          "Value types for source and destination must be the same!");
19457 
19458   // Break 256-bit integer vector compare into smaller ones.
19459   if (VT.is256BitVector() && !Subtarget.hasInt256())
19460     return Lower256IntVSETCC(Op, DAG);
19461 
19462   // The result is boolean, but operands are int/float
19463   if (VT.getVectorElementType() == MVT::i1) {
19464     // In AVX-512 architecture setcc returns mask with i1 elements,
19465     // But there is no compare instruction for i8 and i16 elements in KNL.
19466     assert((VTOp0.getScalarSizeInBits() >= 32 || Subtarget.hasBWI()) &&
19467            "Unexpected operand type");
19468     return LowerIntVSETCC_AVX512(Op, DAG);
19469   }
19470 
19471   // Lower using XOP integer comparisons.
19472   if (VT.is128BitVector() && Subtarget.hasXOP()) {
19473     // Translate compare code to XOP PCOM compare mode.
19474     unsigned CmpMode = 0;
19475     switch (Cond) {
19476     default: llvm_unreachable("Unexpected SETCC condition");
19477     case ISD::SETULT:
19478     case ISD::SETLT: CmpMode = 0x00; break;
19479     case ISD::SETULE:
19480     case ISD::SETLE: CmpMode = 0x01; break;
19481     case ISD::SETUGT:
19482     case ISD::SETGT: CmpMode = 0x02; break;
19483     case ISD::SETUGE:
19484     case ISD::SETGE: CmpMode = 0x03; break;
19485     case ISD::SETEQ: CmpMode = 0x04; break;
19486     case ISD::SETNE: CmpMode = 0x05; break;
19487     }
19488 
19489     // Are we comparing unsigned or signed integers?
19490     unsigned Opc =
19491         ISD::isUnsignedIntSetCC(Cond) ? X86ISD::VPCOMU : X86ISD::VPCOM;
19492 
19493     return DAG.getNode(Opc, dl, VT, Op0, Op1,
19494                        DAG.getConstant(CmpMode, dl, MVT::i8));
19495   }
19496 
19497   // (X & Y) != 0 --> (X & Y) == Y iff Y is power-of-2.
19498   // Revert part of the simplifySetCCWithAnd combine, to avoid an invert.
19499   if (Cond == ISD::SETNE && ISD::isBuildVectorAllZeros(Op1.getNode())) {
19500     SDValue BC0 = peekThroughBitcasts(Op0);
19501     if (BC0.getOpcode() == ISD::AND) {
19502       APInt UndefElts;
19503       SmallVector<APInt, 64> EltBits;
19504       if (getTargetConstantBitsFromNode(BC0.getOperand(1),
19505                                         VT.getScalarSizeInBits(), UndefElts,
19506                                         EltBits, false, false)) {
19507         if (llvm::all_of(EltBits, [](APInt &V) { return V.isPowerOf2(); })) {
19508           Cond = ISD::SETEQ;
19509           Op1 = DAG.getBitcast(VT, BC0.getOperand(1));
19510         }
19511       }
19512     }
19513   }
19514 
19515   // If this is a SETNE against the signed minimum value, change it to SETGT.
19516   // If this is a SETNE against the signed maximum value, change it to SETLT.
19517   // which will be swapped to SETGT.
19518   // Otherwise we use PCMPEQ+invert.
19519   APInt ConstValue;
19520   if (Cond == ISD::SETNE &&
19521       ISD::isConstantSplatVector(Op1.getNode(), ConstValue)) {
19522     if (ConstValue.isMinSignedValue())
19523       Cond = ISD::SETGT;
19524     else if (ConstValue.isMaxSignedValue())
19525       Cond = ISD::SETLT;
19526   }
19527 
19528   // If both operands are known non-negative, then an unsigned compare is the
19529   // same as a signed compare and there's no need to flip signbits.
19530   // TODO: We could check for more general simplifications here since we're
19531   // computing known bits.
19532   bool FlipSigns = ISD::isUnsignedIntSetCC(Cond) &&
19533                    !(DAG.SignBitIsZero(Op0) && DAG.SignBitIsZero(Op1));
19534 
19535   // Special case: Use min/max operations for unsigned compares.
19536   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19537   if (ISD::isUnsignedIntSetCC(Cond) &&
19538       (FlipSigns || ISD::isTrueWhenEqual(Cond)) &&
19539       TLI.isOperationLegal(ISD::UMIN, VT)) {
19540     // If we have a constant operand, increment/decrement it and change the
19541     // condition to avoid an invert.
19542     // TODO: This could be extended to handle a non-splat constant by checking
19543     // that each element of the constant is not the max/null value.
19544     APInt C;
19545     if (Cond == ISD::SETUGT && isConstantSplat(Op1, C) && !C.isMaxValue()) {
19546       // X > C --> X >= (C+1) --> X == umax(X, C+1)
19547       Op1 = DAG.getConstant(C + 1, dl, VT);
19548       Cond = ISD::SETUGE;
19549     }
19550     if (Cond == ISD::SETULT && isConstantSplat(Op1, C) && !C.isNullValue()) {
19551       // X < C --> X <= (C-1) --> X == umin(X, C-1)
19552       Op1 = DAG.getConstant(C - 1, dl, VT);
19553       Cond = ISD::SETULE;
19554     }
19555     bool Invert = false;
19556     unsigned Opc;
19557     switch (Cond) {
19558     default: llvm_unreachable("Unexpected condition code");
19559     case ISD::SETUGT: Invert = true; LLVM_FALLTHROUGH;
19560     case ISD::SETULE: Opc = ISD::UMIN; break;
19561     case ISD::SETULT: Invert = true; LLVM_FALLTHROUGH;
19562     case ISD::SETUGE: Opc = ISD::UMAX; break;
19563     }
19564 
19565     SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
19566     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
19567 
19568     // If the logical-not of the result is required, perform that now.
19569     if (Invert)
19570       Result = DAG.getNOT(dl, Result, VT);
19571 
19572     return Result;
19573   }
19574 
19575   // Try to use SUBUS and PCMPEQ.
19576   if (SDValue V = LowerVSETCCWithSUBUS(Op0, Op1, VT, Cond, dl, Subtarget, DAG))
19577     return V;
19578 
19579   // We are handling one of the integer comparisons here. Since SSE only has
19580   // GT and EQ comparisons for integer, swapping operands and multiple
19581   // operations may be required for some comparisons.
19582   unsigned Opc = (Cond == ISD::SETEQ || Cond == ISD::SETNE) ? X86ISD::PCMPEQ
19583                                                             : X86ISD::PCMPGT;
19584   bool Swap = Cond == ISD::SETLT || Cond == ISD::SETULT ||
19585               Cond == ISD::SETGE || Cond == ISD::SETUGE;
19586   bool Invert = Cond == ISD::SETNE ||
19587                 (Cond != ISD::SETEQ && ISD::isTrueWhenEqual(Cond));
19588 
19589   if (Swap)
19590     std::swap(Op0, Op1);
19591 
19592   // Check that the operation in question is available (most are plain SSE2,
19593   // but PCMPGTQ and PCMPEQQ have different requirements).
19594   if (VT == MVT::v2i64) {
19595     if (Opc == X86ISD::PCMPGT && !Subtarget.hasSSE42()) {
19596       assert(Subtarget.hasSSE2() && "Don't know how to lower!");
19597 
19598       // Since SSE has no unsigned integer comparisons, we need to flip the sign
19599       // bits of the inputs before performing those operations. The lower
19600       // compare is always unsigned.
19601       SDValue SB;
19602       if (FlipSigns) {
19603         SB = DAG.getConstant(0x8000000080000000ULL, dl, MVT::v2i64);
19604       } else {
19605         SB = DAG.getConstant(0x0000000080000000ULL, dl, MVT::v2i64);
19606       }
19607       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op0, SB);
19608       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op1, SB);
19609 
19610       // Cast everything to the right type.
19611       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
19612       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
19613 
19614       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
19615       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
19616       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
19617 
19618       // Create masks for only the low parts/high parts of the 64 bit integers.
19619       static const int MaskHi[] = { 1, 1, 3, 3 };
19620       static const int MaskLo[] = { 0, 0, 2, 2 };
19621       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
19622       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
19623       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
19624 
19625       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
19626       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
19627 
19628       if (Invert)
19629         Result = DAG.getNOT(dl, Result, MVT::v4i32);
19630 
19631       return DAG.getBitcast(VT, Result);
19632     }
19633 
19634     if (Opc == X86ISD::PCMPEQ && !Subtarget.hasSSE41()) {
19635       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
19636       // pcmpeqd + pshufd + pand.
19637       assert(Subtarget.hasSSE2() && !FlipSigns && "Don't know how to lower!");
19638 
19639       // First cast everything to the right type.
19640       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
19641       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
19642 
19643       // Do the compare.
19644       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
19645 
19646       // Make sure the lower and upper halves are both all-ones.
19647       static const int Mask[] = { 1, 0, 3, 2 };
19648       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
19649       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
19650 
19651       if (Invert)
19652         Result = DAG.getNOT(dl, Result, MVT::v4i32);
19653 
19654       return DAG.getBitcast(VT, Result);
19655     }
19656   }
19657 
19658   // Since SSE has no unsigned integer comparisons, we need to flip the sign
19659   // bits of the inputs before performing those operations.
19660   if (FlipSigns) {
19661     MVT EltVT = VT.getVectorElementType();
19662     SDValue SM = DAG.getConstant(APInt::getSignMask(EltVT.getSizeInBits()), dl,
19663                                  VT);
19664     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SM);
19665     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SM);
19666   }
19667 
19668   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
19669 
19670   // If the logical-not of the result is required, perform that now.
19671   if (Invert)
19672     Result = DAG.getNOT(dl, Result, VT);
19673 
19674   return Result;
19675 }
19676 
19677 // Try to select this as a KORTEST+SETCC if possible.
EmitKORTEST(SDValue Op0,SDValue Op1,ISD::CondCode CC,const SDLoc & dl,SelectionDAG & DAG,const X86Subtarget & Subtarget,SDValue & X86CC)19678 static SDValue EmitKORTEST(SDValue Op0, SDValue Op1, ISD::CondCode CC,
19679                            const SDLoc &dl, SelectionDAG &DAG,
19680                            const X86Subtarget &Subtarget,
19681                            SDValue &X86CC) {
19682   // Only support equality comparisons.
19683   if (CC != ISD::SETEQ && CC != ISD::SETNE)
19684     return SDValue();
19685 
19686   // Must be a bitcast from vXi1.
19687   if (Op0.getOpcode() != ISD::BITCAST)
19688     return SDValue();
19689 
19690   Op0 = Op0.getOperand(0);
19691   MVT VT = Op0.getSimpleValueType();
19692   if (!(Subtarget.hasAVX512() && VT == MVT::v16i1) &&
19693       !(Subtarget.hasDQI() && VT == MVT::v8i1) &&
19694       !(Subtarget.hasBWI() && (VT == MVT::v32i1 || VT == MVT::v64i1)))
19695     return SDValue();
19696 
19697   X86::CondCode X86Cond;
19698   if (isNullConstant(Op1)) {
19699     X86Cond = CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE;
19700   } else if (isAllOnesConstant(Op1)) {
19701     // C flag is set for all ones.
19702     X86Cond = CC == ISD::SETEQ ? X86::COND_B : X86::COND_AE;
19703   } else
19704     return SDValue();
19705 
19706   // If the input is an OR, we can combine it's operands into the KORTEST.
19707   SDValue LHS = Op0;
19708   SDValue RHS = Op0;
19709   if (Op0.getOpcode() == ISD::OR && Op0.hasOneUse()) {
19710     LHS = Op0.getOperand(0);
19711     RHS = Op0.getOperand(1);
19712   }
19713 
19714   X86CC = DAG.getConstant(X86Cond, dl, MVT::i8);
19715   return DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
19716 }
19717 
19718 /// Emit flags for the given setcc condition and operands. Also returns the
19719 /// corresponding X86 condition code constant in X86CC.
emitFlagsForSetcc(SDValue Op0,SDValue Op1,ISD::CondCode CC,const SDLoc & dl,SelectionDAG & DAG,SDValue & X86CC) const19720 SDValue X86TargetLowering::emitFlagsForSetcc(SDValue Op0, SDValue Op1,
19721                                              ISD::CondCode CC, const SDLoc &dl,
19722                                              SelectionDAG &DAG,
19723                                              SDValue &X86CC) const {
19724   // Optimize to BT if possible.
19725   // Lower (X & (1 << N)) == 0 to BT(X, N).
19726   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
19727   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
19728   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && isNullConstant(Op1) &&
19729       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
19730     if (SDValue BT = LowerAndToBT(Op0, CC, dl, DAG, X86CC))
19731       return BT;
19732   }
19733 
19734   // Try to use PTEST for a tree ORs equality compared with 0.
19735   // TODO: We could do AND tree with all 1s as well by using the C flag.
19736   if (Op0.getOpcode() == ISD::OR && isNullConstant(Op1) &&
19737       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
19738     if (SDValue PTEST = LowerVectorAllZeroTest(Op0, CC, Subtarget, DAG, X86CC))
19739       return PTEST;
19740   }
19741 
19742   // Try to lower using KORTEST.
19743   if (SDValue KORTEST = EmitKORTEST(Op0, Op1, CC, dl, DAG, Subtarget, X86CC))
19744     return KORTEST;
19745 
19746   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
19747   // these.
19748   if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
19749       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
19750     // If the input is a setcc, then reuse the input setcc or use a new one with
19751     // the inverted condition.
19752     if (Op0.getOpcode() == X86ISD::SETCC) {
19753       bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
19754 
19755       X86CC = Op0.getOperand(0);
19756       if (Invert) {
19757         X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
19758         CCode = X86::GetOppositeBranchCondition(CCode);
19759         X86CC = DAG.getConstant(CCode, dl, MVT::i8);
19760       }
19761 
19762       return Op0.getOperand(1);
19763     }
19764   }
19765 
19766   bool IsFP = Op1.getSimpleValueType().isFloatingPoint();
19767   X86::CondCode CondCode = TranslateX86CC(CC, dl, IsFP, Op0, Op1, DAG);
19768   if (CondCode == X86::COND_INVALID)
19769     return SDValue();
19770 
19771   SDValue EFLAGS = EmitCmp(Op0, Op1, CondCode, dl, DAG);
19772   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
19773   X86CC = DAG.getConstant(CondCode, dl, MVT::i8);
19774   return EFLAGS;
19775 }
19776 
LowerSETCC(SDValue Op,SelectionDAG & DAG) const19777 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
19778 
19779   MVT VT = Op.getSimpleValueType();
19780 
19781   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
19782 
19783   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
19784   SDValue Op0 = Op.getOperand(0);
19785   SDValue Op1 = Op.getOperand(1);
19786   SDLoc dl(Op);
19787   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
19788 
19789   SDValue X86CC;
19790   SDValue EFLAGS = emitFlagsForSetcc(Op0, Op1, CC, dl, DAG, X86CC);
19791   if (!EFLAGS)
19792     return SDValue();
19793 
19794   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, X86CC, EFLAGS);
19795 }
19796 
LowerSETCCCARRY(SDValue Op,SelectionDAG & DAG) const19797 SDValue X86TargetLowering::LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) const {
19798   SDValue LHS = Op.getOperand(0);
19799   SDValue RHS = Op.getOperand(1);
19800   SDValue Carry = Op.getOperand(2);
19801   SDValue Cond = Op.getOperand(3);
19802   SDLoc DL(Op);
19803 
19804   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
19805   X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
19806 
19807   // Recreate the carry if needed.
19808   EVT CarryVT = Carry.getValueType();
19809   APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits());
19810   Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
19811                       Carry, DAG.getConstant(NegOne, DL, CarryVT));
19812 
19813   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
19814   SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry.getValue(1));
19815   return getSETCC(CC, Cmp.getValue(1), DL, DAG);
19816 }
19817 
19818 // This function returns three things: the arithmetic computation itself
19819 // (Value), an EFLAGS result (Overflow), and a condition code (Cond).  The
19820 // flag and the condition code define the case in which the arithmetic
19821 // computation overflows.
19822 static std::pair<SDValue, SDValue>
getX86XALUOOp(X86::CondCode & Cond,SDValue Op,SelectionDAG & DAG)19823 getX86XALUOOp(X86::CondCode &Cond, SDValue Op, SelectionDAG &DAG) {
19824   assert(Op.getResNo() == 0 && "Unexpected result number!");
19825   SDValue Value, Overflow;
19826   SDValue LHS = Op.getOperand(0);
19827   SDValue RHS = Op.getOperand(1);
19828   unsigned BaseOp = 0;
19829   SDLoc DL(Op);
19830   switch (Op.getOpcode()) {
19831   default: llvm_unreachable("Unknown ovf instruction!");
19832   case ISD::SADDO:
19833     BaseOp = X86ISD::ADD;
19834     Cond = X86::COND_O;
19835     break;
19836   case ISD::UADDO:
19837     BaseOp = X86ISD::ADD;
19838     Cond = X86::COND_B;
19839     break;
19840   case ISD::SSUBO:
19841     BaseOp = X86ISD::SUB;
19842     Cond = X86::COND_O;
19843     break;
19844   case ISD::USUBO:
19845     BaseOp = X86ISD::SUB;
19846     Cond = X86::COND_B;
19847     break;
19848   case ISD::SMULO:
19849     BaseOp = X86ISD::SMUL;
19850     Cond = X86::COND_O;
19851     break;
19852   case ISD::UMULO:
19853     BaseOp = X86ISD::UMUL;
19854     Cond = X86::COND_O;
19855     break;
19856   }
19857 
19858   if (BaseOp) {
19859     // Also sets EFLAGS.
19860     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
19861     Value = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
19862     Overflow = Value.getValue(1);
19863   }
19864 
19865   return std::make_pair(Value, Overflow);
19866 }
19867 
LowerXALUO(SDValue Op,SelectionDAG & DAG)19868 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
19869   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
19870   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
19871   // looks for this combo and may remove the "setcc" instruction if the "setcc"
19872   // has only one use.
19873   SDLoc DL(Op);
19874   X86::CondCode Cond;
19875   SDValue Value, Overflow;
19876   std::tie(Value, Overflow) = getX86XALUOOp(Cond, Op, DAG);
19877 
19878   SDValue SetCC = getSETCC(Cond, Overflow, DL, DAG);
19879   return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(), Value, SetCC);
19880 }
19881 
19882 /// Return true if opcode is a X86 logical comparison.
isX86LogicalCmp(SDValue Op)19883 static bool isX86LogicalCmp(SDValue Op) {
19884   unsigned Opc = Op.getOpcode();
19885   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
19886       Opc == X86ISD::SAHF)
19887     return true;
19888   if (Op.getResNo() == 1 &&
19889       (Opc == X86ISD::ADD || Opc == X86ISD::SUB || Opc == X86ISD::ADC ||
19890        Opc == X86ISD::SBB || Opc == X86ISD::SMUL || Opc == X86ISD::UMUL ||
19891        Opc == X86ISD::OR || Opc == X86ISD::XOR || Opc == X86ISD::AND))
19892     return true;
19893 
19894   return false;
19895 }
19896 
isTruncWithZeroHighBitsInput(SDValue V,SelectionDAG & DAG)19897 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
19898   if (V.getOpcode() != ISD::TRUNCATE)
19899     return false;
19900 
19901   SDValue VOp0 = V.getOperand(0);
19902   unsigned InBits = VOp0.getValueSizeInBits();
19903   unsigned Bits = V.getValueSizeInBits();
19904   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
19905 }
19906 
LowerSELECT(SDValue Op,SelectionDAG & DAG) const19907 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
19908   bool AddTest = true;
19909   SDValue Cond  = Op.getOperand(0);
19910   SDValue Op1 = Op.getOperand(1);
19911   SDValue Op2 = Op.getOperand(2);
19912   SDLoc DL(Op);
19913   MVT VT = Op1.getSimpleValueType();
19914   SDValue CC;
19915 
19916   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
19917   // are available or VBLENDV if AVX is available.
19918   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
19919   if (Cond.getOpcode() == ISD::SETCC &&
19920       ((Subtarget.hasSSE2() && VT == MVT::f64) ||
19921        (Subtarget.hasSSE1() && VT == MVT::f32)) &&
19922       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
19923     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
19924     unsigned SSECC = translateX86FSETCC(
19925         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
19926 
19927     if (Subtarget.hasAVX512()) {
19928       SDValue Cmp = DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CondOp0,
19929                                 CondOp1, DAG.getConstant(SSECC, DL, MVT::i8));
19930       assert(!VT.isVector() && "Not a scalar type?");
19931       return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
19932     }
19933 
19934     if (SSECC < 8 || Subtarget.hasAVX()) {
19935       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
19936                                 DAG.getConstant(SSECC, DL, MVT::i8));
19937 
19938       // If we have AVX, we can use a variable vector select (VBLENDV) instead
19939       // of 3 logic instructions for size savings and potentially speed.
19940       // Unfortunately, there is no scalar form of VBLENDV.
19941 
19942       // If either operand is a +0.0 constant, don't try this. We can expect to
19943       // optimize away at least one of the logic instructions later in that
19944       // case, so that sequence would be faster than a variable blend.
19945 
19946       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
19947       // uses XMM0 as the selection register. That may need just as many
19948       // instructions as the AND/ANDN/OR sequence due to register moves, so
19949       // don't bother.
19950       if (Subtarget.hasAVX() && !isNullFPConstant(Op1) &&
19951           !isNullFPConstant(Op2)) {
19952         // Convert to vectors, do a VSELECT, and convert back to scalar.
19953         // All of the conversions should be optimized away.
19954         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
19955         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
19956         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
19957         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
19958 
19959         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
19960         VCmp = DAG.getBitcast(VCmpVT, VCmp);
19961 
19962         SDValue VSel = DAG.getSelect(DL, VecVT, VCmp, VOp1, VOp2);
19963 
19964         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
19965                            VSel, DAG.getIntPtrConstant(0, DL));
19966       }
19967       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
19968       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
19969       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
19970     }
19971   }
19972 
19973   // AVX512 fallback is to lower selects of scalar floats to masked moves.
19974   if ((VT == MVT::f64 || VT == MVT::f32) && Subtarget.hasAVX512()) {
19975     SDValue Cmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1, Cond);
19976     return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
19977   }
19978 
19979   // For v64i1 without 64-bit support we need to split and rejoin.
19980   if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
19981     assert(Subtarget.hasBWI() && "Expected BWI to be legal");
19982     SDValue Op1Lo = extractSubVector(Op1, 0, DAG, DL, 32);
19983     SDValue Op2Lo = extractSubVector(Op2, 0, DAG, DL, 32);
19984     SDValue Op1Hi = extractSubVector(Op1, 32, DAG, DL, 32);
19985     SDValue Op2Hi = extractSubVector(Op2, 32, DAG, DL, 32);
19986     SDValue Lo = DAG.getSelect(DL, MVT::v32i1, Cond, Op1Lo, Op2Lo);
19987     SDValue Hi = DAG.getSelect(DL, MVT::v32i1, Cond, Op1Hi, Op2Hi);
19988     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
19989   }
19990 
19991   if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
19992     SDValue Op1Scalar;
19993     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
19994       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
19995     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
19996       Op1Scalar = Op1.getOperand(0);
19997     SDValue Op2Scalar;
19998     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
19999       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
20000     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
20001       Op2Scalar = Op2.getOperand(0);
20002     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
20003       SDValue newSelect = DAG.getSelect(DL, Op1Scalar.getValueType(), Cond,
20004                                         Op1Scalar, Op2Scalar);
20005       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
20006         return DAG.getBitcast(VT, newSelect);
20007       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
20008       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
20009                          DAG.getIntPtrConstant(0, DL));
20010     }
20011   }
20012 
20013   if (Cond.getOpcode() == ISD::SETCC) {
20014     if (SDValue NewCond = LowerSETCC(Cond, DAG)) {
20015       Cond = NewCond;
20016       // If the condition was updated, it's possible that the operands of the
20017       // select were also updated (for example, EmitTest has a RAUW). Refresh
20018       // the local references to the select operands in case they got stale.
20019       Op1 = Op.getOperand(1);
20020       Op2 = Op.getOperand(2);
20021     }
20022   }
20023 
20024   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
20025   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
20026   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
20027   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
20028   // (select (and (x , 0x1) == 0), y, (z ^ y) ) -> (-(and (x , 0x1)) & z ) ^ y
20029   // (select (and (x , 0x1) == 0), y, (z | y) ) -> (-(and (x , 0x1)) & z ) | y
20030   if (Cond.getOpcode() == X86ISD::SETCC &&
20031       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
20032       isNullConstant(Cond.getOperand(1).getOperand(1))) {
20033     SDValue Cmp = Cond.getOperand(1);
20034     unsigned CondCode =
20035         cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
20036 
20037     if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
20038         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
20039       SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
20040       SDValue CmpOp0 = Cmp.getOperand(0);
20041 
20042       // Apply further optimizations for special cases
20043       // (select (x != 0), -1, 0) -> neg & sbb
20044       // (select (x == 0), 0, -1) -> neg & sbb
20045       if (isNullConstant(Y) &&
20046           (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
20047         SDValue Zero = DAG.getConstant(0, DL, CmpOp0.getValueType());
20048         SDValue Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, Zero, CmpOp0);
20049         SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
20050         Zero = DAG.getConstant(0, DL, Op.getValueType());
20051         return DAG.getNode(X86ISD::SBB, DL, VTs, Zero, Zero, Cmp);
20052       }
20053 
20054       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
20055                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
20056       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
20057 
20058       SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
20059       SDValue Zero = DAG.getConstant(0, DL, Op.getValueType());
20060       SDValue Res =   // Res = 0 or -1.
20061         DAG.getNode(X86ISD::SBB, DL, VTs, Zero, Zero, Cmp);
20062 
20063       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
20064         Res = DAG.getNOT(DL, Res, Res.getValueType());
20065 
20066       if (!isNullConstant(Op2))
20067         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
20068       return Res;
20069     } else if (!Subtarget.hasCMov() && CondCode == X86::COND_E &&
20070                Cmp.getOperand(0).getOpcode() == ISD::AND &&
20071                isOneConstant(Cmp.getOperand(0).getOperand(1))) {
20072       SDValue CmpOp0 = Cmp.getOperand(0);
20073       SDValue Src1, Src2;
20074       // true if Op2 is XOR or OR operator and one of its operands
20075       // is equal to Op1
20076       // ( a , a op b) || ( b , a op b)
20077       auto isOrXorPattern = [&]() {
20078         if ((Op2.getOpcode() == ISD::XOR || Op2.getOpcode() == ISD::OR) &&
20079             (Op2.getOperand(0) == Op1 || Op2.getOperand(1) == Op1)) {
20080           Src1 =
20081               Op2.getOperand(0) == Op1 ? Op2.getOperand(1) : Op2.getOperand(0);
20082           Src2 = Op1;
20083           return true;
20084         }
20085         return false;
20086       };
20087 
20088       if (isOrXorPattern()) {
20089         SDValue Neg;
20090         unsigned int CmpSz = CmpOp0.getSimpleValueType().getSizeInBits();
20091         // we need mask of all zeros or ones with same size of the other
20092         // operands.
20093         if (CmpSz > VT.getSizeInBits())
20094           Neg = DAG.getNode(ISD::TRUNCATE, DL, VT, CmpOp0);
20095         else if (CmpSz < VT.getSizeInBits())
20096           Neg = DAG.getNode(ISD::AND, DL, VT,
20097               DAG.getNode(ISD::ANY_EXTEND, DL, VT, CmpOp0.getOperand(0)),
20098               DAG.getConstant(1, DL, VT));
20099         else
20100           Neg = CmpOp0;
20101         SDValue Mask = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
20102                                    Neg); // -(and (x, 0x1))
20103         SDValue And = DAG.getNode(ISD::AND, DL, VT, Mask, Src1); // Mask & z
20104         return DAG.getNode(Op2.getOpcode(), DL, VT, And, Src2);  // And Op y
20105       }
20106     }
20107   }
20108 
20109   // Look past (and (setcc_carry (cmp ...)), 1).
20110   if (Cond.getOpcode() == ISD::AND &&
20111       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
20112       isOneConstant(Cond.getOperand(1)))
20113     Cond = Cond.getOperand(0);
20114 
20115   // If condition flag is set by a X86ISD::CMP, then use it as the condition
20116   // setting operand in place of the X86ISD::SETCC.
20117   unsigned CondOpcode = Cond.getOpcode();
20118   if (CondOpcode == X86ISD::SETCC ||
20119       CondOpcode == X86ISD::SETCC_CARRY) {
20120     CC = Cond.getOperand(0);
20121 
20122     SDValue Cmp = Cond.getOperand(1);
20123     unsigned Opc = Cmp.getOpcode();
20124     MVT VT = Op.getSimpleValueType();
20125 
20126     bool IllegalFPCMov = false;
20127     if (VT.isFloatingPoint() && !VT.isVector() &&
20128         !isScalarFPTypeInSSEReg(VT))  // FPStack?
20129       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
20130 
20131     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
20132         Opc == X86ISD::BT) { // FIXME
20133       Cond = Cmp;
20134       AddTest = false;
20135     }
20136   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
20137              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
20138              CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) {
20139     SDValue Value;
20140     X86::CondCode X86Cond;
20141     std::tie(Value, Cond) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
20142 
20143     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
20144     AddTest = false;
20145   }
20146 
20147   if (AddTest) {
20148     // Look past the truncate if the high bits are known zero.
20149     if (isTruncWithZeroHighBitsInput(Cond, DAG))
20150       Cond = Cond.getOperand(0);
20151 
20152     // We know the result of AND is compared against zero. Try to match
20153     // it to BT.
20154     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
20155       SDValue BTCC;
20156       if (SDValue BT = LowerAndToBT(Cond, ISD::SETNE, DL, DAG, BTCC)) {
20157         CC = BTCC;
20158         Cond = BT;
20159         AddTest = false;
20160       }
20161     }
20162   }
20163 
20164   if (AddTest) {
20165     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
20166     Cond = EmitCmp(Cond, DAG.getConstant(0, DL, Cond.getValueType()),
20167                    X86::COND_NE, DL, DAG);
20168   }
20169 
20170   // a <  b ? -1 :  0 -> RES = ~setcc_carry
20171   // a <  b ?  0 : -1 -> RES = setcc_carry
20172   // a >= b ? -1 :  0 -> RES = setcc_carry
20173   // a >= b ?  0 : -1 -> RES = ~setcc_carry
20174   if (Cond.getOpcode() == X86ISD::SUB) {
20175     Cond = ConvertCmpIfNecessary(Cond, DAG);
20176     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
20177 
20178     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
20179         (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
20180         (isNullConstant(Op1) || isNullConstant(Op2))) {
20181       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
20182                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
20183                                 Cond);
20184       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
20185         return DAG.getNOT(DL, Res, Res.getValueType());
20186       return Res;
20187     }
20188   }
20189 
20190   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
20191   // widen the cmov and push the truncate through. This avoids introducing a new
20192   // branch during isel and doesn't add any extensions.
20193   if (Op.getValueType() == MVT::i8 &&
20194       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
20195     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
20196     if (T1.getValueType() == T2.getValueType() &&
20197         // Blacklist CopyFromReg to avoid partial register stalls.
20198         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
20199       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, T1.getValueType(), T2, T1,
20200                                  CC, Cond);
20201       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
20202     }
20203   }
20204 
20205   // Promote i16 cmovs if it won't prevent folding a load.
20206   if (Op.getValueType() == MVT::i16 && !MayFoldLoad(Op1) && !MayFoldLoad(Op2)) {
20207     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
20208     Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
20209     SDValue Ops[] = { Op2, Op1, CC, Cond };
20210     SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, MVT::i32, Ops);
20211     return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
20212   }
20213 
20214   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
20215   // condition is true.
20216   SDValue Ops[] = { Op2, Op1, CC, Cond };
20217   return DAG.getNode(X86ISD::CMOV, DL, Op.getValueType(), Ops);
20218 }
20219 
LowerSIGN_EXTEND_Mask(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)20220 static SDValue LowerSIGN_EXTEND_Mask(SDValue Op,
20221                                      const X86Subtarget &Subtarget,
20222                                      SelectionDAG &DAG) {
20223   MVT VT = Op->getSimpleValueType(0);
20224   SDValue In = Op->getOperand(0);
20225   MVT InVT = In.getSimpleValueType();
20226   assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!");
20227   MVT VTElt = VT.getVectorElementType();
20228   SDLoc dl(Op);
20229 
20230   unsigned NumElts = VT.getVectorNumElements();
20231 
20232   // Extend VT if the scalar type is i8/i16 and BWI is not supported.
20233   MVT ExtVT = VT;
20234   if (!Subtarget.hasBWI() && VTElt.getSizeInBits() <= 16) {
20235     // If v16i32 is to be avoided, we'll need to split and concatenate.
20236     if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
20237       return SplitAndExtendv16i1(Op.getOpcode(), VT, In, dl, DAG);
20238 
20239     ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
20240   }
20241 
20242   // Widen to 512-bits if VLX is not supported.
20243   MVT WideVT = ExtVT;
20244   if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
20245     NumElts *= 512 / ExtVT.getSizeInBits();
20246     InVT = MVT::getVectorVT(MVT::i1, NumElts);
20247     In = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, InVT, DAG.getUNDEF(InVT),
20248                      In, DAG.getIntPtrConstant(0, dl));
20249     WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(), NumElts);
20250   }
20251 
20252   SDValue V;
20253   MVT WideEltVT = WideVT.getVectorElementType();
20254   if ((Subtarget.hasDQI() && WideEltVT.getSizeInBits() >= 32) ||
20255       (Subtarget.hasBWI() && WideEltVT.getSizeInBits() <= 16)) {
20256     V = DAG.getNode(Op.getOpcode(), dl, WideVT, In);
20257   } else {
20258     SDValue NegOne = DAG.getConstant(-1, dl, WideVT);
20259     SDValue Zero = DAG.getConstant(0, dl, WideVT);
20260     V = DAG.getSelect(dl, WideVT, In, NegOne, Zero);
20261   }
20262 
20263   // Truncate if we had to extend i16/i8 above.
20264   if (VT != ExtVT) {
20265     WideVT = MVT::getVectorVT(VTElt, NumElts);
20266     V = DAG.getNode(ISD::TRUNCATE, dl, WideVT, V);
20267   }
20268 
20269   // Extract back to 128/256-bit if we widened.
20270   if (WideVT != VT)
20271     V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, V,
20272                     DAG.getIntPtrConstant(0, dl));
20273 
20274   return V;
20275 }
20276 
LowerANY_EXTEND(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)20277 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
20278                                SelectionDAG &DAG) {
20279   SDValue In = Op->getOperand(0);
20280   MVT InVT = In.getSimpleValueType();
20281 
20282   if (InVT.getVectorElementType() == MVT::i1)
20283     return LowerSIGN_EXTEND_Mask(Op, Subtarget, DAG);
20284 
20285   assert(Subtarget.hasAVX() && "Expected AVX support");
20286   return LowerAVXExtend(Op, DAG, Subtarget);
20287 }
20288 
20289 // Lowering for SIGN_EXTEND_VECTOR_INREG and ZERO_EXTEND_VECTOR_INREG.
20290 // For sign extend this needs to handle all vector sizes and SSE4.1 and
20291 // non-SSE4.1 targets. For zero extend this should only handle inputs of
20292 // MVT::v64i8 when BWI is not supported, but AVX512 is.
LowerEXTEND_VECTOR_INREG(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)20293 static SDValue LowerEXTEND_VECTOR_INREG(SDValue Op,
20294                                         const X86Subtarget &Subtarget,
20295                                         SelectionDAG &DAG) {
20296   SDValue In = Op->getOperand(0);
20297   MVT VT = Op->getSimpleValueType(0);
20298   MVT InVT = In.getSimpleValueType();
20299 
20300   MVT SVT = VT.getVectorElementType();
20301   MVT InSVT = InVT.getVectorElementType();
20302   assert(SVT.getSizeInBits() > InSVT.getSizeInBits());
20303 
20304   if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16)
20305     return SDValue();
20306   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
20307     return SDValue();
20308   if (!(VT.is128BitVector() && Subtarget.hasSSE2()) &&
20309       !(VT.is256BitVector() && Subtarget.hasAVX()) &&
20310       !(VT.is512BitVector() && Subtarget.hasAVX512()))
20311     return SDValue();
20312 
20313   SDLoc dl(Op);
20314   unsigned Opc = Op.getOpcode();
20315   unsigned NumElts = VT.getVectorNumElements();
20316 
20317   // For 256-bit vectors, we only need the lower (128-bit) half of the input.
20318   // For 512-bit vectors, we need 128-bits or 256-bits.
20319   if (InVT.getSizeInBits() > 128) {
20320     // Input needs to be at least the same number of elements as output, and
20321     // at least 128-bits.
20322     int InSize = InSVT.getSizeInBits() * NumElts;
20323     In = extractSubVector(In, 0, DAG, dl, std::max(InSize, 128));
20324     InVT = In.getSimpleValueType();
20325   }
20326 
20327   // SSE41 targets can use the pmov[sz]x* instructions directly for 128-bit results,
20328   // so are legal and shouldn't occur here. AVX2/AVX512 pmovsx* instructions still
20329   // need to be handled here for 256/512-bit results.
20330   if (Subtarget.hasInt256()) {
20331     assert(VT.getSizeInBits() > 128 && "Unexpected 128-bit vector extension");
20332 
20333     if (InVT.getVectorNumElements() != NumElts)
20334       return DAG.getNode(Op.getOpcode(), dl, VT, In);
20335 
20336     // FIXME: Apparently we create inreg operations that could be regular
20337     // extends.
20338     unsigned ExtOpc =
20339         Opc == ISD::SIGN_EXTEND_VECTOR_INREG ? ISD::SIGN_EXTEND
20340                                              : ISD::ZERO_EXTEND;
20341     return DAG.getNode(ExtOpc, dl, VT, In);
20342   }
20343 
20344   // pre-AVX2 256-bit extensions need to be split into 128-bit instructions.
20345   if (Subtarget.hasAVX()) {
20346     assert(VT.is256BitVector() && "256-bit vector expected");
20347     int HalfNumElts = NumElts / 2;
20348     MVT HalfVT = MVT::getVectorVT(SVT, HalfNumElts);
20349 
20350     unsigned NumSrcElts = InVT.getVectorNumElements();
20351     SmallVector<int, 16> HiMask(NumSrcElts, SM_SentinelUndef);
20352     for (int i = 0; i != HalfNumElts; ++i)
20353       HiMask[i] = HalfNumElts + i;
20354 
20355     SDValue Lo = DAG.getNode(Opc, dl, HalfVT, In);
20356     SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, DAG.getUNDEF(InVT), HiMask);
20357     Hi = DAG.getNode(Opc, dl, HalfVT, Hi);
20358     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
20359   }
20360 
20361   // We should only get here for sign extend.
20362   assert(Opc == ISD::SIGN_EXTEND_VECTOR_INREG && "Unexpected opcode!");
20363   assert(VT.is128BitVector() && InVT.is128BitVector() && "Unexpected VTs");
20364 
20365   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
20366   SDValue Curr = In;
20367   SDValue SignExt = Curr;
20368 
20369   // As SRAI is only available on i16/i32 types, we expand only up to i32
20370   // and handle i64 separately.
20371   if (InVT != MVT::v4i32) {
20372     MVT DestVT = VT == MVT::v2i64 ? MVT::v4i32 : VT;
20373 
20374     unsigned DestWidth = DestVT.getScalarSizeInBits();
20375     unsigned Scale = DestWidth / InSVT.getSizeInBits();
20376 
20377     unsigned InNumElts = InVT.getVectorNumElements();
20378     unsigned DestElts = DestVT.getVectorNumElements();
20379 
20380     // Build a shuffle mask that takes each input element and places it in the
20381     // MSBs of the new element size.
20382     SmallVector<int, 16> Mask(InNumElts, SM_SentinelUndef);
20383     for (unsigned i = 0; i != DestElts; ++i)
20384       Mask[i * Scale + (Scale - 1)] = i;
20385 
20386     Curr = DAG.getVectorShuffle(InVT, dl, In, In, Mask);
20387     Curr = DAG.getBitcast(DestVT, Curr);
20388 
20389     unsigned SignExtShift = DestWidth - InSVT.getSizeInBits();
20390     SignExt = DAG.getNode(X86ISD::VSRAI, dl, DestVT, Curr,
20391                           DAG.getConstant(SignExtShift, dl, MVT::i8));
20392   }
20393 
20394   if (VT == MVT::v2i64) {
20395     assert(Curr.getValueType() == MVT::v4i32 && "Unexpected input VT");
20396     SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
20397     SDValue Sign = DAG.getSetCC(dl, MVT::v4i32, Zero, Curr, ISD::SETGT);
20398     SignExt = DAG.getVectorShuffle(MVT::v4i32, dl, SignExt, Sign, {0, 4, 1, 5});
20399     SignExt = DAG.getBitcast(VT, SignExt);
20400   }
20401 
20402   return SignExt;
20403 }
20404 
LowerSIGN_EXTEND(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)20405 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
20406                                 SelectionDAG &DAG) {
20407   MVT VT = Op->getSimpleValueType(0);
20408   SDValue In = Op->getOperand(0);
20409   MVT InVT = In.getSimpleValueType();
20410   SDLoc dl(Op);
20411 
20412   if (InVT.getVectorElementType() == MVT::i1)
20413     return LowerSIGN_EXTEND_Mask(Op, Subtarget, DAG);
20414 
20415   assert(VT.isVector() && InVT.isVector() && "Expected vector type");
20416   assert(VT.getVectorNumElements() == VT.getVectorNumElements() &&
20417          "Expected same number of elements");
20418   assert((VT.getVectorElementType() == MVT::i16 ||
20419           VT.getVectorElementType() == MVT::i32 ||
20420           VT.getVectorElementType() == MVT::i64) &&
20421          "Unexpected element type");
20422   assert((InVT.getVectorElementType() == MVT::i8 ||
20423           InVT.getVectorElementType() == MVT::i16 ||
20424           InVT.getVectorElementType() == MVT::i32) &&
20425          "Unexpected element type");
20426 
20427   // Custom legalize v8i8->v8i64 on CPUs without avx512bw.
20428   if (InVT == MVT::v8i8) {
20429     if (!ExperimentalVectorWideningLegalization || VT != MVT::v8i64)
20430       return SDValue();
20431 
20432     In = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op),
20433                      MVT::v16i8, In, DAG.getUNDEF(MVT::v8i8));
20434     return DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, VT, In);
20435   }
20436 
20437   if (Subtarget.hasInt256())
20438     return Op;
20439 
20440   // Optimize vectors in AVX mode
20441   // Sign extend  v8i16 to v8i32 and
20442   //              v4i32 to v4i64
20443   //
20444   // Divide input vector into two parts
20445   // for v4i32 the high shuffle mask will be {2, 3, -1, -1}
20446   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
20447   // concat the vectors to original VT
20448 
20449   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
20450                                 VT.getVectorNumElements() / 2);
20451 
20452   SDValue OpLo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, In);
20453 
20454   unsigned NumElems = InVT.getVectorNumElements();
20455   SmallVector<int,8> ShufMask(NumElems, -1);
20456   for (unsigned i = 0; i != NumElems/2; ++i)
20457     ShufMask[i] = i + NumElems/2;
20458 
20459   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
20460   OpHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, OpHi);
20461 
20462   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
20463 }
20464 
LowerStore(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)20465 static SDValue LowerStore(SDValue Op, const X86Subtarget &Subtarget,
20466                           SelectionDAG &DAG) {
20467   StoreSDNode *St = cast<StoreSDNode>(Op.getNode());
20468   SDLoc dl(St);
20469   SDValue StoredVal = St->getValue();
20470 
20471   // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 stores.
20472   if (StoredVal.getValueType().isVector() &&
20473       StoredVal.getValueType().getVectorElementType() == MVT::i1) {
20474     assert(StoredVal.getValueType().getVectorNumElements() <= 8 &&
20475            "Unexpected VT");
20476     assert(!St->isTruncatingStore() && "Expected non-truncating store");
20477     assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
20478            "Expected AVX512F without AVX512DQI");
20479 
20480     StoredVal = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
20481                             DAG.getUNDEF(MVT::v16i1), StoredVal,
20482                             DAG.getIntPtrConstant(0, dl));
20483     StoredVal = DAG.getBitcast(MVT::i16, StoredVal);
20484     StoredVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, StoredVal);
20485 
20486     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
20487                         St->getPointerInfo(), St->getAlignment(),
20488                         St->getMemOperand()->getFlags());
20489   }
20490 
20491   if (St->isTruncatingStore())
20492     return SDValue();
20493 
20494   MVT StoreVT = StoredVal.getSimpleValueType();
20495   assert(StoreVT.isVector() && StoreVT.getSizeInBits() == 64 &&
20496          "Unexpected VT");
20497   if (DAG.getTargetLoweringInfo().getTypeAction(*DAG.getContext(), StoreVT) !=
20498         TargetLowering::TypeWidenVector)
20499     return SDValue();
20500 
20501   // Widen the vector, cast to a v2x64 type, extract the single 64-bit element
20502   // and store it.
20503   MVT WideVT = MVT::getVectorVT(StoreVT.getVectorElementType(),
20504                                 StoreVT.getVectorNumElements() * 2);
20505   StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, StoredVal,
20506                           DAG.getUNDEF(StoreVT));
20507   MVT StVT = Subtarget.is64Bit() && StoreVT.isInteger() ? MVT::i64 : MVT::f64;
20508   MVT CastVT = MVT::getVectorVT(StVT, 2);
20509   StoredVal = DAG.getBitcast(CastVT, StoredVal);
20510   StoredVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, StVT, StoredVal,
20511                           DAG.getIntPtrConstant(0, dl));
20512 
20513   return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
20514                       St->getPointerInfo(), St->getAlignment(),
20515                       St->getMemOperand()->getFlags());
20516 }
20517 
20518 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
20519 // may emit an illegal shuffle but the expansion is still better than scalar
20520 // code. We generate sext/sext_invec for SEXTLOADs if it's available, otherwise
20521 // we'll emit a shuffle and a arithmetic shift.
20522 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
20523 // TODO: It is possible to support ZExt by zeroing the undef values during
20524 // the shuffle phase or after the shuffle.
LowerLoad(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)20525 static SDValue LowerLoad(SDValue Op, const X86Subtarget &Subtarget,
20526                                  SelectionDAG &DAG) {
20527   MVT RegVT = Op.getSimpleValueType();
20528   assert(RegVT.isVector() && "We only custom lower vector loads.");
20529   assert(RegVT.isInteger() &&
20530          "We only custom lower integer vector loads.");
20531 
20532   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
20533   SDLoc dl(Ld);
20534   EVT MemVT = Ld->getMemoryVT();
20535 
20536   // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 loads.
20537   if (RegVT.getVectorElementType() == MVT::i1) {
20538     assert(EVT(RegVT) == MemVT && "Expected non-extending load");
20539     assert(RegVT.getVectorNumElements() <= 8 && "Unexpected VT");
20540     assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
20541            "Expected AVX512F without AVX512DQI");
20542 
20543     SDValue NewLd = DAG.getLoad(MVT::i8, dl, Ld->getChain(), Ld->getBasePtr(),
20544                                 Ld->getPointerInfo(), Ld->getAlignment(),
20545                                 Ld->getMemOperand()->getFlags());
20546 
20547     // Replace chain users with the new chain.
20548     assert(NewLd->getNumValues() == 2 && "Loads must carry a chain!");
20549 
20550     SDValue Val = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i16, NewLd);
20551     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, RegVT,
20552                       DAG.getBitcast(MVT::v16i1, Val),
20553                       DAG.getIntPtrConstant(0, dl));
20554     return DAG.getMergeValues({Val, NewLd.getValue(1)}, dl);
20555   }
20556 
20557   // Nothing useful we can do without SSE2 shuffles.
20558   assert(Subtarget.hasSSE2() && "We only custom lower sext loads with SSE2.");
20559 
20560   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20561   unsigned RegSz = RegVT.getSizeInBits();
20562 
20563   ISD::LoadExtType Ext = Ld->getExtensionType();
20564 
20565   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
20566          && "Only anyext and sext are currently implemented.");
20567   assert(MemVT != RegVT && "Cannot extend to the same type");
20568   assert(MemVT.isVector() && "Must load a vector from memory");
20569 
20570   unsigned NumElems = RegVT.getVectorNumElements();
20571   unsigned MemSz = MemVT.getSizeInBits();
20572   assert(RegSz > MemSz && "Register size must be greater than the mem size");
20573 
20574   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget.hasInt256()) {
20575     // The only way in which we have a legal 256-bit vector result but not the
20576     // integer 256-bit operations needed to directly lower a sextload is if we
20577     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
20578     // a 128-bit vector and a normal sign_extend to 256-bits that should get
20579     // correctly legalized. We do this late to allow the canonical form of
20580     // sextload to persist throughout the rest of the DAG combiner -- it wants
20581     // to fold together any extensions it can, and so will fuse a sign_extend
20582     // of an sextload into a sextload targeting a wider value.
20583     SDValue Load;
20584     if (MemSz == 128) {
20585       // Just switch this to a normal load.
20586       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
20587                                        "it must be a legal 128-bit vector "
20588                                        "type!");
20589       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
20590                          Ld->getPointerInfo(), Ld->getAlignment(),
20591                          Ld->getMemOperand()->getFlags());
20592     } else {
20593       assert(MemSz < 128 &&
20594              "Can't extend a type wider than 128 bits to a 256 bit vector!");
20595       // Do an sext load to a 128-bit vector type. We want to use the same
20596       // number of elements, but elements half as wide. This will end up being
20597       // recursively lowered by this routine, but will succeed as we definitely
20598       // have all the necessary features if we're using AVX1.
20599       EVT HalfEltVT =
20600           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
20601       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
20602       Load =
20603           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
20604                          Ld->getPointerInfo(), MemVT, Ld->getAlignment(),
20605                          Ld->getMemOperand()->getFlags());
20606     }
20607 
20608     // Replace chain users with the new chain.
20609     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
20610 
20611     // Finally, do a normal sign-extend to the desired register.
20612     SDValue SExt = DAG.getSExtOrTrunc(Load, dl, RegVT);
20613     return DAG.getMergeValues({SExt, Load.getValue(1)}, dl);
20614   }
20615 
20616   // All sizes must be a power of two.
20617   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
20618          "Non-power-of-two elements are not custom lowered!");
20619 
20620   // Attempt to load the original value using scalar loads.
20621   // Find the largest scalar type that divides the total loaded size.
20622   MVT SclrLoadTy = MVT::i8;
20623   for (MVT Tp : MVT::integer_valuetypes()) {
20624     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
20625       SclrLoadTy = Tp;
20626     }
20627   }
20628 
20629   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20630   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
20631       (64 <= MemSz))
20632     SclrLoadTy = MVT::f64;
20633 
20634   // Calculate the number of scalar loads that we need to perform
20635   // in order to load our vector from memory.
20636   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
20637 
20638   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
20639          "Can only lower sext loads with a single scalar load!");
20640 
20641   unsigned loadRegSize = RegSz;
20642   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
20643     loadRegSize = 128;
20644 
20645   // If we don't have BWI we won't be able to create the shuffle needed for
20646   // v8i8->v8i64.
20647   if (Ext == ISD::EXTLOAD && !Subtarget.hasBWI() && RegVT == MVT::v8i64 &&
20648       MemVT == MVT::v8i8)
20649     loadRegSize = 128;
20650 
20651   // Represent our vector as a sequence of elements which are the
20652   // largest scalar that we can load.
20653   EVT LoadUnitVecVT = EVT::getVectorVT(
20654       *DAG.getContext(), SclrLoadTy, loadRegSize / SclrLoadTy.getSizeInBits());
20655 
20656   // Represent the data using the same element type that is stored in
20657   // memory. In practice, we ''widen'' MemVT.
20658   EVT WideVecVT =
20659       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20660                        loadRegSize / MemVT.getScalarSizeInBits());
20661 
20662   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
20663          "Invalid vector type");
20664 
20665   // We can't shuffle using an illegal type.
20666   assert(TLI.isTypeLegal(WideVecVT) &&
20667          "We only lower types that form legal widened vector types");
20668 
20669   SmallVector<SDValue, 8> Chains;
20670   SDValue Ptr = Ld->getBasePtr();
20671   unsigned OffsetInc = SclrLoadTy.getSizeInBits() / 8;
20672   SDValue Increment = DAG.getConstant(OffsetInc, dl,
20673                                       TLI.getPointerTy(DAG.getDataLayout()));
20674   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
20675 
20676   unsigned Offset = 0;
20677   for (unsigned i = 0; i < NumLoads; ++i) {
20678     unsigned NewAlign = MinAlign(Ld->getAlignment(), Offset);
20679 
20680     // Perform a single load.
20681     SDValue ScalarLoad =
20682       DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr,
20683                   Ld->getPointerInfo().getWithOffset(Offset),
20684                   NewAlign, Ld->getMemOperand()->getFlags());
20685     Chains.push_back(ScalarLoad.getValue(1));
20686     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
20687     // another round of DAGCombining.
20688     if (i == 0)
20689       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
20690     else
20691       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
20692                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
20693 
20694     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20695     Offset += OffsetInc;
20696   }
20697 
20698   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20699 
20700   // Bitcast the loaded value to a vector of the original element type, in
20701   // the size of the target vector type.
20702   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
20703   unsigned SizeRatio = RegSz / MemSz;
20704 
20705   if (Ext == ISD::SEXTLOAD) {
20706     SDValue Sext = getExtendInVec(/*Signed*/true, dl, RegVT, SlicedVec, DAG);
20707     return DAG.getMergeValues({Sext, TF}, dl);
20708   }
20709 
20710   if (Ext == ISD::EXTLOAD && !Subtarget.hasBWI() && RegVT == MVT::v8i64 &&
20711       MemVT == MVT::v8i8) {
20712     SDValue Sext = getExtendInVec(/*Signed*/false, dl, RegVT, SlicedVec, DAG);
20713     return DAG.getMergeValues({Sext, TF}, dl);
20714   }
20715 
20716   // Redistribute the loaded elements into the different locations.
20717   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
20718   for (unsigned i = 0; i != NumElems; ++i)
20719     ShuffleVec[i * SizeRatio] = i;
20720 
20721   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20722                                        DAG.getUNDEF(WideVecVT), ShuffleVec);
20723 
20724   // Bitcast to the requested type.
20725   Shuff = DAG.getBitcast(RegVT, Shuff);
20726   return DAG.getMergeValues({Shuff, TF}, dl);
20727 }
20728 
20729 /// Return true if node is an ISD::AND or ISD::OR of two X86ISD::SETCC nodes
20730 /// each of which has no other use apart from the AND / OR.
isAndOrOfSetCCs(SDValue Op,unsigned & Opc)20731 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
20732   Opc = Op.getOpcode();
20733   if (Opc != ISD::OR && Opc != ISD::AND)
20734     return false;
20735   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
20736           Op.getOperand(0).hasOneUse() &&
20737           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
20738           Op.getOperand(1).hasOneUse());
20739 }
20740 
20741 /// Return true if node is an ISD::XOR of a X86ISD::SETCC and 1 and that the
20742 /// SETCC node has a single use.
isXor1OfSetCC(SDValue Op)20743 static bool isXor1OfSetCC(SDValue Op) {
20744   if (Op.getOpcode() != ISD::XOR)
20745     return false;
20746   if (isOneConstant(Op.getOperand(1)))
20747     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
20748            Op.getOperand(0).hasOneUse();
20749   return false;
20750 }
20751 
LowerBRCOND(SDValue Op,SelectionDAG & DAG) const20752 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
20753   bool addTest = true;
20754   SDValue Chain = Op.getOperand(0);
20755   SDValue Cond  = Op.getOperand(1);
20756   SDValue Dest  = Op.getOperand(2);
20757   SDLoc dl(Op);
20758   SDValue CC;
20759   bool Inverted = false;
20760 
20761   if (Cond.getOpcode() == ISD::SETCC) {
20762     // Check for setcc([su]{add,sub,mul}o == 0).
20763     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
20764         isNullConstant(Cond.getOperand(1)) &&
20765         Cond.getOperand(0).getResNo() == 1 &&
20766         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
20767          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
20768          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
20769          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
20770          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
20771          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
20772       Inverted = true;
20773       Cond = Cond.getOperand(0);
20774     } else {
20775       if (SDValue NewCond = LowerSETCC(Cond, DAG))
20776         Cond = NewCond;
20777     }
20778   }
20779 #if 0
20780   // FIXME: LowerXALUO doesn't handle these!!
20781   else if (Cond.getOpcode() == X86ISD::ADD  ||
20782            Cond.getOpcode() == X86ISD::SUB  ||
20783            Cond.getOpcode() == X86ISD::SMUL ||
20784            Cond.getOpcode() == X86ISD::UMUL)
20785     Cond = LowerXALUO(Cond, DAG);
20786 #endif
20787 
20788   // Look pass (and (setcc_carry (cmp ...)), 1).
20789   if (Cond.getOpcode() == ISD::AND &&
20790       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
20791       isOneConstant(Cond.getOperand(1)))
20792     Cond = Cond.getOperand(0);
20793 
20794   // If condition flag is set by a X86ISD::CMP, then use it as the condition
20795   // setting operand in place of the X86ISD::SETCC.
20796   unsigned CondOpcode = Cond.getOpcode();
20797   if (CondOpcode == X86ISD::SETCC ||
20798       CondOpcode == X86ISD::SETCC_CARRY) {
20799     CC = Cond.getOperand(0);
20800 
20801     SDValue Cmp = Cond.getOperand(1);
20802     unsigned Opc = Cmp.getOpcode();
20803     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
20804     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
20805       Cond = Cmp;
20806       addTest = false;
20807     } else {
20808       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
20809       default: break;
20810       case X86::COND_O:
20811       case X86::COND_B:
20812         // These can only come from an arithmetic instruction with overflow,
20813         // e.g. SADDO, UADDO.
20814         Cond = Cond.getOperand(1);
20815         addTest = false;
20816         break;
20817       }
20818     }
20819   }
20820   CondOpcode = Cond.getOpcode();
20821   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
20822       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
20823       CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) {
20824     SDValue Value;
20825     X86::CondCode X86Cond;
20826     std::tie(Value, Cond) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
20827 
20828     if (Inverted)
20829       X86Cond = X86::GetOppositeBranchCondition(X86Cond);
20830 
20831     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
20832     addTest = false;
20833   } else {
20834     unsigned CondOpc;
20835     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
20836       SDValue Cmp = Cond.getOperand(0).getOperand(1);
20837       if (CondOpc == ISD::OR) {
20838         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
20839         // two branches instead of an explicit OR instruction with a
20840         // separate test.
20841         if (Cmp == Cond.getOperand(1).getOperand(1) &&
20842             isX86LogicalCmp(Cmp)) {
20843           CC = Cond.getOperand(0).getOperand(0);
20844           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
20845                               Chain, Dest, CC, Cmp);
20846           CC = Cond.getOperand(1).getOperand(0);
20847           Cond = Cmp;
20848           addTest = false;
20849         }
20850       } else { // ISD::AND
20851         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
20852         // two branches instead of an explicit AND instruction with a
20853         // separate test. However, we only do this if this block doesn't
20854         // have a fall-through edge, because this requires an explicit
20855         // jmp when the condition is false.
20856         if (Cmp == Cond.getOperand(1).getOperand(1) &&
20857             isX86LogicalCmp(Cmp) &&
20858             Op.getNode()->hasOneUse()) {
20859           X86::CondCode CCode =
20860             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
20861           CCode = X86::GetOppositeBranchCondition(CCode);
20862           CC = DAG.getConstant(CCode, dl, MVT::i8);
20863           SDNode *User = *Op.getNode()->use_begin();
20864           // Look for an unconditional branch following this conditional branch.
20865           // We need this because we need to reverse the successors in order
20866           // to implement FCMP_OEQ.
20867           if (User->getOpcode() == ISD::BR) {
20868             SDValue FalseBB = User->getOperand(1);
20869             SDNode *NewBR =
20870               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
20871             assert(NewBR == User);
20872             (void)NewBR;
20873             Dest = FalseBB;
20874 
20875             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
20876                                 Chain, Dest, CC, Cmp);
20877             X86::CondCode CCode =
20878               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
20879             CCode = X86::GetOppositeBranchCondition(CCode);
20880             CC = DAG.getConstant(CCode, dl, MVT::i8);
20881             Cond = Cmp;
20882             addTest = false;
20883           }
20884         }
20885       }
20886     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
20887       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
20888       // It should be transformed during dag combiner except when the condition
20889       // is set by a arithmetics with overflow node.
20890       X86::CondCode CCode =
20891         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
20892       CCode = X86::GetOppositeBranchCondition(CCode);
20893       CC = DAG.getConstant(CCode, dl, MVT::i8);
20894       Cond = Cond.getOperand(0).getOperand(1);
20895       addTest = false;
20896     } else if (Cond.getOpcode() == ISD::SETCC &&
20897                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
20898       // For FCMP_OEQ, we can emit
20899       // two branches instead of an explicit AND instruction with a
20900       // separate test. However, we only do this if this block doesn't
20901       // have a fall-through edge, because this requires an explicit
20902       // jmp when the condition is false.
20903       if (Op.getNode()->hasOneUse()) {
20904         SDNode *User = *Op.getNode()->use_begin();
20905         // Look for an unconditional branch following this conditional branch.
20906         // We need this because we need to reverse the successors in order
20907         // to implement FCMP_OEQ.
20908         if (User->getOpcode() == ISD::BR) {
20909           SDValue FalseBB = User->getOperand(1);
20910           SDNode *NewBR =
20911             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
20912           assert(NewBR == User);
20913           (void)NewBR;
20914           Dest = FalseBB;
20915 
20916           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
20917                                     Cond.getOperand(0), Cond.getOperand(1));
20918           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
20919           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
20920           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
20921                               Chain, Dest, CC, Cmp);
20922           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
20923           Cond = Cmp;
20924           addTest = false;
20925         }
20926       }
20927     } else if (Cond.getOpcode() == ISD::SETCC &&
20928                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
20929       // For FCMP_UNE, we can emit
20930       // two branches instead of an explicit OR instruction with a
20931       // separate test.
20932       SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
20933                                 Cond.getOperand(0), Cond.getOperand(1));
20934       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
20935       CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
20936       Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
20937                           Chain, Dest, CC, Cmp);
20938       CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
20939       Cond = Cmp;
20940       addTest = false;
20941     }
20942   }
20943 
20944   if (addTest) {
20945     // Look pass the truncate if the high bits are known zero.
20946     if (isTruncWithZeroHighBitsInput(Cond, DAG))
20947         Cond = Cond.getOperand(0);
20948 
20949     // We know the result of AND is compared against zero. Try to match
20950     // it to BT.
20951     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
20952       SDValue BTCC;
20953       if (SDValue BT = LowerAndToBT(Cond, ISD::SETNE, dl, DAG, BTCC)) {
20954         CC = BTCC;
20955         Cond = BT;
20956         addTest = false;
20957       }
20958     }
20959   }
20960 
20961   if (addTest) {
20962     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
20963     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
20964     Cond = EmitCmp(Cond, DAG.getConstant(0, dl, Cond.getValueType()),
20965                    X86Cond, dl, DAG);
20966   }
20967   Cond = ConvertCmpIfNecessary(Cond, DAG);
20968   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
20969                      Chain, Dest, CC, Cond);
20970 }
20971 
20972 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
20973 // Calls to _alloca are needed to probe the stack when allocating more than 4k
20974 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
20975 // that the guard pages used by the OS virtual memory manager are allocated in
20976 // correct sequence.
20977 SDValue
LowerDYNAMIC_STACKALLOC(SDValue Op,SelectionDAG & DAG) const20978 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
20979                                            SelectionDAG &DAG) const {
20980   MachineFunction &MF = DAG.getMachineFunction();
20981   bool SplitStack = MF.shouldSplitStack();
20982   bool EmitStackProbe = !getStackProbeSymbolName(MF).empty();
20983   bool Lower = (Subtarget.isOSWindows() && !Subtarget.isTargetMachO()) ||
20984                SplitStack || EmitStackProbe;
20985   SDLoc dl(Op);
20986 
20987   // Get the inputs.
20988   SDNode *Node = Op.getNode();
20989   SDValue Chain = Op.getOperand(0);
20990   SDValue Size  = Op.getOperand(1);
20991   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
20992   EVT VT = Node->getValueType(0);
20993 
20994   // Chain the dynamic stack allocation so that it doesn't modify the stack
20995   // pointer when other instructions are using the stack.
20996   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
20997 
20998   bool Is64Bit = Subtarget.is64Bit();
20999   MVT SPTy = getPointerTy(DAG.getDataLayout());
21000 
21001   SDValue Result;
21002   if (!Lower) {
21003     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21004     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
21005     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
21006                     " not tell us which reg is the stack pointer!");
21007 
21008     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
21009     Chain = SP.getValue(1);
21010     const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
21011     unsigned StackAlign = TFI.getStackAlignment();
21012     Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
21013     if (Align > StackAlign)
21014       Result = DAG.getNode(ISD::AND, dl, VT, Result,
21015                          DAG.getConstant(-(uint64_t)Align, dl, VT));
21016     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
21017   } else if (SplitStack) {
21018     MachineRegisterInfo &MRI = MF.getRegInfo();
21019 
21020     if (Is64Bit) {
21021       // The 64 bit implementation of segmented stacks needs to clobber both r10
21022       // r11. This makes it impossible to use it along with nested parameters.
21023       const Function &F = MF.getFunction();
21024       for (const auto &A : F.args()) {
21025         if (A.hasNestAttr())
21026           report_fatal_error("Cannot use segmented stacks with functions that "
21027                              "have nested arguments.");
21028       }
21029     }
21030 
21031     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
21032     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
21033     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
21034     Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
21035                                 DAG.getRegister(Vreg, SPTy));
21036   } else {
21037     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
21038     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Size);
21039     MF.getInfo<X86MachineFunctionInfo>()->setHasWinAlloca(true);
21040 
21041     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
21042     unsigned SPReg = RegInfo->getStackRegister();
21043     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
21044     Chain = SP.getValue(1);
21045 
21046     if (Align) {
21047       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
21048                        DAG.getConstant(-(uint64_t)Align, dl, VT));
21049       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
21050     }
21051 
21052     Result = SP;
21053   }
21054 
21055   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
21056                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
21057 
21058   SDValue Ops[2] = {Result, Chain};
21059   return DAG.getMergeValues(Ops, dl);
21060 }
21061 
LowerVASTART(SDValue Op,SelectionDAG & DAG) const21062 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
21063   MachineFunction &MF = DAG.getMachineFunction();
21064   auto PtrVT = getPointerTy(MF.getDataLayout());
21065   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
21066 
21067   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
21068   SDLoc DL(Op);
21069 
21070   if (!Subtarget.is64Bit() ||
21071       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv())) {
21072     // vastart just stores the address of the VarArgsFrameIndex slot into the
21073     // memory location argument.
21074     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
21075     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
21076                         MachinePointerInfo(SV));
21077   }
21078 
21079   // __va_list_tag:
21080   //   gp_offset         (0 - 6 * 8)
21081   //   fp_offset         (48 - 48 + 8 * 16)
21082   //   overflow_arg_area (point to parameters coming in memory).
21083   //   reg_save_area
21084   SmallVector<SDValue, 8> MemOps;
21085   SDValue FIN = Op.getOperand(1);
21086   // Store gp_offset
21087   SDValue Store = DAG.getStore(
21088       Op.getOperand(0), DL,
21089       DAG.getConstant(FuncInfo->getVarArgsGPOffset(), DL, MVT::i32), FIN,
21090       MachinePointerInfo(SV));
21091   MemOps.push_back(Store);
21092 
21093   // Store fp_offset
21094   FIN = DAG.getMemBasePlusOffset(FIN, 4, DL);
21095   Store = DAG.getStore(
21096       Op.getOperand(0), DL,
21097       DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL, MVT::i32), FIN,
21098       MachinePointerInfo(SV, 4));
21099   MemOps.push_back(Store);
21100 
21101   // Store ptr to overflow_arg_area
21102   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
21103   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
21104   Store =
21105       DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, MachinePointerInfo(SV, 8));
21106   MemOps.push_back(Store);
21107 
21108   // Store ptr to reg_save_area.
21109   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
21110       Subtarget.isTarget64BitLP64() ? 8 : 4, DL));
21111   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
21112   Store = DAG.getStore(
21113       Op.getOperand(0), DL, RSFIN, FIN,
21114       MachinePointerInfo(SV, Subtarget.isTarget64BitLP64() ? 16 : 12));
21115   MemOps.push_back(Store);
21116   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
21117 }
21118 
LowerVAARG(SDValue Op,SelectionDAG & DAG) const21119 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
21120   assert(Subtarget.is64Bit() &&
21121          "LowerVAARG only handles 64-bit va_arg!");
21122   assert(Op.getNumOperands() == 4);
21123 
21124   MachineFunction &MF = DAG.getMachineFunction();
21125   if (Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()))
21126     // The Win64 ABI uses char* instead of a structure.
21127     return DAG.expandVAArg(Op.getNode());
21128 
21129   SDValue Chain = Op.getOperand(0);
21130   SDValue SrcPtr = Op.getOperand(1);
21131   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
21132   unsigned Align = Op.getConstantOperandVal(3);
21133   SDLoc dl(Op);
21134 
21135   EVT ArgVT = Op.getNode()->getValueType(0);
21136   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
21137   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
21138   uint8_t ArgMode;
21139 
21140   // Decide which area this value should be read from.
21141   // TODO: Implement the AMD64 ABI in its entirety. This simple
21142   // selection mechanism works only for the basic types.
21143   if (ArgVT == MVT::f80) {
21144     llvm_unreachable("va_arg for f80 not yet implemented");
21145   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
21146     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
21147   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
21148     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
21149   } else {
21150     llvm_unreachable("Unhandled argument type in LowerVAARG");
21151   }
21152 
21153   if (ArgMode == 2) {
21154     // Sanity Check: Make sure using fp_offset makes sense.
21155     assert(!Subtarget.useSoftFloat() &&
21156            !(MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat)) &&
21157            Subtarget.hasSSE1());
21158   }
21159 
21160   // Insert VAARG_64 node into the DAG
21161   // VAARG_64 returns two values: Variable Argument Address, Chain
21162   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
21163                        DAG.getConstant(ArgMode, dl, MVT::i8),
21164                        DAG.getConstant(Align, dl, MVT::i32)};
21165   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
21166   SDValue VAARG = DAG.getMemIntrinsicNode(
21167     X86ISD::VAARG_64, dl,
21168     VTs, InstOps, MVT::i64,
21169     MachinePointerInfo(SV),
21170     /*Align=*/0,
21171     MachineMemOperand::MOLoad | MachineMemOperand::MOStore);
21172   Chain = VAARG.getValue(1);
21173 
21174   // Load the next argument and return it
21175   return DAG.getLoad(ArgVT, dl, Chain, VAARG, MachinePointerInfo());
21176 }
21177 
LowerVACOPY(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)21178 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget &Subtarget,
21179                            SelectionDAG &DAG) {
21180   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
21181   // where a va_list is still an i8*.
21182   assert(Subtarget.is64Bit() && "This code only handles 64-bit va_copy!");
21183   if (Subtarget.isCallingConvWin64(
21184         DAG.getMachineFunction().getFunction().getCallingConv()))
21185     // Probably a Win64 va_copy.
21186     return DAG.expandVACopy(Op.getNode());
21187 
21188   SDValue Chain = Op.getOperand(0);
21189   SDValue DstPtr = Op.getOperand(1);
21190   SDValue SrcPtr = Op.getOperand(2);
21191   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
21192   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
21193   SDLoc DL(Op);
21194 
21195   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
21196                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
21197                        false, false,
21198                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
21199 }
21200 
21201 // Helper to get immediate/variable SSE shift opcode from other shift opcodes.
getTargetVShiftUniformOpcode(unsigned Opc,bool IsVariable)21202 static unsigned getTargetVShiftUniformOpcode(unsigned Opc, bool IsVariable) {
21203   switch (Opc) {
21204   case ISD::SHL:
21205   case X86ISD::VSHL:
21206   case X86ISD::VSHLI:
21207     return IsVariable ? X86ISD::VSHL : X86ISD::VSHLI;
21208   case ISD::SRL:
21209   case X86ISD::VSRL:
21210   case X86ISD::VSRLI:
21211     return IsVariable ? X86ISD::VSRL : X86ISD::VSRLI;
21212   case ISD::SRA:
21213   case X86ISD::VSRA:
21214   case X86ISD::VSRAI:
21215     return IsVariable ? X86ISD::VSRA : X86ISD::VSRAI;
21216   }
21217   llvm_unreachable("Unknown target vector shift node");
21218 }
21219 
21220 /// Handle vector element shifts where the shift amount is a constant.
21221 /// Takes immediate version of shift as input.
getTargetVShiftByConstNode(unsigned Opc,const SDLoc & dl,MVT VT,SDValue SrcOp,uint64_t ShiftAmt,SelectionDAG & DAG)21222 static SDValue getTargetVShiftByConstNode(unsigned Opc, const SDLoc &dl, MVT VT,
21223                                           SDValue SrcOp, uint64_t ShiftAmt,
21224                                           SelectionDAG &DAG) {
21225   MVT ElementType = VT.getVectorElementType();
21226 
21227   // Bitcast the source vector to the output type, this is mainly necessary for
21228   // vXi8/vXi64 shifts.
21229   if (VT != SrcOp.getSimpleValueType())
21230     SrcOp = DAG.getBitcast(VT, SrcOp);
21231 
21232   // Fold this packed shift into its first operand if ShiftAmt is 0.
21233   if (ShiftAmt == 0)
21234     return SrcOp;
21235 
21236   // Check for ShiftAmt >= element width
21237   if (ShiftAmt >= ElementType.getSizeInBits()) {
21238     if (Opc == X86ISD::VSRAI)
21239       ShiftAmt = ElementType.getSizeInBits() - 1;
21240     else
21241       return DAG.getConstant(0, dl, VT);
21242   }
21243 
21244   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
21245          && "Unknown target vector shift-by-constant node");
21246 
21247   // Fold this packed vector shift into a build vector if SrcOp is a
21248   // vector of Constants or UNDEFs.
21249   if (ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
21250     SmallVector<SDValue, 8> Elts;
21251     unsigned NumElts = SrcOp->getNumOperands();
21252     ConstantSDNode *ND;
21253 
21254     switch(Opc) {
21255     default: llvm_unreachable("Unknown opcode!");
21256     case X86ISD::VSHLI:
21257       for (unsigned i=0; i!=NumElts; ++i) {
21258         SDValue CurrentOp = SrcOp->getOperand(i);
21259         if (CurrentOp->isUndef()) {
21260           Elts.push_back(CurrentOp);
21261           continue;
21262         }
21263         ND = cast<ConstantSDNode>(CurrentOp);
21264         const APInt &C = ND->getAPIntValue();
21265         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
21266       }
21267       break;
21268     case X86ISD::VSRLI:
21269       for (unsigned i=0; i!=NumElts; ++i) {
21270         SDValue CurrentOp = SrcOp->getOperand(i);
21271         if (CurrentOp->isUndef()) {
21272           Elts.push_back(CurrentOp);
21273           continue;
21274         }
21275         ND = cast<ConstantSDNode>(CurrentOp);
21276         const APInt &C = ND->getAPIntValue();
21277         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
21278       }
21279       break;
21280     case X86ISD::VSRAI:
21281       for (unsigned i=0; i!=NumElts; ++i) {
21282         SDValue CurrentOp = SrcOp->getOperand(i);
21283         if (CurrentOp->isUndef()) {
21284           Elts.push_back(CurrentOp);
21285           continue;
21286         }
21287         ND = cast<ConstantSDNode>(CurrentOp);
21288         const APInt &C = ND->getAPIntValue();
21289         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
21290       }
21291       break;
21292     }
21293 
21294     return DAG.getBuildVector(VT, dl, Elts);
21295   }
21296 
21297   return DAG.getNode(Opc, dl, VT, SrcOp,
21298                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
21299 }
21300 
21301 /// Handle vector element shifts where the shift amount may or may not be a
21302 /// constant. Takes immediate version of shift as input.
getTargetVShiftNode(unsigned Opc,const SDLoc & dl,MVT VT,SDValue SrcOp,SDValue ShAmt,const X86Subtarget & Subtarget,SelectionDAG & DAG)21303 static SDValue getTargetVShiftNode(unsigned Opc, const SDLoc &dl, MVT VT,
21304                                    SDValue SrcOp, SDValue ShAmt,
21305                                    const X86Subtarget &Subtarget,
21306                                    SelectionDAG &DAG) {
21307   MVT SVT = ShAmt.getSimpleValueType();
21308   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
21309 
21310   // Catch shift-by-constant.
21311   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
21312     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
21313                                       CShAmt->getZExtValue(), DAG);
21314 
21315   // Change opcode to non-immediate version.
21316   Opc = getTargetVShiftUniformOpcode(Opc, true);
21317 
21318   // Need to build a vector containing shift amount.
21319   // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
21320   // +====================+============+=======================================+
21321   // | ShAmt is           | HasSSE4.1? | Construct ShAmt vector as             |
21322   // +====================+============+=======================================+
21323   // | i64                | Yes, No    | Use ShAmt as lowest elt               |
21324   // | i32                | Yes        | zero-extend in-reg                    |
21325   // | (i32 zext(i16/i8)) | Yes        | zero-extend in-reg                    |
21326   // | (i32 zext(i16/i8)) | No         | byte-shift-in-reg                     |
21327   // | i16/i32            | No         | v4i32 build_vector(ShAmt, 0, ud, ud)) |
21328   // +====================+============+=======================================+
21329 
21330   if (SVT == MVT::i64)
21331     ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), MVT::v2i64, ShAmt);
21332   else if (ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
21333            ShAmt.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
21334            (ShAmt.getOperand(0).getSimpleValueType() == MVT::i16 ||
21335             ShAmt.getOperand(0).getSimpleValueType() == MVT::i8)) {
21336     ShAmt = ShAmt.getOperand(0);
21337     MVT AmtTy = ShAmt.getSimpleValueType() == MVT::i8 ? MVT::v16i8 : MVT::v8i16;
21338     ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), AmtTy, ShAmt);
21339     if (Subtarget.hasSSE41())
21340       ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
21341                           MVT::v2i64, ShAmt);
21342     else {
21343       SDValue ByteShift = DAG.getConstant(
21344           (128 - AmtTy.getScalarSizeInBits()) / 8, SDLoc(ShAmt), MVT::i8);
21345       ShAmt = DAG.getBitcast(MVT::v16i8, ShAmt);
21346       ShAmt = DAG.getNode(X86ISD::VSHLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
21347                           ByteShift);
21348       ShAmt = DAG.getNode(X86ISD::VSRLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
21349                           ByteShift);
21350     }
21351   } else if (Subtarget.hasSSE41() &&
21352              ShAmt.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
21353     ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), MVT::v4i32, ShAmt);
21354     ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
21355                         MVT::v2i64, ShAmt);
21356   } else {
21357     SDValue ShOps[4] = {ShAmt, DAG.getConstant(0, dl, SVT), DAG.getUNDEF(SVT),
21358                         DAG.getUNDEF(SVT)};
21359     ShAmt = DAG.getBuildVector(MVT::v4i32, dl, ShOps);
21360   }
21361 
21362   // The return type has to be a 128-bit type with the same element
21363   // type as the input type.
21364   MVT EltVT = VT.getVectorElementType();
21365   MVT ShVT = MVT::getVectorVT(EltVT, 128 / EltVT.getSizeInBits());
21366 
21367   ShAmt = DAG.getBitcast(ShVT, ShAmt);
21368   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
21369 }
21370 
21371 /// Return Mask with the necessary casting or extending
21372 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
getMaskNode(SDValue Mask,MVT MaskVT,const X86Subtarget & Subtarget,SelectionDAG & DAG,const SDLoc & dl)21373 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
21374                            const X86Subtarget &Subtarget, SelectionDAG &DAG,
21375                            const SDLoc &dl) {
21376 
21377   if (isAllOnesConstant(Mask))
21378     return DAG.getConstant(1, dl, MaskVT);
21379   if (X86::isZeroNode(Mask))
21380     return DAG.getConstant(0, dl, MaskVT);
21381 
21382   assert(MaskVT.bitsLE(Mask.getSimpleValueType()) && "Unexpected mask size!");
21383 
21384   if (Mask.getSimpleValueType() == MVT::i64 && Subtarget.is32Bit()) {
21385     assert(MaskVT == MVT::v64i1 && "Expected v64i1 mask!");
21386     assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
21387     // In case 32bit mode, bitcast i64 is illegal, extend/split it.
21388     SDValue Lo, Hi;
21389     Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
21390                         DAG.getConstant(0, dl, MVT::i32));
21391     Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
21392                         DAG.getConstant(1, dl, MVT::i32));
21393 
21394     Lo = DAG.getBitcast(MVT::v32i1, Lo);
21395     Hi = DAG.getBitcast(MVT::v32i1, Hi);
21396 
21397     return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
21398   } else {
21399     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
21400                                      Mask.getSimpleValueType().getSizeInBits());
21401     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
21402     // are extracted by EXTRACT_SUBVECTOR.
21403     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
21404                        DAG.getBitcast(BitcastVT, Mask),
21405                        DAG.getIntPtrConstant(0, dl));
21406   }
21407 }
21408 
21409 /// Return (and \p Op, \p Mask) for compare instructions or
21410 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
21411 /// necessary casting or extending for \p Mask when lowering masking intrinsics
getVectorMaskingNode(SDValue Op,SDValue Mask,SDValue PreservedSrc,const X86Subtarget & Subtarget,SelectionDAG & DAG)21412 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
21413                   SDValue PreservedSrc,
21414                   const X86Subtarget &Subtarget,
21415                   SelectionDAG &DAG) {
21416   MVT VT = Op.getSimpleValueType();
21417   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
21418   unsigned OpcodeSelect = ISD::VSELECT;
21419   SDLoc dl(Op);
21420 
21421   if (isAllOnesConstant(Mask))
21422     return Op;
21423 
21424   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
21425 
21426   if (PreservedSrc.isUndef())
21427     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
21428   return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
21429 }
21430 
21431 /// Creates an SDNode for a predicated scalar operation.
21432 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
21433 /// The mask is coming as MVT::i8 and it should be transformed
21434 /// to MVT::v1i1 while lowering masking intrinsics.
21435 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
21436 /// "X86select" instead of "vselect". We just can't create the "vselect" node
21437 /// for a scalar instruction.
getScalarMaskingNode(SDValue Op,SDValue Mask,SDValue PreservedSrc,const X86Subtarget & Subtarget,SelectionDAG & DAG)21438 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
21439                                     SDValue PreservedSrc,
21440                                     const X86Subtarget &Subtarget,
21441                                     SelectionDAG &DAG) {
21442 
21443   if (auto *MaskConst = dyn_cast<ConstantSDNode>(Mask))
21444     if (MaskConst->getZExtValue() & 0x1)
21445       return Op;
21446 
21447   MVT VT = Op.getSimpleValueType();
21448   SDLoc dl(Op);
21449 
21450   assert(Mask.getValueType() == MVT::i8 && "Unexpect type");
21451   SDValue IMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v1i1,
21452                               DAG.getBitcast(MVT::v8i1, Mask),
21453                               DAG.getIntPtrConstant(0, dl));
21454   if (Op.getOpcode() == X86ISD::FSETCCM ||
21455       Op.getOpcode() == X86ISD::FSETCCM_RND ||
21456       Op.getOpcode() == X86ISD::VFPCLASSS)
21457     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
21458 
21459   if (PreservedSrc.isUndef())
21460     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
21461   return DAG.getNode(X86ISD::SELECTS, dl, VT, IMask, Op, PreservedSrc);
21462 }
21463 
getSEHRegistrationNodeSize(const Function * Fn)21464 static int getSEHRegistrationNodeSize(const Function *Fn) {
21465   if (!Fn->hasPersonalityFn())
21466     report_fatal_error(
21467         "querying registration node size for function without personality");
21468   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
21469   // WinEHStatePass for the full struct definition.
21470   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
21471   case EHPersonality::MSVC_X86SEH: return 24;
21472   case EHPersonality::MSVC_CXX: return 16;
21473   default: break;
21474   }
21475   report_fatal_error(
21476       "can only recover FP for 32-bit MSVC EH personality functions");
21477 }
21478 
21479 /// When the MSVC runtime transfers control to us, either to an outlined
21480 /// function or when returning to a parent frame after catching an exception, we
21481 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
21482 /// Here's the math:
21483 ///   RegNodeBase = EntryEBP - RegNodeSize
21484 ///   ParentFP = RegNodeBase - ParentFrameOffset
21485 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
21486 /// subtracting the offset (negative on x86) takes us back to the parent FP.
recoverFramePointer(SelectionDAG & DAG,const Function * Fn,SDValue EntryEBP)21487 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
21488                                    SDValue EntryEBP) {
21489   MachineFunction &MF = DAG.getMachineFunction();
21490   SDLoc dl;
21491 
21492   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21493   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
21494 
21495   // It's possible that the parent function no longer has a personality function
21496   // if the exceptional code was optimized away, in which case we just return
21497   // the incoming EBP.
21498   if (!Fn->hasPersonalityFn())
21499     return EntryEBP;
21500 
21501   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
21502   // registration, or the .set_setframe offset.
21503   MCSymbol *OffsetSym =
21504       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
21505           GlobalValue::dropLLVMManglingEscape(Fn->getName()));
21506   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
21507   SDValue ParentFrameOffset =
21508       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
21509 
21510   // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
21511   // prologue to RBP in the parent function.
21512   const X86Subtarget &Subtarget =
21513       static_cast<const X86Subtarget &>(DAG.getSubtarget());
21514   if (Subtarget.is64Bit())
21515     return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
21516 
21517   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
21518   // RegNodeBase = EntryEBP - RegNodeSize
21519   // ParentFP = RegNodeBase - ParentFrameOffset
21520   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
21521                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
21522   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
21523 }
21524 
LowerINTRINSIC_WO_CHAIN(SDValue Op,SelectionDAG & DAG) const21525 SDValue X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
21526                                                    SelectionDAG &DAG) const {
21527   // Helper to detect if the operand is CUR_DIRECTION rounding mode.
21528   auto isRoundModeCurDirection = [](SDValue Rnd) {
21529     if (!isa<ConstantSDNode>(Rnd))
21530       return false;
21531 
21532     unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
21533     return Round == X86::STATIC_ROUNDING::CUR_DIRECTION;
21534   };
21535 
21536   SDLoc dl(Op);
21537   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21538   MVT VT = Op.getSimpleValueType();
21539   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
21540   if (IntrData) {
21541     switch(IntrData->Type) {
21542     case INTR_TYPE_1OP: {
21543       // We specify 2 possible opcodes for intrinsics with rounding modes.
21544       // First, we check if the intrinsic may have non-default rounding mode,
21545       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
21546       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
21547       if (IntrWithRoundingModeOpcode != 0) {
21548         SDValue Rnd = Op.getOperand(2);
21549         if (!isRoundModeCurDirection(Rnd)) {
21550           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
21551                              Op.getOperand(1), Rnd);
21552         }
21553       }
21554       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
21555     }
21556     case INTR_TYPE_2OP: {
21557       SDValue Src2 = Op.getOperand(2);
21558 
21559       // We specify 2 possible opcodes for intrinsics with rounding modes.
21560       // First, we check if the intrinsic may have non-default rounding mode,
21561       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
21562       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
21563       if (IntrWithRoundingModeOpcode != 0) {
21564         SDValue Rnd = Op.getOperand(3);
21565         if (!isRoundModeCurDirection(Rnd)) {
21566           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
21567                              Op.getOperand(1), Src2, Rnd);
21568         }
21569       }
21570 
21571       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
21572                          Op.getOperand(1), Src2);
21573     }
21574     case INTR_TYPE_3OP:
21575     case INTR_TYPE_3OP_IMM8: {
21576       SDValue Src1 = Op.getOperand(1);
21577       SDValue Src2 = Op.getOperand(2);
21578       SDValue Src3 = Op.getOperand(3);
21579 
21580       if (IntrData->Type == INTR_TYPE_3OP_IMM8)
21581         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
21582 
21583       // We specify 2 possible opcodes for intrinsics with rounding modes.
21584       // First, we check if the intrinsic may have non-default rounding mode,
21585       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
21586       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
21587       if (IntrWithRoundingModeOpcode != 0) {
21588         SDValue Rnd = Op.getOperand(4);
21589         if (!isRoundModeCurDirection(Rnd)) {
21590           return DAG.getNode(IntrWithRoundingModeOpcode,
21591                              dl, Op.getValueType(),
21592                              Src1, Src2, Src3, Rnd);
21593         }
21594       }
21595 
21596       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
21597                          Src1, Src2, Src3);
21598     }
21599     case INTR_TYPE_4OP:
21600       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
21601         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
21602     case INTR_TYPE_1OP_MASK_RM: {
21603       SDValue Src = Op.getOperand(1);
21604       SDValue PassThru = Op.getOperand(2);
21605       SDValue Mask = Op.getOperand(3);
21606       SDValue RoundingMode;
21607       // We always add rounding mode to the Node.
21608       // If the rounding mode is not specified, we add the
21609       // "current direction" mode.
21610       if (Op.getNumOperands() == 4)
21611         RoundingMode =
21612           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
21613       else
21614         RoundingMode = Op.getOperand(4);
21615       assert(IntrData->Opc1 == 0 && "Unexpected second opcode!");
21616       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
21617                                               RoundingMode),
21618                                   Mask, PassThru, Subtarget, DAG);
21619     }
21620     case INTR_TYPE_1OP_MASK: {
21621       SDValue Src = Op.getOperand(1);
21622       SDValue PassThru = Op.getOperand(2);
21623       SDValue Mask = Op.getOperand(3);
21624       // We add rounding mode to the Node when
21625       //   - RM Opcode is specified and
21626       //   - RM is not "current direction".
21627       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
21628       if (IntrWithRoundingModeOpcode != 0) {
21629         SDValue Rnd = Op.getOperand(4);
21630         if (!isRoundModeCurDirection(Rnd)) {
21631           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
21632                                       dl, Op.getValueType(),
21633                                       Src, Rnd),
21634                                       Mask, PassThru, Subtarget, DAG);
21635         }
21636       }
21637       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
21638                                   Mask, PassThru, Subtarget, DAG);
21639     }
21640     case INTR_TYPE_SCALAR_MASK: {
21641       SDValue Src1 = Op.getOperand(1);
21642       SDValue Src2 = Op.getOperand(2);
21643       SDValue passThru = Op.getOperand(3);
21644       SDValue Mask = Op.getOperand(4);
21645       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
21646       // There are 2 kinds of intrinsics in this group:
21647       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
21648       // (2) With rounding mode and sae - 7 operands.
21649       bool HasRounding = IntrWithRoundingModeOpcode != 0;
21650       if (Op.getNumOperands() == (5U + HasRounding)) {
21651         if (HasRounding) {
21652           SDValue Rnd = Op.getOperand(5);
21653           if (!isRoundModeCurDirection(Rnd))
21654             return getScalarMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
21655                                                     dl, VT, Src1, Src2, Rnd),
21656                                         Mask, passThru, Subtarget, DAG);
21657         }
21658         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
21659                                                 Src2),
21660                                     Mask, passThru, Subtarget, DAG);
21661       }
21662 
21663       assert(Op.getNumOperands() == (6U + HasRounding) &&
21664              "Unexpected intrinsic form");
21665       SDValue RoundingMode = Op.getOperand(5);
21666       if (HasRounding) {
21667         SDValue Sae = Op.getOperand(6);
21668         if (!isRoundModeCurDirection(Sae))
21669           return getScalarMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
21670                                                   dl, VT, Src1, Src2,
21671                                                   RoundingMode, Sae),
21672                                       Mask, passThru, Subtarget, DAG);
21673       }
21674       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
21675                                               Src2, RoundingMode),
21676                                   Mask, passThru, Subtarget, DAG);
21677     }
21678     case INTR_TYPE_SCALAR_MASK_RM: {
21679       SDValue Src1 = Op.getOperand(1);
21680       SDValue Src2 = Op.getOperand(2);
21681       SDValue Src0 = Op.getOperand(3);
21682       SDValue Mask = Op.getOperand(4);
21683       // There are 2 kinds of intrinsics in this group:
21684       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
21685       // (2) With rounding mode and sae - 7 operands.
21686       if (Op.getNumOperands() == 6) {
21687         SDValue Sae  = Op.getOperand(5);
21688         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
21689                                                 Sae),
21690                                     Mask, Src0, Subtarget, DAG);
21691       }
21692       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
21693       SDValue RoundingMode  = Op.getOperand(5);
21694       SDValue Sae  = Op.getOperand(6);
21695       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
21696                                               RoundingMode, Sae),
21697                                   Mask, Src0, Subtarget, DAG);
21698     }
21699     case INTR_TYPE_2OP_MASK: {
21700       SDValue Src1 = Op.getOperand(1);
21701       SDValue Src2 = Op.getOperand(2);
21702       SDValue PassThru = Op.getOperand(3);
21703       SDValue Mask = Op.getOperand(4);
21704 
21705       // We specify 2 possible opcodes for intrinsics with rounding modes.
21706       // First, we check if the intrinsic may have non-default rounding mode,
21707       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
21708       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
21709       if (IntrWithRoundingModeOpcode != 0) {
21710         SDValue Rnd = Op.getOperand(5);
21711         if (!isRoundModeCurDirection(Rnd)) {
21712           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
21713                                       dl, Op.getValueType(),
21714                                       Src1, Src2, Rnd),
21715                                       Mask, PassThru, Subtarget, DAG);
21716         }
21717       }
21718       // TODO: Intrinsics should have fast-math-flags to propagate.
21719       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
21720                                   Mask, PassThru, Subtarget, DAG);
21721     }
21722     case INTR_TYPE_2OP_MASK_RM: {
21723       SDValue Src1 = Op.getOperand(1);
21724       SDValue Src2 = Op.getOperand(2);
21725       SDValue PassThru = Op.getOperand(3);
21726       SDValue Mask = Op.getOperand(4);
21727       // We specify 2 possible modes for intrinsics, with/without rounding
21728       // modes.
21729       // First, we check if the intrinsic have rounding mode (6 operands),
21730       // if not, we set rounding mode to "current".
21731       SDValue Rnd;
21732       if (Op.getNumOperands() == 6)
21733         Rnd = Op.getOperand(5);
21734       else
21735         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
21736       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
21737                                               Src1, Src2, Rnd),
21738                                   Mask, PassThru, Subtarget, DAG);
21739     }
21740     case INTR_TYPE_3OP_SCALAR_MASK: {
21741       SDValue Src1 = Op.getOperand(1);
21742       SDValue Src2 = Op.getOperand(2);
21743       SDValue Src3 = Op.getOperand(3);
21744       SDValue PassThru = Op.getOperand(4);
21745       SDValue Mask = Op.getOperand(5);
21746 
21747       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
21748       if (IntrWithRoundingModeOpcode != 0) {
21749         SDValue Rnd = Op.getOperand(6);
21750         if (!isRoundModeCurDirection(Rnd))
21751           return getScalarMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
21752                                                   dl, VT, Src1, Src2, Src3, Rnd),
21753                                       Mask, PassThru, Subtarget, DAG);
21754       }
21755       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
21756                                               Src2, Src3),
21757                                   Mask, PassThru, Subtarget, DAG);
21758     }
21759     case INTR_TYPE_3OP_MASK: {
21760       SDValue Src1 = Op.getOperand(1);
21761       SDValue Src2 = Op.getOperand(2);
21762       SDValue Src3 = Op.getOperand(3);
21763       SDValue PassThru = Op.getOperand(4);
21764       SDValue Mask = Op.getOperand(5);
21765 
21766       // We specify 2 possible opcodes for intrinsics with rounding modes.
21767       // First, we check if the intrinsic may have non-default rounding mode,
21768       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
21769       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
21770       if (IntrWithRoundingModeOpcode != 0) {
21771         SDValue Rnd = Op.getOperand(6);
21772         if (!isRoundModeCurDirection(Rnd)) {
21773           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
21774                                       dl, Op.getValueType(),
21775                                       Src1, Src2, Src3, Rnd),
21776                                       Mask, PassThru, Subtarget, DAG);
21777         }
21778       }
21779       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
21780                                               Src1, Src2, Src3),
21781                                   Mask, PassThru, Subtarget, DAG);
21782     }
21783     case VPERM_2OP : {
21784       SDValue Src1 = Op.getOperand(1);
21785       SDValue Src2 = Op.getOperand(2);
21786 
21787       // Swap Src1 and Src2 in the node creation
21788       return DAG.getNode(IntrData->Opc0, dl, VT,Src2, Src1);
21789     }
21790     case IFMA_OP:
21791       // NOTE: We need to swizzle the operands to pass the multiply operands
21792       // first.
21793       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
21794                          Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
21795     case CVTPD2PS:
21796       // ISD::FP_ROUND has a second argument that indicates if the truncation
21797       // does not change the value. Set it to 0 since it can change.
21798       return DAG.getNode(IntrData->Opc0, dl, VT, Op.getOperand(1),
21799                          DAG.getIntPtrConstant(0, dl));
21800     case CVTPD2PS_RND_MASK: {
21801       SDValue Src = Op.getOperand(1);
21802       SDValue PassThru = Op.getOperand(2);
21803       SDValue Mask = Op.getOperand(3);
21804       // We add rounding mode to the Node when
21805       //   - RM Opcode is specified and
21806       //   - RM is not "current direction".
21807       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
21808       if (IntrWithRoundingModeOpcode != 0) {
21809         SDValue Rnd = Op.getOperand(4);
21810         if (!isRoundModeCurDirection(Rnd)) {
21811           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
21812                                       dl, Op.getValueType(),
21813                                       Src, Rnd),
21814                                       Mask, PassThru, Subtarget, DAG);
21815         }
21816       }
21817       assert(IntrData->Opc0 == ISD::FP_ROUND && "Unexpected opcode!");
21818       // ISD::FP_ROUND has a second argument that indicates if the truncation
21819       // does not change the value. Set it to 0 since it can change.
21820       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
21821                                               DAG.getIntPtrConstant(0, dl)),
21822                                   Mask, PassThru, Subtarget, DAG);
21823     }
21824     case FPCLASSS: {
21825       SDValue Src1 = Op.getOperand(1);
21826       SDValue Imm = Op.getOperand(2);
21827       SDValue Mask = Op.getOperand(3);
21828       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Imm);
21829       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask, SDValue(),
21830                                                  Subtarget, DAG);
21831       // Need to fill with zeros to ensure the bitcast will produce zeroes
21832       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
21833       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
21834                                 DAG.getConstant(0, dl, MVT::v8i1),
21835                                 FPclassMask, DAG.getIntPtrConstant(0, dl));
21836       return DAG.getBitcast(MVT::i8, Ins);
21837     }
21838 
21839     case CMP_MASK_CC: {
21840       MVT MaskVT = Op.getSimpleValueType();
21841       SDValue Cmp;
21842       SDValue CC = Op.getOperand(3);
21843       CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
21844       // We specify 2 possible opcodes for intrinsics with rounding modes.
21845       // First, we check if the intrinsic may have non-default rounding mode,
21846       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
21847       if (IntrData->Opc1 != 0) {
21848         SDValue Rnd = Op.getOperand(4);
21849         if (!isRoundModeCurDirection(Rnd))
21850           Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
21851                             Op.getOperand(2), CC, Rnd);
21852       }
21853       //default rounding mode
21854       if (!Cmp.getNode())
21855         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
21856                           Op.getOperand(2), CC);
21857 
21858       return Cmp;
21859     }
21860     case CMP_MASK_SCALAR_CC: {
21861       SDValue Src1 = Op.getOperand(1);
21862       SDValue Src2 = Op.getOperand(2);
21863       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
21864       SDValue Mask = Op.getOperand(4);
21865 
21866       SDValue Cmp;
21867       if (IntrData->Opc1 != 0) {
21868         SDValue Rnd = Op.getOperand(5);
21869         if (!isRoundModeCurDirection(Rnd))
21870           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::v1i1, Src1, Src2, CC, Rnd);
21871       }
21872       //default rounding mode
21873       if(!Cmp.getNode())
21874         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Src2, CC);
21875 
21876       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask, SDValue(),
21877                                              Subtarget, DAG);
21878       // Need to fill with zeros to ensure the bitcast will produce zeroes
21879       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
21880       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
21881                                 DAG.getConstant(0, dl, MVT::v8i1),
21882                                 CmpMask, DAG.getIntPtrConstant(0, dl));
21883       return DAG.getBitcast(MVT::i8, Ins);
21884     }
21885     case COMI: { // Comparison intrinsics
21886       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
21887       SDValue LHS = Op.getOperand(1);
21888       SDValue RHS = Op.getOperand(2);
21889       SDValue Comi = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
21890       SDValue InvComi = DAG.getNode(IntrData->Opc0, dl, MVT::i32, RHS, LHS);
21891       SDValue SetCC;
21892       switch (CC) {
21893       case ISD::SETEQ: { // (ZF = 0 and PF = 0)
21894         SetCC = getSETCC(X86::COND_E, Comi, dl, DAG);
21895         SDValue SetNP = getSETCC(X86::COND_NP, Comi, dl, DAG);
21896         SetCC = DAG.getNode(ISD::AND, dl, MVT::i8, SetCC, SetNP);
21897         break;
21898       }
21899       case ISD::SETNE: { // (ZF = 1 or PF = 1)
21900         SetCC = getSETCC(X86::COND_NE, Comi, dl, DAG);
21901         SDValue SetP = getSETCC(X86::COND_P, Comi, dl, DAG);
21902         SetCC = DAG.getNode(ISD::OR, dl, MVT::i8, SetCC, SetP);
21903         break;
21904       }
21905       case ISD::SETGT: // (CF = 0 and ZF = 0)
21906         SetCC = getSETCC(X86::COND_A, Comi, dl, DAG);
21907         break;
21908       case ISD::SETLT: { // The condition is opposite to GT. Swap the operands.
21909         SetCC = getSETCC(X86::COND_A, InvComi, dl, DAG);
21910         break;
21911       }
21912       case ISD::SETGE: // CF = 0
21913         SetCC = getSETCC(X86::COND_AE, Comi, dl, DAG);
21914         break;
21915       case ISD::SETLE: // The condition is opposite to GE. Swap the operands.
21916         SetCC = getSETCC(X86::COND_AE, InvComi, dl, DAG);
21917         break;
21918       default:
21919         llvm_unreachable("Unexpected illegal condition!");
21920       }
21921       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
21922     }
21923     case COMI_RM: { // Comparison intrinsics with Sae
21924       SDValue LHS = Op.getOperand(1);
21925       SDValue RHS = Op.getOperand(2);
21926       unsigned CondVal = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
21927       SDValue Sae = Op.getOperand(4);
21928 
21929       SDValue FCmp;
21930       if (isRoundModeCurDirection(Sae))
21931         FCmp = DAG.getNode(X86ISD::FSETCCM, dl, MVT::v1i1, LHS, RHS,
21932                            DAG.getConstant(CondVal, dl, MVT::i8));
21933       else
21934         FCmp = DAG.getNode(X86ISD::FSETCCM_RND, dl, MVT::v1i1, LHS, RHS,
21935                            DAG.getConstant(CondVal, dl, MVT::i8), Sae);
21936       // Need to fill with zeros to ensure the bitcast will produce zeroes
21937       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
21938       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
21939                                 DAG.getConstant(0, dl, MVT::v16i1),
21940                                 FCmp, DAG.getIntPtrConstant(0, dl));
21941       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32,
21942                          DAG.getBitcast(MVT::i16, Ins));
21943     }
21944     case VSHIFT:
21945       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
21946                                  Op.getOperand(1), Op.getOperand(2), Subtarget,
21947                                  DAG);
21948     case COMPRESS_EXPAND_IN_REG: {
21949       SDValue Mask = Op.getOperand(3);
21950       SDValue DataToCompress = Op.getOperand(1);
21951       SDValue PassThru = Op.getOperand(2);
21952       if (isAllOnesConstant(Mask)) // return data as is
21953         return Op.getOperand(1);
21954 
21955       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
21956                                               DataToCompress),
21957                                   Mask, PassThru, Subtarget, DAG);
21958     }
21959     case FIXUPIMMS:
21960     case FIXUPIMMS_MASKZ:
21961     case FIXUPIMM:
21962     case FIXUPIMM_MASKZ:{
21963       SDValue Src1 = Op.getOperand(1);
21964       SDValue Src2 = Op.getOperand(2);
21965       SDValue Src3 = Op.getOperand(3);
21966       SDValue Imm = Op.getOperand(4);
21967       SDValue Mask = Op.getOperand(5);
21968       SDValue Passthru = (IntrData->Type == FIXUPIMM || IntrData->Type == FIXUPIMMS ) ?
21969                                          Src1 : getZeroVector(VT, Subtarget, DAG, dl);
21970       // We specify 2 possible modes for intrinsics, with/without rounding
21971       // modes.
21972       // First, we check if the intrinsic have rounding mode (7 operands),
21973       // if not, we set rounding mode to "current".
21974       SDValue Rnd;
21975       if (Op.getNumOperands() == 7)
21976         Rnd = Op.getOperand(6);
21977       else
21978         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
21979       if (IntrData->Type == FIXUPIMM || IntrData->Type == FIXUPIMM_MASKZ)
21980         return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
21981                                                 Src1, Src2, Src3, Imm, Rnd),
21982                                     Mask, Passthru, Subtarget, DAG);
21983       else // Scalar - FIXUPIMMS, FIXUPIMMS_MASKZ
21984         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
21985                                        Src1, Src2, Src3, Imm, Rnd),
21986                                     Mask, Passthru, Subtarget, DAG);
21987     }
21988     case ROUNDP: {
21989       assert(IntrData->Opc0 == X86ISD::VRNDSCALE && "Unexpected opcode");
21990       // Clear the upper bits of the rounding immediate so that the legacy
21991       // intrinsic can't trigger the scaling behavior of VRNDSCALE.
21992       SDValue RoundingMode = DAG.getNode(ISD::AND, dl, MVT::i32,
21993                                          Op.getOperand(2),
21994                                          DAG.getConstant(0xf, dl, MVT::i32));
21995       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
21996                          Op.getOperand(1), RoundingMode);
21997     }
21998     case ROUNDS: {
21999       assert(IntrData->Opc0 == X86ISD::VRNDSCALES && "Unexpected opcode");
22000       // Clear the upper bits of the rounding immediate so that the legacy
22001       // intrinsic can't trigger the scaling behavior of VRNDSCALE.
22002       SDValue RoundingMode = DAG.getNode(ISD::AND, dl, MVT::i32,
22003                                          Op.getOperand(3),
22004                                          DAG.getConstant(0xf, dl, MVT::i32));
22005       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
22006                          Op.getOperand(1), Op.getOperand(2), RoundingMode);
22007     }
22008     // ADC/ADCX/SBB
22009     case ADX: {
22010       SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
22011       SDVTList VTs = DAG.getVTList(Op.getOperand(2).getValueType(), MVT::i32);
22012 
22013       SDValue Res;
22014       // If the carry in is zero, then we should just use ADD/SUB instead of
22015       // ADC/SBB.
22016       if (isNullConstant(Op.getOperand(1))) {
22017         Res = DAG.getNode(IntrData->Opc1, dl, VTs, Op.getOperand(2),
22018                           Op.getOperand(3));
22019       } else {
22020         SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(1),
22021                                     DAG.getConstant(-1, dl, MVT::i8));
22022         Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(2),
22023                           Op.getOperand(3), GenCF.getValue(1));
22024       }
22025       SDValue SetCC = getSETCC(X86::COND_B, Res.getValue(1), dl, DAG);
22026       SDValue Results[] = { SetCC, Res };
22027       return DAG.getMergeValues(Results, dl);
22028     }
22029     case CVTPD2PS_MASK:
22030     case CVTPD2I_MASK:
22031     case TRUNCATE_TO_REG: {
22032       SDValue Src = Op.getOperand(1);
22033       SDValue PassThru = Op.getOperand(2);
22034       SDValue Mask = Op.getOperand(3);
22035 
22036       if (isAllOnesConstant(Mask))
22037         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
22038 
22039       MVT SrcVT = Src.getSimpleValueType();
22040       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
22041       Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
22042       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(), Src, PassThru,
22043                          Mask);
22044     }
22045     case CVTPS2PH_MASK: {
22046       SDValue Src = Op.getOperand(1);
22047       SDValue Rnd = Op.getOperand(2);
22048       SDValue PassThru = Op.getOperand(3);
22049       SDValue Mask = Op.getOperand(4);
22050 
22051       if (isAllOnesConstant(Mask))
22052         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src, Rnd);
22053 
22054       MVT SrcVT = Src.getSimpleValueType();
22055       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
22056       Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
22057       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(), Src, Rnd,
22058                          PassThru, Mask);
22059 
22060     }
22061     default:
22062       break;
22063     }
22064   }
22065 
22066   switch (IntNo) {
22067   default: return SDValue();    // Don't custom lower most intrinsics.
22068 
22069   // ptest and testp intrinsics. The intrinsic these come from are designed to
22070   // return an integer value, not just an instruction so lower it to the ptest
22071   // or testp pattern and a setcc for the result.
22072   case Intrinsic::x86_avx512_ktestc_b:
22073   case Intrinsic::x86_avx512_ktestc_w:
22074   case Intrinsic::x86_avx512_ktestc_d:
22075   case Intrinsic::x86_avx512_ktestc_q:
22076   case Intrinsic::x86_avx512_ktestz_b:
22077   case Intrinsic::x86_avx512_ktestz_w:
22078   case Intrinsic::x86_avx512_ktestz_d:
22079   case Intrinsic::x86_avx512_ktestz_q:
22080   case Intrinsic::x86_sse41_ptestz:
22081   case Intrinsic::x86_sse41_ptestc:
22082   case Intrinsic::x86_sse41_ptestnzc:
22083   case Intrinsic::x86_avx_ptestz_256:
22084   case Intrinsic::x86_avx_ptestc_256:
22085   case Intrinsic::x86_avx_ptestnzc_256:
22086   case Intrinsic::x86_avx_vtestz_ps:
22087   case Intrinsic::x86_avx_vtestc_ps:
22088   case Intrinsic::x86_avx_vtestnzc_ps:
22089   case Intrinsic::x86_avx_vtestz_pd:
22090   case Intrinsic::x86_avx_vtestc_pd:
22091   case Intrinsic::x86_avx_vtestnzc_pd:
22092   case Intrinsic::x86_avx_vtestz_ps_256:
22093   case Intrinsic::x86_avx_vtestc_ps_256:
22094   case Intrinsic::x86_avx_vtestnzc_ps_256:
22095   case Intrinsic::x86_avx_vtestz_pd_256:
22096   case Intrinsic::x86_avx_vtestc_pd_256:
22097   case Intrinsic::x86_avx_vtestnzc_pd_256: {
22098     unsigned TestOpc = X86ISD::PTEST;
22099     X86::CondCode X86CC;
22100     switch (IntNo) {
22101     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
22102     case Intrinsic::x86_avx512_ktestc_b:
22103     case Intrinsic::x86_avx512_ktestc_w:
22104     case Intrinsic::x86_avx512_ktestc_d:
22105     case Intrinsic::x86_avx512_ktestc_q:
22106       // CF = 1
22107       TestOpc = X86ISD::KTEST;
22108       X86CC = X86::COND_B;
22109       break;
22110     case Intrinsic::x86_avx512_ktestz_b:
22111     case Intrinsic::x86_avx512_ktestz_w:
22112     case Intrinsic::x86_avx512_ktestz_d:
22113     case Intrinsic::x86_avx512_ktestz_q:
22114       TestOpc = X86ISD::KTEST;
22115       X86CC = X86::COND_E;
22116       break;
22117     case Intrinsic::x86_avx_vtestz_ps:
22118     case Intrinsic::x86_avx_vtestz_pd:
22119     case Intrinsic::x86_avx_vtestz_ps_256:
22120     case Intrinsic::x86_avx_vtestz_pd_256:
22121       TestOpc = X86ISD::TESTP;
22122       LLVM_FALLTHROUGH;
22123     case Intrinsic::x86_sse41_ptestz:
22124     case Intrinsic::x86_avx_ptestz_256:
22125       // ZF = 1
22126       X86CC = X86::COND_E;
22127       break;
22128     case Intrinsic::x86_avx_vtestc_ps:
22129     case Intrinsic::x86_avx_vtestc_pd:
22130     case Intrinsic::x86_avx_vtestc_ps_256:
22131     case Intrinsic::x86_avx_vtestc_pd_256:
22132       TestOpc = X86ISD::TESTP;
22133       LLVM_FALLTHROUGH;
22134     case Intrinsic::x86_sse41_ptestc:
22135     case Intrinsic::x86_avx_ptestc_256:
22136       // CF = 1
22137       X86CC = X86::COND_B;
22138       break;
22139     case Intrinsic::x86_avx_vtestnzc_ps:
22140     case Intrinsic::x86_avx_vtestnzc_pd:
22141     case Intrinsic::x86_avx_vtestnzc_ps_256:
22142     case Intrinsic::x86_avx_vtestnzc_pd_256:
22143       TestOpc = X86ISD::TESTP;
22144       LLVM_FALLTHROUGH;
22145     case Intrinsic::x86_sse41_ptestnzc:
22146     case Intrinsic::x86_avx_ptestnzc_256:
22147       // ZF and CF = 0
22148       X86CC = X86::COND_A;
22149       break;
22150     }
22151 
22152     SDValue LHS = Op.getOperand(1);
22153     SDValue RHS = Op.getOperand(2);
22154     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
22155     SDValue SetCC = getSETCC(X86CC, Test, dl, DAG);
22156     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
22157   }
22158 
22159   case Intrinsic::x86_sse42_pcmpistria128:
22160   case Intrinsic::x86_sse42_pcmpestria128:
22161   case Intrinsic::x86_sse42_pcmpistric128:
22162   case Intrinsic::x86_sse42_pcmpestric128:
22163   case Intrinsic::x86_sse42_pcmpistrio128:
22164   case Intrinsic::x86_sse42_pcmpestrio128:
22165   case Intrinsic::x86_sse42_pcmpistris128:
22166   case Intrinsic::x86_sse42_pcmpestris128:
22167   case Intrinsic::x86_sse42_pcmpistriz128:
22168   case Intrinsic::x86_sse42_pcmpestriz128: {
22169     unsigned Opcode;
22170     X86::CondCode X86CC;
22171     switch (IntNo) {
22172     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
22173     case Intrinsic::x86_sse42_pcmpistria128:
22174       Opcode = X86ISD::PCMPISTR;
22175       X86CC = X86::COND_A;
22176       break;
22177     case Intrinsic::x86_sse42_pcmpestria128:
22178       Opcode = X86ISD::PCMPESTR;
22179       X86CC = X86::COND_A;
22180       break;
22181     case Intrinsic::x86_sse42_pcmpistric128:
22182       Opcode = X86ISD::PCMPISTR;
22183       X86CC = X86::COND_B;
22184       break;
22185     case Intrinsic::x86_sse42_pcmpestric128:
22186       Opcode = X86ISD::PCMPESTR;
22187       X86CC = X86::COND_B;
22188       break;
22189     case Intrinsic::x86_sse42_pcmpistrio128:
22190       Opcode = X86ISD::PCMPISTR;
22191       X86CC = X86::COND_O;
22192       break;
22193     case Intrinsic::x86_sse42_pcmpestrio128:
22194       Opcode = X86ISD::PCMPESTR;
22195       X86CC = X86::COND_O;
22196       break;
22197     case Intrinsic::x86_sse42_pcmpistris128:
22198       Opcode = X86ISD::PCMPISTR;
22199       X86CC = X86::COND_S;
22200       break;
22201     case Intrinsic::x86_sse42_pcmpestris128:
22202       Opcode = X86ISD::PCMPESTR;
22203       X86CC = X86::COND_S;
22204       break;
22205     case Intrinsic::x86_sse42_pcmpistriz128:
22206       Opcode = X86ISD::PCMPISTR;
22207       X86CC = X86::COND_E;
22208       break;
22209     case Intrinsic::x86_sse42_pcmpestriz128:
22210       Opcode = X86ISD::PCMPESTR;
22211       X86CC = X86::COND_E;
22212       break;
22213     }
22214     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
22215     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
22216     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps).getValue(2);
22217     SDValue SetCC = getSETCC(X86CC, PCMP, dl, DAG);
22218     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
22219   }
22220 
22221   case Intrinsic::x86_sse42_pcmpistri128:
22222   case Intrinsic::x86_sse42_pcmpestri128: {
22223     unsigned Opcode;
22224     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
22225       Opcode = X86ISD::PCMPISTR;
22226     else
22227       Opcode = X86ISD::PCMPESTR;
22228 
22229     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
22230     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
22231     return DAG.getNode(Opcode, dl, VTs, NewOps);
22232   }
22233 
22234   case Intrinsic::x86_sse42_pcmpistrm128:
22235   case Intrinsic::x86_sse42_pcmpestrm128: {
22236     unsigned Opcode;
22237     if (IntNo == Intrinsic::x86_sse42_pcmpistrm128)
22238       Opcode = X86ISD::PCMPISTR;
22239     else
22240       Opcode = X86ISD::PCMPESTR;
22241 
22242     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
22243     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
22244     return DAG.getNode(Opcode, dl, VTs, NewOps).getValue(1);
22245   }
22246 
22247   case Intrinsic::eh_sjlj_lsda: {
22248     MachineFunction &MF = DAG.getMachineFunction();
22249     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22250     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22251     auto &Context = MF.getMMI().getContext();
22252     MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
22253                                             Twine(MF.getFunctionNumber()));
22254     return DAG.getNode(getGlobalWrapperKind(), dl, VT,
22255                        DAG.getMCSymbol(S, PtrVT));
22256   }
22257 
22258   case Intrinsic::x86_seh_lsda: {
22259     // Compute the symbol for the LSDA. We know it'll get emitted later.
22260     MachineFunction &MF = DAG.getMachineFunction();
22261     SDValue Op1 = Op.getOperand(1);
22262     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
22263     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
22264         GlobalValue::dropLLVMManglingEscape(Fn->getName()));
22265 
22266     // Generate a simple absolute symbol reference. This intrinsic is only
22267     // supported on 32-bit Windows, which isn't PIC.
22268     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
22269     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
22270   }
22271 
22272   case Intrinsic::eh_recoverfp: {
22273     SDValue FnOp = Op.getOperand(1);
22274     SDValue IncomingFPOp = Op.getOperand(2);
22275     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
22276     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
22277     if (!Fn)
22278       report_fatal_error(
22279           "llvm.eh.recoverfp must take a function as the first argument");
22280     return recoverFramePointer(DAG, Fn, IncomingFPOp);
22281   }
22282 
22283   case Intrinsic::localaddress: {
22284     // Returns one of the stack, base, or frame pointer registers, depending on
22285     // which is used to reference local variables.
22286     MachineFunction &MF = DAG.getMachineFunction();
22287     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
22288     unsigned Reg;
22289     if (RegInfo->hasBasePointer(MF))
22290       Reg = RegInfo->getBaseRegister();
22291     else // This function handles the SP or FP case.
22292       Reg = RegInfo->getPtrSizedFrameRegister(MF);
22293     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
22294   }
22295   }
22296 }
22297 
getAVX2GatherNode(unsigned Opc,SDValue Op,SelectionDAG & DAG,SDValue Src,SDValue Mask,SDValue Base,SDValue Index,SDValue ScaleOp,SDValue Chain,const X86Subtarget & Subtarget)22298 static SDValue getAVX2GatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
22299                                  SDValue Src, SDValue Mask, SDValue Base,
22300                                  SDValue Index, SDValue ScaleOp, SDValue Chain,
22301                                  const X86Subtarget &Subtarget) {
22302   SDLoc dl(Op);
22303   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
22304   // Scale must be constant.
22305   if (!C)
22306     return SDValue();
22307   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
22308   EVT MaskVT = Mask.getValueType();
22309   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
22310   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
22311   SDValue Segment = DAG.getRegister(0, MVT::i32);
22312   // If source is undef or we know it won't be used, use a zero vector
22313   // to break register dependency.
22314   // TODO: use undef instead and let BreakFalseDeps deal with it?
22315   if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
22316     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
22317   SDValue Ops[] = {Src, Base, Scale, Index, Disp, Segment, Mask, Chain};
22318   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
22319   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
22320   return DAG.getMergeValues(RetOps, dl);
22321 }
22322 
getGatherNode(unsigned Opc,SDValue Op,SelectionDAG & DAG,SDValue Src,SDValue Mask,SDValue Base,SDValue Index,SDValue ScaleOp,SDValue Chain,const X86Subtarget & Subtarget)22323 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
22324                               SDValue Src, SDValue Mask, SDValue Base,
22325                               SDValue Index, SDValue ScaleOp, SDValue Chain,
22326                               const X86Subtarget &Subtarget) {
22327   MVT VT = Op.getSimpleValueType();
22328   SDLoc dl(Op);
22329   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
22330   // Scale must be constant.
22331   if (!C)
22332     return SDValue();
22333   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
22334   unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
22335                               VT.getVectorNumElements());
22336   MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
22337 
22338   // We support two versions of the gather intrinsics. One with scalar mask and
22339   // one with vXi1 mask. Convert scalar to vXi1 if necessary.
22340   if (Mask.getValueType() != MaskVT)
22341     Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
22342 
22343   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
22344   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
22345   SDValue Segment = DAG.getRegister(0, MVT::i32);
22346   // If source is undef or we know it won't be used, use a zero vector
22347   // to break register dependency.
22348   // TODO: use undef instead and let BreakFalseDeps deal with it?
22349   if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
22350     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
22351   SDValue Ops[] = {Src, Mask, Base, Scale, Index, Disp, Segment, Chain};
22352   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
22353   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
22354   return DAG.getMergeValues(RetOps, dl);
22355 }
22356 
getScatterNode(unsigned Opc,SDValue Op,SelectionDAG & DAG,SDValue Src,SDValue Mask,SDValue Base,SDValue Index,SDValue ScaleOp,SDValue Chain,const X86Subtarget & Subtarget)22357 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
22358                                SDValue Src, SDValue Mask, SDValue Base,
22359                                SDValue Index, SDValue ScaleOp, SDValue Chain,
22360                                const X86Subtarget &Subtarget) {
22361   SDLoc dl(Op);
22362   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
22363   // Scale must be constant.
22364   if (!C)
22365     return SDValue();
22366   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
22367   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
22368   SDValue Segment = DAG.getRegister(0, MVT::i32);
22369   unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
22370                               Src.getSimpleValueType().getVectorNumElements());
22371   MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
22372 
22373   // We support two versions of the scatter intrinsics. One with scalar mask and
22374   // one with vXi1 mask. Convert scalar to vXi1 if necessary.
22375   if (Mask.getValueType() != MaskVT)
22376     Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
22377 
22378   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
22379   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, Mask, Src, Chain};
22380   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
22381   return SDValue(Res, 1);
22382 }
22383 
getPrefetchNode(unsigned Opc,SDValue Op,SelectionDAG & DAG,SDValue Mask,SDValue Base,SDValue Index,SDValue ScaleOp,SDValue Chain,const X86Subtarget & Subtarget)22384 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
22385                                SDValue Mask, SDValue Base, SDValue Index,
22386                                SDValue ScaleOp, SDValue Chain,
22387                                const X86Subtarget &Subtarget) {
22388   SDLoc dl(Op);
22389   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
22390   // Scale must be constant.
22391   if (!C)
22392     return SDValue();
22393   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
22394   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
22395   SDValue Segment = DAG.getRegister(0, MVT::i32);
22396   MVT MaskVT =
22397     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
22398   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
22399   SDValue Ops[] = {VMask, Base, Scale, Index, Disp, Segment, Chain};
22400   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
22401   return SDValue(Res, 0);
22402 }
22403 
22404 /// Handles the lowering of builtin intrinsic that return the value
22405 /// of the extended control register.
getExtendedControlRegister(SDNode * N,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget,SmallVectorImpl<SDValue> & Results)22406 static void getExtendedControlRegister(SDNode *N, const SDLoc &DL,
22407                                        SelectionDAG &DAG,
22408                                        const X86Subtarget &Subtarget,
22409                                        SmallVectorImpl<SDValue> &Results) {
22410   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
22411   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
22412   SDValue LO, HI;
22413 
22414   // The ECX register is used to select the index of the XCR register to
22415   // return.
22416   SDValue Chain =
22417       DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX, N->getOperand(2));
22418   SDNode *N1 = DAG.getMachineNode(X86::XGETBV, DL, Tys, Chain);
22419   Chain = SDValue(N1, 0);
22420 
22421   // Reads the content of XCR and returns it in registers EDX:EAX.
22422   if (Subtarget.is64Bit()) {
22423     LO = DAG.getCopyFromReg(Chain, DL, X86::RAX, MVT::i64, SDValue(N1, 1));
22424     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
22425                             LO.getValue(2));
22426   } else {
22427     LO = DAG.getCopyFromReg(Chain, DL, X86::EAX, MVT::i32, SDValue(N1, 1));
22428     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
22429                             LO.getValue(2));
22430   }
22431   Chain = HI.getValue(1);
22432 
22433   if (Subtarget.is64Bit()) {
22434     // Merge the two 32-bit values into a 64-bit one..
22435     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
22436                               DAG.getConstant(32, DL, MVT::i8));
22437     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
22438     Results.push_back(Chain);
22439     return;
22440   }
22441 
22442   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
22443   SDValue Ops[] = { LO, HI };
22444   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
22445   Results.push_back(Pair);
22446   Results.push_back(Chain);
22447 }
22448 
22449 /// Handles the lowering of builtin intrinsics that read performance monitor
22450 /// counters (x86_rdpmc).
getReadPerformanceCounter(SDNode * N,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget,SmallVectorImpl<SDValue> & Results)22451 static void getReadPerformanceCounter(SDNode *N, const SDLoc &DL,
22452                                       SelectionDAG &DAG,
22453                                       const X86Subtarget &Subtarget,
22454                                       SmallVectorImpl<SDValue> &Results) {
22455   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
22456   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
22457   SDValue LO, HI;
22458 
22459   // The ECX register is used to select the index of the performance counter
22460   // to read.
22461   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
22462                                    N->getOperand(2));
22463   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
22464 
22465   // Reads the content of a 64-bit performance counter and returns it in the
22466   // registers EDX:EAX.
22467   if (Subtarget.is64Bit()) {
22468     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
22469     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
22470                             LO.getValue(2));
22471   } else {
22472     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
22473     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
22474                             LO.getValue(2));
22475   }
22476   Chain = HI.getValue(1);
22477 
22478   if (Subtarget.is64Bit()) {
22479     // The EAX register is loaded with the low-order 32 bits. The EDX register
22480     // is loaded with the supported high-order bits of the counter.
22481     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
22482                               DAG.getConstant(32, DL, MVT::i8));
22483     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
22484     Results.push_back(Chain);
22485     return;
22486   }
22487 
22488   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
22489   SDValue Ops[] = { LO, HI };
22490   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
22491   Results.push_back(Pair);
22492   Results.push_back(Chain);
22493 }
22494 
22495 /// Handles the lowering of builtin intrinsics that read the time stamp counter
22496 /// (x86_rdtsc and x86_rdtscp). This function is also used to custom lower
22497 /// READCYCLECOUNTER nodes.
getReadTimeStampCounter(SDNode * N,const SDLoc & DL,unsigned Opcode,SelectionDAG & DAG,const X86Subtarget & Subtarget,SmallVectorImpl<SDValue> & Results)22498 static void getReadTimeStampCounter(SDNode *N, const SDLoc &DL, unsigned Opcode,
22499                                     SelectionDAG &DAG,
22500                                     const X86Subtarget &Subtarget,
22501                                     SmallVectorImpl<SDValue> &Results) {
22502   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
22503   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
22504   SDValue LO, HI;
22505 
22506   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
22507   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
22508   // and the EAX register is loaded with the low-order 32 bits.
22509   if (Subtarget.is64Bit()) {
22510     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
22511     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
22512                             LO.getValue(2));
22513   } else {
22514     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
22515     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
22516                             LO.getValue(2));
22517   }
22518   SDValue Chain = HI.getValue(1);
22519 
22520   SDValue TSC;
22521   if (Subtarget.is64Bit()) {
22522     // The EDX register is loaded with the high-order 32 bits of the MSR, and
22523     // the EAX register is loaded with the low-order 32 bits.
22524     TSC = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
22525                       DAG.getConstant(32, DL, MVT::i8));
22526     TSC = DAG.getNode(ISD::OR, DL, MVT::i64, LO, TSC);
22527   } else {
22528     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
22529     TSC = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, { LO, HI });
22530   }
22531 
22532   if (Opcode == X86ISD::RDTSCP_DAG) {
22533     assert(N->getNumOperands() == 2 && "Unexpected number of operands!");
22534 
22535     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
22536     // the ECX register. Add 'ecx' explicitly to the chain.
22537     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
22538                                      HI.getValue(2));
22539 
22540     Results.push_back(TSC);
22541     Results.push_back(ecx);
22542     Results.push_back(ecx.getValue(1));
22543     return;
22544   }
22545 
22546   Results.push_back(TSC);
22547   Results.push_back(Chain);
22548 }
22549 
LowerREADCYCLECOUNTER(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)22550 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget &Subtarget,
22551                                      SelectionDAG &DAG) {
22552   SmallVector<SDValue, 3> Results;
22553   SDLoc DL(Op);
22554   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
22555                           Results);
22556   return DAG.getMergeValues(Results, DL);
22557 }
22558 
MarkEHRegistrationNode(SDValue Op,SelectionDAG & DAG)22559 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
22560   MachineFunction &MF = DAG.getMachineFunction();
22561   SDValue Chain = Op.getOperand(0);
22562   SDValue RegNode = Op.getOperand(2);
22563   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
22564   if (!EHInfo)
22565     report_fatal_error("EH registrations only live in functions using WinEH");
22566 
22567   // Cast the operand to an alloca, and remember the frame index.
22568   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
22569   if (!FINode)
22570     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
22571   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
22572 
22573   // Return the chain operand without making any DAG nodes.
22574   return Chain;
22575 }
22576 
MarkEHGuard(SDValue Op,SelectionDAG & DAG)22577 static SDValue MarkEHGuard(SDValue Op, SelectionDAG &DAG) {
22578   MachineFunction &MF = DAG.getMachineFunction();
22579   SDValue Chain = Op.getOperand(0);
22580   SDValue EHGuard = Op.getOperand(2);
22581   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
22582   if (!EHInfo)
22583     report_fatal_error("EHGuard only live in functions using WinEH");
22584 
22585   // Cast the operand to an alloca, and remember the frame index.
22586   auto *FINode = dyn_cast<FrameIndexSDNode>(EHGuard);
22587   if (!FINode)
22588     report_fatal_error("llvm.x86.seh.ehguard expects a static alloca");
22589   EHInfo->EHGuardFrameIndex = FINode->getIndex();
22590 
22591   // Return the chain operand without making any DAG nodes.
22592   return Chain;
22593 }
22594 
22595 /// Emit Truncating Store with signed or unsigned saturation.
22596 static SDValue
EmitTruncSStore(bool SignedSat,SDValue Chain,const SDLoc & Dl,SDValue Val,SDValue Ptr,EVT MemVT,MachineMemOperand * MMO,SelectionDAG & DAG)22597 EmitTruncSStore(bool SignedSat, SDValue Chain, const SDLoc &Dl, SDValue Val,
22598                 SDValue Ptr, EVT MemVT, MachineMemOperand *MMO,
22599                 SelectionDAG &DAG) {
22600 
22601   SDVTList VTs = DAG.getVTList(MVT::Other);
22602   SDValue Undef = DAG.getUNDEF(Ptr.getValueType());
22603   SDValue Ops[] = { Chain, Val, Ptr, Undef };
22604   return SignedSat ?
22605     DAG.getTargetMemSDNode<TruncSStoreSDNode>(VTs, Ops, Dl, MemVT, MMO) :
22606     DAG.getTargetMemSDNode<TruncUSStoreSDNode>(VTs, Ops, Dl, MemVT, MMO);
22607 }
22608 
22609 /// Emit Masked Truncating Store with signed or unsigned saturation.
22610 static SDValue
EmitMaskedTruncSStore(bool SignedSat,SDValue Chain,const SDLoc & Dl,SDValue Val,SDValue Ptr,SDValue Mask,EVT MemVT,MachineMemOperand * MMO,SelectionDAG & DAG)22611 EmitMaskedTruncSStore(bool SignedSat, SDValue Chain, const SDLoc &Dl,
22612                       SDValue Val, SDValue Ptr, SDValue Mask, EVT MemVT,
22613                       MachineMemOperand *MMO, SelectionDAG &DAG) {
22614 
22615   SDVTList VTs = DAG.getVTList(MVT::Other);
22616   SDValue Ops[] = { Chain, Val, Ptr, Mask };
22617   return SignedSat ?
22618     DAG.getTargetMemSDNode<MaskedTruncSStoreSDNode>(VTs, Ops, Dl, MemVT, MMO) :
22619     DAG.getTargetMemSDNode<MaskedTruncUSStoreSDNode>(VTs, Ops, Dl, MemVT, MMO);
22620 }
22621 
LowerINTRINSIC_W_CHAIN(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)22622 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget &Subtarget,
22623                                       SelectionDAG &DAG) {
22624   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
22625 
22626   const IntrinsicData *IntrData = getIntrinsicWithChain(IntNo);
22627   if (!IntrData) {
22628     switch (IntNo) {
22629     case llvm::Intrinsic::x86_seh_ehregnode:
22630       return MarkEHRegistrationNode(Op, DAG);
22631     case llvm::Intrinsic::x86_seh_ehguard:
22632       return MarkEHGuard(Op, DAG);
22633     case llvm::Intrinsic::x86_flags_read_u32:
22634     case llvm::Intrinsic::x86_flags_read_u64:
22635     case llvm::Intrinsic::x86_flags_write_u32:
22636     case llvm::Intrinsic::x86_flags_write_u64: {
22637       // We need a frame pointer because this will get lowered to a PUSH/POP
22638       // sequence.
22639       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
22640       MFI.setHasCopyImplyingStackAdjustment(true);
22641       // Don't do anything here, we will expand these intrinsics out later
22642       // during ExpandISelPseudos in EmitInstrWithCustomInserter.
22643       return SDValue();
22644     }
22645     case Intrinsic::x86_lwpins32:
22646     case Intrinsic::x86_lwpins64:
22647     case Intrinsic::x86_umwait:
22648     case Intrinsic::x86_tpause: {
22649       SDLoc dl(Op);
22650       SDValue Chain = Op->getOperand(0);
22651       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
22652       unsigned Opcode;
22653 
22654       switch (IntNo) {
22655       default: llvm_unreachable("Impossible intrinsic");
22656       case Intrinsic::x86_umwait:
22657         Opcode = X86ISD::UMWAIT;
22658         break;
22659       case Intrinsic::x86_tpause:
22660         Opcode = X86ISD::TPAUSE;
22661         break;
22662       case Intrinsic::x86_lwpins32:
22663       case Intrinsic::x86_lwpins64:
22664         Opcode = X86ISD::LWPINS;
22665         break;
22666       }
22667 
22668       SDValue Operation =
22669           DAG.getNode(Opcode, dl, VTs, Chain, Op->getOperand(2),
22670                       Op->getOperand(3), Op->getOperand(4));
22671       SDValue SetCC = getSETCC(X86::COND_B, Operation.getValue(0), dl, DAG);
22672       SDValue Result = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, SetCC);
22673       return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result,
22674                          Operation.getValue(1));
22675     }
22676     }
22677     return SDValue();
22678   }
22679 
22680   SDLoc dl(Op);
22681   switch(IntrData->Type) {
22682   default: llvm_unreachable("Unknown Intrinsic Type");
22683   case RDSEED:
22684   case RDRAND: {
22685     // Emit the node with the right value type.
22686     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32, MVT::Other);
22687     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
22688 
22689     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
22690     // Otherwise return the value from Rand, which is always 0, casted to i32.
22691     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
22692                       DAG.getConstant(1, dl, Op->getValueType(1)),
22693                       DAG.getConstant(X86::COND_B, dl, MVT::i8),
22694                       SDValue(Result.getNode(), 1) };
22695     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl, Op->getValueType(1), Ops);
22696 
22697     // Return { result, isValid, chain }.
22698     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
22699                        SDValue(Result.getNode(), 2));
22700   }
22701   case GATHER_AVX2: {
22702     SDValue Chain = Op.getOperand(0);
22703     SDValue Src   = Op.getOperand(2);
22704     SDValue Base  = Op.getOperand(3);
22705     SDValue Index = Op.getOperand(4);
22706     SDValue Mask  = Op.getOperand(5);
22707     SDValue Scale = Op.getOperand(6);
22708     return getAVX2GatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
22709                              Scale, Chain, Subtarget);
22710   }
22711   case GATHER: {
22712   //gather(v1, mask, index, base, scale);
22713     SDValue Chain = Op.getOperand(0);
22714     SDValue Src   = Op.getOperand(2);
22715     SDValue Base  = Op.getOperand(3);
22716     SDValue Index = Op.getOperand(4);
22717     SDValue Mask  = Op.getOperand(5);
22718     SDValue Scale = Op.getOperand(6);
22719     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
22720                          Chain, Subtarget);
22721   }
22722   case SCATTER: {
22723   //scatter(base, mask, index, v1, scale);
22724     SDValue Chain = Op.getOperand(0);
22725     SDValue Base  = Op.getOperand(2);
22726     SDValue Mask  = Op.getOperand(3);
22727     SDValue Index = Op.getOperand(4);
22728     SDValue Src   = Op.getOperand(5);
22729     SDValue Scale = Op.getOperand(6);
22730     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
22731                           Scale, Chain, Subtarget);
22732   }
22733   case PREFETCH: {
22734     SDValue Hint = Op.getOperand(6);
22735     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
22736     assert((HintVal == 2 || HintVal == 3) &&
22737            "Wrong prefetch hint in intrinsic: should be 2 or 3");
22738     unsigned Opcode = (HintVal == 2 ? IntrData->Opc1 : IntrData->Opc0);
22739     SDValue Chain = Op.getOperand(0);
22740     SDValue Mask  = Op.getOperand(2);
22741     SDValue Index = Op.getOperand(3);
22742     SDValue Base  = Op.getOperand(4);
22743     SDValue Scale = Op.getOperand(5);
22744     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain,
22745                            Subtarget);
22746   }
22747   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
22748   case RDTSC: {
22749     SmallVector<SDValue, 2> Results;
22750     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
22751                             Results);
22752     return DAG.getMergeValues(Results, dl);
22753   }
22754   // Read Performance Monitoring Counters.
22755   case RDPMC: {
22756     SmallVector<SDValue, 2> Results;
22757     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
22758     return DAG.getMergeValues(Results, dl);
22759   }
22760   // Get Extended Control Register.
22761   case XGETBV: {
22762     SmallVector<SDValue, 2> Results;
22763     getExtendedControlRegister(Op.getNode(), dl, DAG, Subtarget, Results);
22764     return DAG.getMergeValues(Results, dl);
22765   }
22766   // XTEST intrinsics.
22767   case XTEST: {
22768     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
22769     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
22770 
22771     SDValue SetCC = getSETCC(X86::COND_NE, InTrans, dl, DAG);
22772     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
22773     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
22774                        Ret, SDValue(InTrans.getNode(), 1));
22775   }
22776   case TRUNCATE_TO_MEM_VI8:
22777   case TRUNCATE_TO_MEM_VI16:
22778   case TRUNCATE_TO_MEM_VI32: {
22779     SDValue Mask = Op.getOperand(4);
22780     SDValue DataToTruncate = Op.getOperand(3);
22781     SDValue Addr = Op.getOperand(2);
22782     SDValue Chain = Op.getOperand(0);
22783 
22784     MemIntrinsicSDNode *MemIntr = dyn_cast<MemIntrinsicSDNode>(Op);
22785     assert(MemIntr && "Expected MemIntrinsicSDNode!");
22786 
22787     EVT MemVT  = MemIntr->getMemoryVT();
22788 
22789     uint16_t TruncationOp = IntrData->Opc0;
22790     switch (TruncationOp) {
22791     case X86ISD::VTRUNC: {
22792       if (isAllOnesConstant(Mask)) // return just a truncate store
22793         return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr, MemVT,
22794                                  MemIntr->getMemOperand());
22795 
22796       MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
22797       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
22798 
22799       return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr, VMask, MemVT,
22800                                 MemIntr->getMemOperand(), true /* truncating */);
22801     }
22802     case X86ISD::VTRUNCUS:
22803     case X86ISD::VTRUNCS: {
22804       bool IsSigned = (TruncationOp == X86ISD::VTRUNCS);
22805       if (isAllOnesConstant(Mask))
22806         return EmitTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr, MemVT,
22807                                MemIntr->getMemOperand(), DAG);
22808 
22809       MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
22810       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
22811 
22812       return EmitMaskedTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr,
22813                                    VMask, MemVT, MemIntr->getMemOperand(), DAG);
22814     }
22815     default:
22816       llvm_unreachable("Unsupported truncstore intrinsic");
22817     }
22818   }
22819   }
22820 }
22821 
LowerRETURNADDR(SDValue Op,SelectionDAG & DAG) const22822 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
22823                                            SelectionDAG &DAG) const {
22824   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
22825   MFI.setReturnAddressIsTaken(true);
22826 
22827   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
22828     return SDValue();
22829 
22830   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22831   SDLoc dl(Op);
22832   EVT PtrVT = getPointerTy(DAG.getDataLayout());
22833 
22834   if (Depth > 0) {
22835     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
22836     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
22837     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
22838     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
22839                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
22840                        MachinePointerInfo());
22841   }
22842 
22843   // Just load the return address.
22844   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
22845   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
22846                      MachinePointerInfo());
22847 }
22848 
LowerADDROFRETURNADDR(SDValue Op,SelectionDAG & DAG) const22849 SDValue X86TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
22850                                                  SelectionDAG &DAG) const {
22851   DAG.getMachineFunction().getFrameInfo().setReturnAddressIsTaken(true);
22852   return getReturnAddressFrameIndex(DAG);
22853 }
22854 
LowerFRAMEADDR(SDValue Op,SelectionDAG & DAG) const22855 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
22856   MachineFunction &MF = DAG.getMachineFunction();
22857   MachineFrameInfo &MFI = MF.getFrameInfo();
22858   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
22859   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
22860   EVT VT = Op.getValueType();
22861 
22862   MFI.setFrameAddressIsTaken(true);
22863 
22864   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
22865     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
22866     // is not possible to crawl up the stack without looking at the unwind codes
22867     // simultaneously.
22868     int FrameAddrIndex = FuncInfo->getFAIndex();
22869     if (!FrameAddrIndex) {
22870       // Set up a frame object for the return address.
22871       unsigned SlotSize = RegInfo->getSlotSize();
22872       FrameAddrIndex = MF.getFrameInfo().CreateFixedObject(
22873           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
22874       FuncInfo->setFAIndex(FrameAddrIndex);
22875     }
22876     return DAG.getFrameIndex(FrameAddrIndex, VT);
22877   }
22878 
22879   unsigned FrameReg =
22880       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
22881   SDLoc dl(Op);  // FIXME probably not meaningful
22882   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22883   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
22884           (FrameReg == X86::EBP && VT == MVT::i32)) &&
22885          "Invalid Frame Register!");
22886   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
22887   while (Depth--)
22888     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
22889                             MachinePointerInfo());
22890   return FrameAddr;
22891 }
22892 
22893 // FIXME? Maybe this could be a TableGen attribute on some registers and
22894 // this table could be generated automatically from RegInfo.
getRegisterByName(const char * RegName,EVT VT,SelectionDAG & DAG) const22895 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
22896                                               SelectionDAG &DAG) const {
22897   const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
22898   const MachineFunction &MF = DAG.getMachineFunction();
22899 
22900   unsigned Reg = StringSwitch<unsigned>(RegName)
22901                        .Case("esp", X86::ESP)
22902                        .Case("rsp", X86::RSP)
22903                        .Case("ebp", X86::EBP)
22904                        .Case("rbp", X86::RBP)
22905                        .Default(0);
22906 
22907   if (Reg == X86::EBP || Reg == X86::RBP) {
22908     if (!TFI.hasFP(MF))
22909       report_fatal_error("register " + StringRef(RegName) +
22910                          " is allocatable: function has no frame pointer");
22911 #ifndef NDEBUG
22912     else {
22913       const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
22914       unsigned FrameReg =
22915           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
22916       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
22917              "Invalid Frame Register!");
22918     }
22919 #endif
22920   }
22921 
22922   if (Reg)
22923     return Reg;
22924 
22925   report_fatal_error("Invalid register name global variable");
22926 }
22927 
LowerFRAME_TO_ARGS_OFFSET(SDValue Op,SelectionDAG & DAG) const22928 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
22929                                                      SelectionDAG &DAG) const {
22930   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
22931   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
22932 }
22933 
getExceptionPointerRegister(const Constant * PersonalityFn) const22934 unsigned X86TargetLowering::getExceptionPointerRegister(
22935     const Constant *PersonalityFn) const {
22936   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
22937     return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
22938 
22939   return Subtarget.isTarget64BitLP64() ? X86::RAX : X86::EAX;
22940 }
22941 
getExceptionSelectorRegister(const Constant * PersonalityFn) const22942 unsigned X86TargetLowering::getExceptionSelectorRegister(
22943     const Constant *PersonalityFn) const {
22944   // Funclet personalities don't use selectors (the runtime does the selection).
22945   assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
22946   return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
22947 }
22948 
needsFixedCatchObjects() const22949 bool X86TargetLowering::needsFixedCatchObjects() const {
22950   return Subtarget.isTargetWin64();
22951 }
22952 
LowerEH_RETURN(SDValue Op,SelectionDAG & DAG) const22953 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
22954   SDValue Chain     = Op.getOperand(0);
22955   SDValue Offset    = Op.getOperand(1);
22956   SDValue Handler   = Op.getOperand(2);
22957   SDLoc dl      (Op);
22958 
22959   EVT PtrVT = getPointerTy(DAG.getDataLayout());
22960   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
22961   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
22962   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
22963           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
22964          "Invalid Frame Register!");
22965   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
22966   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
22967 
22968   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
22969                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
22970                                                        dl));
22971   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
22972   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo());
22973   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
22974 
22975   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
22976                      DAG.getRegister(StoreAddrReg, PtrVT));
22977 }
22978 
lowerEH_SJLJ_SETJMP(SDValue Op,SelectionDAG & DAG) const22979 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
22980                                                SelectionDAG &DAG) const {
22981   SDLoc DL(Op);
22982   // If the subtarget is not 64bit, we may need the global base reg
22983   // after isel expand pseudo, i.e., after CGBR pass ran.
22984   // Therefore, ask for the GlobalBaseReg now, so that the pass
22985   // inserts the code for us in case we need it.
22986   // Otherwise, we will end up in a situation where we will
22987   // reference a virtual register that is not defined!
22988   if (!Subtarget.is64Bit()) {
22989     const X86InstrInfo *TII = Subtarget.getInstrInfo();
22990     (void)TII->getGlobalBaseReg(&DAG.getMachineFunction());
22991   }
22992   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
22993                      DAG.getVTList(MVT::i32, MVT::Other),
22994                      Op.getOperand(0), Op.getOperand(1));
22995 }
22996 
lowerEH_SJLJ_LONGJMP(SDValue Op,SelectionDAG & DAG) const22997 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
22998                                                 SelectionDAG &DAG) const {
22999   SDLoc DL(Op);
23000   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
23001                      Op.getOperand(0), Op.getOperand(1));
23002 }
23003 
lowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,SelectionDAG & DAG) const23004 SDValue X86TargetLowering::lowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
23005                                                        SelectionDAG &DAG) const {
23006   SDLoc DL(Op);
23007   return DAG.getNode(X86ISD::EH_SJLJ_SETUP_DISPATCH, DL, MVT::Other,
23008                      Op.getOperand(0));
23009 }
23010 
LowerADJUST_TRAMPOLINE(SDValue Op,SelectionDAG & DAG)23011 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
23012   return Op.getOperand(0);
23013 }
23014 
LowerINIT_TRAMPOLINE(SDValue Op,SelectionDAG & DAG) const23015 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
23016                                                 SelectionDAG &DAG) const {
23017   SDValue Root = Op.getOperand(0);
23018   SDValue Trmp = Op.getOperand(1); // trampoline
23019   SDValue FPtr = Op.getOperand(2); // nested function
23020   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
23021   SDLoc dl (Op);
23022 
23023   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
23024   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
23025 
23026   if (Subtarget.is64Bit()) {
23027     SDValue OutChains[6];
23028 
23029     // Large code-model.
23030     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
23031     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
23032 
23033     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
23034     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
23035 
23036     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
23037 
23038     // Load the pointer to the nested function into R11.
23039     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
23040     SDValue Addr = Trmp;
23041     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
23042                                 Addr, MachinePointerInfo(TrmpAddr));
23043 
23044     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
23045                        DAG.getConstant(2, dl, MVT::i64));
23046     OutChains[1] =
23047         DAG.getStore(Root, dl, FPtr, Addr, MachinePointerInfo(TrmpAddr, 2),
23048                      /* Alignment = */ 2);
23049 
23050     // Load the 'nest' parameter value into R10.
23051     // R10 is specified in X86CallingConv.td
23052     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
23053     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
23054                        DAG.getConstant(10, dl, MVT::i64));
23055     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
23056                                 Addr, MachinePointerInfo(TrmpAddr, 10));
23057 
23058     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
23059                        DAG.getConstant(12, dl, MVT::i64));
23060     OutChains[3] =
23061         DAG.getStore(Root, dl, Nest, Addr, MachinePointerInfo(TrmpAddr, 12),
23062                      /* Alignment = */ 2);
23063 
23064     // Jump to the nested function.
23065     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
23066     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
23067                        DAG.getConstant(20, dl, MVT::i64));
23068     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
23069                                 Addr, MachinePointerInfo(TrmpAddr, 20));
23070 
23071     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
23072     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
23073                        DAG.getConstant(22, dl, MVT::i64));
23074     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
23075                                 Addr, MachinePointerInfo(TrmpAddr, 22));
23076 
23077     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
23078   } else {
23079     const Function *Func =
23080       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
23081     CallingConv::ID CC = Func->getCallingConv();
23082     unsigned NestReg;
23083 
23084     switch (CC) {
23085     default:
23086       llvm_unreachable("Unsupported calling convention");
23087     case CallingConv::C:
23088     case CallingConv::X86_StdCall: {
23089       // Pass 'nest' parameter in ECX.
23090       // Must be kept in sync with X86CallingConv.td
23091       NestReg = X86::ECX;
23092 
23093       // Check that ECX wasn't needed by an 'inreg' parameter.
23094       FunctionType *FTy = Func->getFunctionType();
23095       const AttributeList &Attrs = Func->getAttributes();
23096 
23097       if (!Attrs.isEmpty() && !Func->isVarArg()) {
23098         unsigned InRegCount = 0;
23099         unsigned Idx = 1;
23100 
23101         for (FunctionType::param_iterator I = FTy->param_begin(),
23102              E = FTy->param_end(); I != E; ++I, ++Idx)
23103           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
23104             auto &DL = DAG.getDataLayout();
23105             // FIXME: should only count parameters that are lowered to integers.
23106             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
23107           }
23108 
23109         if (InRegCount > 2) {
23110           report_fatal_error("Nest register in use - reduce number of inreg"
23111                              " parameters!");
23112         }
23113       }
23114       break;
23115     }
23116     case CallingConv::X86_FastCall:
23117     case CallingConv::X86_ThisCall:
23118     case CallingConv::Fast:
23119       // Pass 'nest' parameter in EAX.
23120       // Must be kept in sync with X86CallingConv.td
23121       NestReg = X86::EAX;
23122       break;
23123     }
23124 
23125     SDValue OutChains[4];
23126     SDValue Addr, Disp;
23127 
23128     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
23129                        DAG.getConstant(10, dl, MVT::i32));
23130     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
23131 
23132     // This is storing the opcode for MOV32ri.
23133     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
23134     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
23135     OutChains[0] =
23136         DAG.getStore(Root, dl, DAG.getConstant(MOV32ri | N86Reg, dl, MVT::i8),
23137                      Trmp, MachinePointerInfo(TrmpAddr));
23138 
23139     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
23140                        DAG.getConstant(1, dl, MVT::i32));
23141     OutChains[1] =
23142         DAG.getStore(Root, dl, Nest, Addr, MachinePointerInfo(TrmpAddr, 1),
23143                      /* Alignment = */ 1);
23144 
23145     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
23146     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
23147                        DAG.getConstant(5, dl, MVT::i32));
23148     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
23149                                 Addr, MachinePointerInfo(TrmpAddr, 5),
23150                                 /* Alignment = */ 1);
23151 
23152     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
23153                        DAG.getConstant(6, dl, MVT::i32));
23154     OutChains[3] =
23155         DAG.getStore(Root, dl, Disp, Addr, MachinePointerInfo(TrmpAddr, 6),
23156                      /* Alignment = */ 1);
23157 
23158     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
23159   }
23160 }
23161 
LowerFLT_ROUNDS_(SDValue Op,SelectionDAG & DAG) const23162 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
23163                                             SelectionDAG &DAG) const {
23164   /*
23165    The rounding mode is in bits 11:10 of FPSR, and has the following
23166    settings:
23167      00 Round to nearest
23168      01 Round to -inf
23169      10 Round to +inf
23170      11 Round to 0
23171 
23172   FLT_ROUNDS, on the other hand, expects the following:
23173     -1 Undefined
23174      0 Round to 0
23175      1 Round to nearest
23176      2 Round to +inf
23177      3 Round to -inf
23178 
23179   To perform the conversion, we do:
23180     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
23181   */
23182 
23183   MachineFunction &MF = DAG.getMachineFunction();
23184   const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
23185   unsigned StackAlignment = TFI.getStackAlignment();
23186   MVT VT = Op.getSimpleValueType();
23187   SDLoc DL(Op);
23188 
23189   // Save FP Control Word to stack slot
23190   int SSFI = MF.getFrameInfo().CreateStackObject(2, StackAlignment, false);
23191   SDValue StackSlot =
23192       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
23193 
23194   MachineMemOperand *MMO =
23195       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
23196                               MachineMemOperand::MOStore, 2, 2);
23197 
23198   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
23199   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
23200                                           DAG.getVTList(MVT::Other),
23201                                           Ops, MVT::i16, MMO);
23202 
23203   // Load FP Control Word from stack slot
23204   SDValue CWD =
23205       DAG.getLoad(MVT::i16, DL, Chain, StackSlot, MachinePointerInfo());
23206 
23207   // Transform as necessary
23208   SDValue CWD1 =
23209     DAG.getNode(ISD::SRL, DL, MVT::i16,
23210                 DAG.getNode(ISD::AND, DL, MVT::i16,
23211                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
23212                 DAG.getConstant(11, DL, MVT::i8));
23213   SDValue CWD2 =
23214     DAG.getNode(ISD::SRL, DL, MVT::i16,
23215                 DAG.getNode(ISD::AND, DL, MVT::i16,
23216                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
23217                 DAG.getConstant(9, DL, MVT::i8));
23218 
23219   SDValue RetVal =
23220     DAG.getNode(ISD::AND, DL, MVT::i16,
23221                 DAG.getNode(ISD::ADD, DL, MVT::i16,
23222                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
23223                             DAG.getConstant(1, DL, MVT::i16)),
23224                 DAG.getConstant(3, DL, MVT::i16));
23225 
23226   return DAG.getNode((VT.getSizeInBits() < 16 ?
23227                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
23228 }
23229 
23230 // Split an unary integer op into 2 half sized ops.
LowerVectorIntUnary(SDValue Op,SelectionDAG & DAG)23231 static SDValue LowerVectorIntUnary(SDValue Op, SelectionDAG &DAG) {
23232   MVT VT = Op.getSimpleValueType();
23233   unsigned NumElems = VT.getVectorNumElements();
23234   unsigned SizeInBits = VT.getSizeInBits();
23235   MVT EltVT = VT.getVectorElementType();
23236   SDValue Src = Op.getOperand(0);
23237   assert(EltVT == Src.getSimpleValueType().getVectorElementType() &&
23238          "Src and Op should have the same element type!");
23239 
23240   // Extract the Lo/Hi vectors
23241   SDLoc dl(Op);
23242   SDValue Lo = extractSubVector(Src, 0, DAG, dl, SizeInBits / 2);
23243   SDValue Hi = extractSubVector(Src, NumElems / 2, DAG, dl, SizeInBits / 2);
23244 
23245   MVT NewVT = MVT::getVectorVT(EltVT, NumElems / 2);
23246   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
23247                      DAG.getNode(Op.getOpcode(), dl, NewVT, Lo),
23248                      DAG.getNode(Op.getOpcode(), dl, NewVT, Hi));
23249 }
23250 
23251 // Decompose 256-bit ops into smaller 128-bit ops.
Lower256IntUnary(SDValue Op,SelectionDAG & DAG)23252 static SDValue Lower256IntUnary(SDValue Op, SelectionDAG &DAG) {
23253   assert(Op.getSimpleValueType().is256BitVector() &&
23254          Op.getSimpleValueType().isInteger() &&
23255          "Only handle AVX 256-bit vector integer operation");
23256   return LowerVectorIntUnary(Op, DAG);
23257 }
23258 
23259 // Decompose 512-bit ops into smaller 256-bit ops.
Lower512IntUnary(SDValue Op,SelectionDAG & DAG)23260 static SDValue Lower512IntUnary(SDValue Op, SelectionDAG &DAG) {
23261   assert(Op.getSimpleValueType().is512BitVector() &&
23262          Op.getSimpleValueType().isInteger() &&
23263          "Only handle AVX 512-bit vector integer operation");
23264   return LowerVectorIntUnary(Op, DAG);
23265 }
23266 
23267 /// Lower a vector CTLZ using native supported vector CTLZ instruction.
23268 //
23269 // i8/i16 vector implemented using dword LZCNT vector instruction
23270 // ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
23271 // split the vector, perform operation on it's Lo a Hi part and
23272 // concatenate the results.
LowerVectorCTLZ_AVX512CDI(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)23273 static SDValue LowerVectorCTLZ_AVX512CDI(SDValue Op, SelectionDAG &DAG,
23274                                          const X86Subtarget &Subtarget) {
23275   assert(Op.getOpcode() == ISD::CTLZ);
23276   SDLoc dl(Op);
23277   MVT VT = Op.getSimpleValueType();
23278   MVT EltVT = VT.getVectorElementType();
23279   unsigned NumElems = VT.getVectorNumElements();
23280 
23281   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
23282           "Unsupported element type");
23283 
23284   // Split vector, it's Lo and Hi parts will be handled in next iteration.
23285   if (NumElems > 16 ||
23286       (NumElems == 16 && !Subtarget.canExtendTo512DQ()))
23287     return LowerVectorIntUnary(Op, DAG);
23288 
23289   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
23290   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
23291           "Unsupported value type for operation");
23292 
23293   // Use native supported vector instruction vplzcntd.
23294   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
23295   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
23296   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
23297   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
23298 
23299   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
23300 }
23301 
23302 // Lower CTLZ using a PSHUFB lookup table implementation.
LowerVectorCTLZInRegLUT(SDValue Op,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)23303 static SDValue LowerVectorCTLZInRegLUT(SDValue Op, const SDLoc &DL,
23304                                        const X86Subtarget &Subtarget,
23305                                        SelectionDAG &DAG) {
23306   MVT VT = Op.getSimpleValueType();
23307   int NumElts = VT.getVectorNumElements();
23308   int NumBytes = NumElts * (VT.getScalarSizeInBits() / 8);
23309   MVT CurrVT = MVT::getVectorVT(MVT::i8, NumBytes);
23310 
23311   // Per-nibble leading zero PSHUFB lookup table.
23312   const int LUT[16] = {/* 0 */ 4, /* 1 */ 3, /* 2 */ 2, /* 3 */ 2,
23313                        /* 4 */ 1, /* 5 */ 1, /* 6 */ 1, /* 7 */ 1,
23314                        /* 8 */ 0, /* 9 */ 0, /* a */ 0, /* b */ 0,
23315                        /* c */ 0, /* d */ 0, /* e */ 0, /* f */ 0};
23316 
23317   SmallVector<SDValue, 64> LUTVec;
23318   for (int i = 0; i < NumBytes; ++i)
23319     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
23320   SDValue InRegLUT = DAG.getBuildVector(CurrVT, DL, LUTVec);
23321 
23322   // Begin by bitcasting the input to byte vector, then split those bytes
23323   // into lo/hi nibbles and use the PSHUFB LUT to perform CLTZ on each of them.
23324   // If the hi input nibble is zero then we add both results together, otherwise
23325   // we just take the hi result (by masking the lo result to zero before the
23326   // add).
23327   SDValue Op0 = DAG.getBitcast(CurrVT, Op.getOperand(0));
23328   SDValue Zero = DAG.getConstant(0, DL, CurrVT);
23329 
23330   SDValue NibbleShift = DAG.getConstant(0x4, DL, CurrVT);
23331   SDValue Lo = Op0;
23332   SDValue Hi = DAG.getNode(ISD::SRL, DL, CurrVT, Op0, NibbleShift);
23333   SDValue HiZ;
23334   if (CurrVT.is512BitVector()) {
23335     MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
23336     HiZ = DAG.getSetCC(DL, MaskVT, Hi, Zero, ISD::SETEQ);
23337     HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
23338   } else {
23339     HiZ = DAG.getSetCC(DL, CurrVT, Hi, Zero, ISD::SETEQ);
23340   }
23341 
23342   Lo = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Lo);
23343   Hi = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Hi);
23344   Lo = DAG.getNode(ISD::AND, DL, CurrVT, Lo, HiZ);
23345   SDValue Res = DAG.getNode(ISD::ADD, DL, CurrVT, Lo, Hi);
23346 
23347   // Merge result back from vXi8 back to VT, working on the lo/hi halves
23348   // of the current vector width in the same way we did for the nibbles.
23349   // If the upper half of the input element is zero then add the halves'
23350   // leading zero counts together, otherwise just use the upper half's.
23351   // Double the width of the result until we are at target width.
23352   while (CurrVT != VT) {
23353     int CurrScalarSizeInBits = CurrVT.getScalarSizeInBits();
23354     int CurrNumElts = CurrVT.getVectorNumElements();
23355     MVT NextSVT = MVT::getIntegerVT(CurrScalarSizeInBits * 2);
23356     MVT NextVT = MVT::getVectorVT(NextSVT, CurrNumElts / 2);
23357     SDValue Shift = DAG.getConstant(CurrScalarSizeInBits, DL, NextVT);
23358 
23359     // Check if the upper half of the input element is zero.
23360     if (CurrVT.is512BitVector()) {
23361       MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
23362       HiZ = DAG.getSetCC(DL, MaskVT, DAG.getBitcast(CurrVT, Op0),
23363                          DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
23364       HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
23365     } else {
23366       HiZ = DAG.getSetCC(DL, CurrVT, DAG.getBitcast(CurrVT, Op0),
23367                          DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
23368     }
23369     HiZ = DAG.getBitcast(NextVT, HiZ);
23370 
23371     // Move the upper/lower halves to the lower bits as we'll be extending to
23372     // NextVT. Mask the lower result to zero if HiZ is true and add the results
23373     // together.
23374     SDValue ResNext = Res = DAG.getBitcast(NextVT, Res);
23375     SDValue R0 = DAG.getNode(ISD::SRL, DL, NextVT, ResNext, Shift);
23376     SDValue R1 = DAG.getNode(ISD::SRL, DL, NextVT, HiZ, Shift);
23377     R1 = DAG.getNode(ISD::AND, DL, NextVT, ResNext, R1);
23378     Res = DAG.getNode(ISD::ADD, DL, NextVT, R0, R1);
23379     CurrVT = NextVT;
23380   }
23381 
23382   return Res;
23383 }
23384 
LowerVectorCTLZ(SDValue Op,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)23385 static SDValue LowerVectorCTLZ(SDValue Op, const SDLoc &DL,
23386                                const X86Subtarget &Subtarget,
23387                                SelectionDAG &DAG) {
23388   MVT VT = Op.getSimpleValueType();
23389 
23390   if (Subtarget.hasCDI() &&
23391       // vXi8 vectors need to be promoted to 512-bits for vXi32.
23392       (Subtarget.canExtendTo512DQ() || VT.getVectorElementType() != MVT::i8))
23393     return LowerVectorCTLZ_AVX512CDI(Op, DAG, Subtarget);
23394 
23395   // Decompose 256-bit ops into smaller 128-bit ops.
23396   if (VT.is256BitVector() && !Subtarget.hasInt256())
23397     return Lower256IntUnary(Op, DAG);
23398 
23399   // Decompose 512-bit ops into smaller 256-bit ops.
23400   if (VT.is512BitVector() && !Subtarget.hasBWI())
23401     return Lower512IntUnary(Op, DAG);
23402 
23403   assert(Subtarget.hasSSSE3() && "Expected SSSE3 support for PSHUFB");
23404   return LowerVectorCTLZInRegLUT(Op, DL, Subtarget, DAG);
23405 }
23406 
LowerCTLZ(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)23407 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget &Subtarget,
23408                          SelectionDAG &DAG) {
23409   MVT VT = Op.getSimpleValueType();
23410   MVT OpVT = VT;
23411   unsigned NumBits = VT.getSizeInBits();
23412   SDLoc dl(Op);
23413   unsigned Opc = Op.getOpcode();
23414 
23415   if (VT.isVector())
23416     return LowerVectorCTLZ(Op, dl, Subtarget, DAG);
23417 
23418   Op = Op.getOperand(0);
23419   if (VT == MVT::i8) {
23420     // Zero extend to i32 since there is not an i8 bsr.
23421     OpVT = MVT::i32;
23422     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
23423   }
23424 
23425   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
23426   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
23427   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
23428 
23429   if (Opc == ISD::CTLZ) {
23430     // If src is zero (i.e. bsr sets ZF), returns NumBits.
23431     SDValue Ops[] = {
23432       Op,
23433       DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
23434       DAG.getConstant(X86::COND_E, dl, MVT::i8),
23435       Op.getValue(1)
23436     };
23437     Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
23438   }
23439 
23440   // Finally xor with NumBits-1.
23441   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
23442                    DAG.getConstant(NumBits - 1, dl, OpVT));
23443 
23444   if (VT == MVT::i8)
23445     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
23446   return Op;
23447 }
23448 
LowerCTTZ(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)23449 static SDValue LowerCTTZ(SDValue Op, const X86Subtarget &Subtarget,
23450                          SelectionDAG &DAG) {
23451   MVT VT = Op.getSimpleValueType();
23452   unsigned NumBits = VT.getScalarSizeInBits();
23453   SDValue N0 = Op.getOperand(0);
23454   SDLoc dl(Op);
23455 
23456   // Decompose 256-bit ops into smaller 128-bit ops.
23457   if (VT.is256BitVector() && !Subtarget.hasInt256())
23458     return Lower256IntUnary(Op, DAG);
23459 
23460   assert(!VT.isVector() && Op.getOpcode() == ISD::CTTZ &&
23461          "Only scalar CTTZ requires custom lowering");
23462 
23463   // Issue a bsf (scan bits forward) which also sets EFLAGS.
23464   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
23465   Op = DAG.getNode(X86ISD::BSF, dl, VTs, N0);
23466 
23467   // If src is zero (i.e. bsf sets ZF), returns NumBits.
23468   SDValue Ops[] = {
23469     Op,
23470     DAG.getConstant(NumBits, dl, VT),
23471     DAG.getConstant(X86::COND_E, dl, MVT::i8),
23472     Op.getValue(1)
23473   };
23474   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
23475 }
23476 
23477 /// Break a 256-bit integer operation into two new 128-bit ones and then
23478 /// concatenate the result back.
split256IntArith(SDValue Op,SelectionDAG & DAG)23479 static SDValue split256IntArith(SDValue Op, SelectionDAG &DAG) {
23480   MVT VT = Op.getSimpleValueType();
23481 
23482   assert(VT.is256BitVector() && VT.isInteger() &&
23483          "Unsupported value type for operation");
23484 
23485   unsigned NumElems = VT.getVectorNumElements();
23486   SDLoc dl(Op);
23487 
23488   // Extract the LHS vectors
23489   SDValue LHS = Op.getOperand(0);
23490   SDValue LHS1 = extract128BitVector(LHS, 0, DAG, dl);
23491   SDValue LHS2 = extract128BitVector(LHS, NumElems / 2, DAG, dl);
23492 
23493   // Extract the RHS vectors
23494   SDValue RHS = Op.getOperand(1);
23495   SDValue RHS1 = extract128BitVector(RHS, 0, DAG, dl);
23496   SDValue RHS2 = extract128BitVector(RHS, NumElems / 2, DAG, dl);
23497 
23498   MVT EltVT = VT.getVectorElementType();
23499   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
23500 
23501   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
23502                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
23503                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
23504 }
23505 
23506 /// Break a 512-bit integer operation into two new 256-bit ones and then
23507 /// concatenate the result back.
split512IntArith(SDValue Op,SelectionDAG & DAG)23508 static SDValue split512IntArith(SDValue Op, SelectionDAG &DAG) {
23509   MVT VT = Op.getSimpleValueType();
23510 
23511   assert(VT.is512BitVector() && VT.isInteger() &&
23512          "Unsupported value type for operation");
23513 
23514   unsigned NumElems = VT.getVectorNumElements();
23515   SDLoc dl(Op);
23516 
23517   // Extract the LHS vectors
23518   SDValue LHS = Op.getOperand(0);
23519   SDValue LHS1 = extract256BitVector(LHS, 0, DAG, dl);
23520   SDValue LHS2 = extract256BitVector(LHS, NumElems / 2, DAG, dl);
23521 
23522   // Extract the RHS vectors
23523   SDValue RHS = Op.getOperand(1);
23524   SDValue RHS1 = extract256BitVector(RHS, 0, DAG, dl);
23525   SDValue RHS2 = extract256BitVector(RHS, NumElems / 2, DAG, dl);
23526 
23527   MVT EltVT = VT.getVectorElementType();
23528   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
23529 
23530   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
23531                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
23532                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
23533 }
23534 
lowerAddSub(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)23535 static SDValue lowerAddSub(SDValue Op, SelectionDAG &DAG,
23536                            const X86Subtarget &Subtarget) {
23537   MVT VT = Op.getSimpleValueType();
23538   if (VT == MVT::i16 || VT == MVT::i32)
23539     return lowerAddSubToHorizontalOp(Op, DAG, Subtarget);
23540 
23541   if (VT.getScalarType() == MVT::i1)
23542     return DAG.getNode(ISD::XOR, SDLoc(Op), VT,
23543                        Op.getOperand(0), Op.getOperand(1));
23544 
23545   assert(Op.getSimpleValueType().is256BitVector() &&
23546          Op.getSimpleValueType().isInteger() &&
23547          "Only handle AVX 256-bit vector integer operation");
23548   return split256IntArith(Op, DAG);
23549 }
23550 
LowerADDSAT_SUBSAT(SDValue Op,SelectionDAG & DAG)23551 static SDValue LowerADDSAT_SUBSAT(SDValue Op, SelectionDAG &DAG) {
23552   MVT VT = Op.getSimpleValueType();
23553   if (VT.getScalarType() == MVT::i1) {
23554     SDLoc dl(Op);
23555     switch (Op.getOpcode()) {
23556     default: llvm_unreachable("Expected saturated arithmetic opcode");
23557     case ISD::UADDSAT:
23558     case ISD::SADDSAT:
23559       return DAG.getNode(ISD::OR, dl, VT, Op.getOperand(0), Op.getOperand(1));
23560     case ISD::USUBSAT:
23561     case ISD::SSUBSAT:
23562       return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0),
23563                          DAG.getNOT(dl, Op.getOperand(1), VT));
23564     }
23565   }
23566 
23567   assert(Op.getSimpleValueType().is256BitVector() &&
23568          Op.getSimpleValueType().isInteger() &&
23569          "Only handle AVX 256-bit vector integer operation");
23570   return split256IntArith(Op, DAG);
23571 }
23572 
LowerABS(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)23573 static SDValue LowerABS(SDValue Op, const X86Subtarget &Subtarget,
23574                         SelectionDAG &DAG) {
23575   MVT VT = Op.getSimpleValueType();
23576   if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) {
23577     // Since X86 does not have CMOV for 8-bit integer, we don't convert
23578     // 8-bit integer abs to NEG and CMOV.
23579     SDLoc DL(Op);
23580     SDValue N0 = Op.getOperand(0);
23581     SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
23582                               DAG.getConstant(0, DL, VT), N0);
23583     SDValue Ops[] = {N0, Neg, DAG.getConstant(X86::COND_GE, DL, MVT::i8),
23584                      SDValue(Neg.getNode(), 1)};
23585     return DAG.getNode(X86ISD::CMOV, DL, VT, Ops);
23586   }
23587 
23588   // ABS(vXi64 X) --> VPBLENDVPD(X, 0-X, X).
23589   if ((VT == MVT::v2i64 || VT == MVT::v4i64) && Subtarget.hasSSE41()) {
23590     SDLoc DL(Op);
23591     SDValue Src = Op.getOperand(0);
23592     SDValue Sub =
23593         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
23594     return DAG.getNode(X86ISD::BLENDV, DL, VT, Src, Sub, Src);
23595   }
23596 
23597   if (VT.is256BitVector() && !Subtarget.hasInt256()) {
23598     assert(VT.isInteger() &&
23599            "Only handle AVX 256-bit vector integer operation");
23600     return Lower256IntUnary(Op, DAG);
23601   }
23602 
23603   // Default to expand.
23604   return SDValue();
23605 }
23606 
LowerMINMAX(SDValue Op,SelectionDAG & DAG)23607 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
23608   MVT VT = Op.getSimpleValueType();
23609 
23610   // For AVX1 cases, split to use legal ops (everything but v4i64).
23611   if (VT.getScalarType() != MVT::i64 && VT.is256BitVector())
23612     return split256IntArith(Op, DAG);
23613 
23614   SDLoc DL(Op);
23615   unsigned Opcode = Op.getOpcode();
23616   SDValue N0 = Op.getOperand(0);
23617   SDValue N1 = Op.getOperand(1);
23618 
23619   // For pre-SSE41, we can perform UMIN/UMAX v8i16 by flipping the signbit,
23620   // using the SMIN/SMAX instructions and flipping the signbit back.
23621   if (VT == MVT::v8i16) {
23622     assert((Opcode == ISD::UMIN || Opcode == ISD::UMAX) &&
23623            "Unexpected MIN/MAX opcode");
23624     SDValue Sign = DAG.getConstant(APInt::getSignedMinValue(16), DL, VT);
23625     N0 = DAG.getNode(ISD::XOR, DL, VT, N0, Sign);
23626     N1 = DAG.getNode(ISD::XOR, DL, VT, N1, Sign);
23627     Opcode = (Opcode == ISD::UMIN ? ISD::SMIN : ISD::SMAX);
23628     SDValue Result = DAG.getNode(Opcode, DL, VT, N0, N1);
23629     return DAG.getNode(ISD::XOR, DL, VT, Result, Sign);
23630   }
23631 
23632   // Else, expand to a compare/select.
23633   ISD::CondCode CC;
23634   switch (Opcode) {
23635   case ISD::SMIN: CC = ISD::CondCode::SETLT;  break;
23636   case ISD::SMAX: CC = ISD::CondCode::SETGT;  break;
23637   case ISD::UMIN: CC = ISD::CondCode::SETULT; break;
23638   case ISD::UMAX: CC = ISD::CondCode::SETUGT; break;
23639   default: llvm_unreachable("Unknown MINMAX opcode");
23640   }
23641 
23642   SDValue Cond = DAG.getSetCC(DL, VT, N0, N1, CC);
23643   return DAG.getSelect(DL, VT, Cond, N0, N1);
23644 }
23645 
LowerMUL(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)23646 static SDValue LowerMUL(SDValue Op, const X86Subtarget &Subtarget,
23647                         SelectionDAG &DAG) {
23648   SDLoc dl(Op);
23649   MVT VT = Op.getSimpleValueType();
23650 
23651   if (VT.getScalarType() == MVT::i1)
23652     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
23653 
23654   // Decompose 256-bit ops into 128-bit ops.
23655   if (VT.is256BitVector() && !Subtarget.hasInt256())
23656     return split256IntArith(Op, DAG);
23657 
23658   SDValue A = Op.getOperand(0);
23659   SDValue B = Op.getOperand(1);
23660 
23661   // Lower v16i8/v32i8/v64i8 mul as sign-extension to v8i16/v16i16/v32i16
23662   // vector pairs, multiply and truncate.
23663   if (VT == MVT::v16i8 || VT == MVT::v32i8 || VT == MVT::v64i8) {
23664     unsigned NumElts = VT.getVectorNumElements();
23665 
23666     if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
23667         (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
23668       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
23669       return DAG.getNode(
23670           ISD::TRUNCATE, dl, VT,
23671           DAG.getNode(ISD::MUL, dl, ExVT,
23672                       DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, A),
23673                       DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, B)));
23674     }
23675 
23676     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
23677 
23678     // Extract the lo/hi parts to any extend to i16.
23679     // We're going to mask off the low byte of each result element of the
23680     // pmullw, so it doesn't matter what's in the high byte of each 16-bit
23681     // element.
23682     SDValue Undef = DAG.getUNDEF(VT);
23683     SDValue ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A, Undef));
23684     SDValue AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A, Undef));
23685 
23686     SDValue BLo, BHi;
23687     if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
23688       // If the LHS is a constant, manually unpackl/unpackh.
23689       SmallVector<SDValue, 16> LoOps, HiOps;
23690       for (unsigned i = 0; i != NumElts; i += 16) {
23691         for (unsigned j = 0; j != 8; ++j) {
23692           LoOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j), dl,
23693                                                MVT::i16));
23694           HiOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j + 8), dl,
23695                                                MVT::i16));
23696         }
23697       }
23698 
23699       BLo = DAG.getBuildVector(ExVT, dl, LoOps);
23700       BHi = DAG.getBuildVector(ExVT, dl, HiOps);
23701     } else {
23702       BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B, Undef));
23703       BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B, Undef));
23704     }
23705 
23706     // Multiply, mask the lower 8bits of the lo/hi results and pack.
23707     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
23708     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
23709     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
23710     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
23711     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
23712   }
23713 
23714   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
23715   if (VT == MVT::v4i32) {
23716     assert(Subtarget.hasSSE2() && !Subtarget.hasSSE41() &&
23717            "Should not custom lower when pmulld is available!");
23718 
23719     // Extract the odd parts.
23720     static const int UnpackMask[] = { 1, -1, 3, -1 };
23721     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
23722     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
23723 
23724     // Multiply the even parts.
23725     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
23726                                 DAG.getBitcast(MVT::v2i64, A),
23727                                 DAG.getBitcast(MVT::v2i64, B));
23728     // Now multiply odd parts.
23729     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
23730                                DAG.getBitcast(MVT::v2i64, Aodds),
23731                                DAG.getBitcast(MVT::v2i64, Bodds));
23732 
23733     Evens = DAG.getBitcast(VT, Evens);
23734     Odds = DAG.getBitcast(VT, Odds);
23735 
23736     // Merge the two vectors back together with a shuffle. This expands into 2
23737     // shuffles.
23738     static const int ShufMask[] = { 0, 4, 2, 6 };
23739     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
23740   }
23741 
23742   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
23743          "Only know how to lower V2I64/V4I64/V8I64 multiply");
23744   assert(!Subtarget.hasDQI() && "DQI should use MULLQ");
23745 
23746   //  Ahi = psrlqi(a, 32);
23747   //  Bhi = psrlqi(b, 32);
23748   //
23749   //  AloBlo = pmuludq(a, b);
23750   //  AloBhi = pmuludq(a, Bhi);
23751   //  AhiBlo = pmuludq(Ahi, b);
23752   //
23753   //  Hi = psllqi(AloBhi + AhiBlo, 32);
23754   //  return AloBlo + Hi;
23755   KnownBits AKnown = DAG.computeKnownBits(A);
23756   KnownBits BKnown = DAG.computeKnownBits(B);
23757 
23758   APInt LowerBitsMask = APInt::getLowBitsSet(64, 32);
23759   bool ALoIsZero = LowerBitsMask.isSubsetOf(AKnown.Zero);
23760   bool BLoIsZero = LowerBitsMask.isSubsetOf(BKnown.Zero);
23761 
23762   APInt UpperBitsMask = APInt::getHighBitsSet(64, 32);
23763   bool AHiIsZero = UpperBitsMask.isSubsetOf(AKnown.Zero);
23764   bool BHiIsZero = UpperBitsMask.isSubsetOf(BKnown.Zero);
23765 
23766   SDValue Zero = DAG.getConstant(0, dl, VT);
23767 
23768   // Only multiply lo/hi halves that aren't known to be zero.
23769   SDValue AloBlo = Zero;
23770   if (!ALoIsZero && !BLoIsZero)
23771     AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
23772 
23773   SDValue AloBhi = Zero;
23774   if (!ALoIsZero && !BHiIsZero) {
23775     SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
23776     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
23777   }
23778 
23779   SDValue AhiBlo = Zero;
23780   if (!AHiIsZero && !BLoIsZero) {
23781     SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
23782     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
23783   }
23784 
23785   SDValue Hi = DAG.getNode(ISD::ADD, dl, VT, AloBhi, AhiBlo);
23786   Hi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Hi, 32, DAG);
23787 
23788   return DAG.getNode(ISD::ADD, dl, VT, AloBlo, Hi);
23789 }
23790 
LowerMULH(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)23791 static SDValue LowerMULH(SDValue Op, const X86Subtarget &Subtarget,
23792                          SelectionDAG &DAG) {
23793   SDLoc dl(Op);
23794   MVT VT = Op.getSimpleValueType();
23795   bool IsSigned = Op->getOpcode() == ISD::MULHS;
23796   unsigned NumElts = VT.getVectorNumElements();
23797   SDValue A = Op.getOperand(0);
23798   SDValue B = Op.getOperand(1);
23799 
23800   // Decompose 256-bit ops into 128-bit ops.
23801   if (VT.is256BitVector() && !Subtarget.hasInt256())
23802     return split256IntArith(Op, DAG);
23803 
23804   if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32) {
23805     assert((VT == MVT::v4i32 && Subtarget.hasSSE2()) ||
23806            (VT == MVT::v8i32 && Subtarget.hasInt256()) ||
23807            (VT == MVT::v16i32 && Subtarget.hasAVX512()));
23808 
23809     // PMULxD operations multiply each even value (starting at 0) of LHS with
23810     // the related value of RHS and produce a widen result.
23811     // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
23812     // => <2 x i64> <ae|cg>
23813     //
23814     // In other word, to have all the results, we need to perform two PMULxD:
23815     // 1. one with the even values.
23816     // 2. one with the odd values.
23817     // To achieve #2, with need to place the odd values at an even position.
23818     //
23819     // Place the odd value at an even position (basically, shift all values 1
23820     // step to the left):
23821     const int Mask[] = {1, -1,  3, -1,  5, -1,  7, -1,
23822                         9, -1, 11, -1, 13, -1, 15, -1};
23823     // <a|b|c|d> => <b|undef|d|undef>
23824     SDValue Odd0 = DAG.getVectorShuffle(VT, dl, A, A,
23825                                         makeArrayRef(&Mask[0], NumElts));
23826     // <e|f|g|h> => <f|undef|h|undef>
23827     SDValue Odd1 = DAG.getVectorShuffle(VT, dl, B, B,
23828                                         makeArrayRef(&Mask[0], NumElts));
23829 
23830     // Emit two multiplies, one for the lower 2 ints and one for the higher 2
23831     // ints.
23832     MVT MulVT = MVT::getVectorVT(MVT::i64, NumElts / 2);
23833     unsigned Opcode =
23834         (IsSigned && Subtarget.hasSSE41()) ? X86ISD::PMULDQ : X86ISD::PMULUDQ;
23835     // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
23836     // => <2 x i64> <ae|cg>
23837     SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
23838                                                   DAG.getBitcast(MulVT, A),
23839                                                   DAG.getBitcast(MulVT, B)));
23840     // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
23841     // => <2 x i64> <bf|dh>
23842     SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
23843                                                   DAG.getBitcast(MulVT, Odd0),
23844                                                   DAG.getBitcast(MulVT, Odd1)));
23845 
23846     // Shuffle it back into the right order.
23847     SmallVector<int, 16> ShufMask(NumElts);
23848     for (int i = 0; i != (int)NumElts; ++i)
23849       ShufMask[i] = (i / 2) * 2 + ((i % 2) * NumElts) + 1;
23850 
23851     SDValue Res = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, ShufMask);
23852 
23853     // If we have a signed multiply but no PMULDQ fix up the result of an
23854     // unsigned multiply.
23855     if (IsSigned && !Subtarget.hasSSE41()) {
23856       SDValue Zero = DAG.getConstant(0, dl, VT);
23857       SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
23858                                DAG.getSetCC(dl, VT, Zero, A, ISD::SETGT), B);
23859       SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
23860                                DAG.getSetCC(dl, VT, Zero, B, ISD::SETGT), A);
23861 
23862       SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
23863       Res = DAG.getNode(ISD::SUB, dl, VT, Res, Fixup);
23864     }
23865 
23866     return Res;
23867   }
23868 
23869   // Only i8 vectors should need custom lowering after this.
23870   assert((VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) ||
23871          (VT == MVT::v64i8 && Subtarget.hasBWI())) &&
23872          "Unsupported vector type");
23873 
23874   // Lower v16i8/v32i8 as extension to v8i16/v16i16 vector pairs, multiply,
23875   // logical shift down the upper half and pack back to i8.
23876 
23877   // With SSE41 we can use sign/zero extend, but for pre-SSE41 we unpack
23878   // and then ashr/lshr the upper bits down to the lower bits before multiply.
23879   unsigned ExAVX = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
23880 
23881   if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
23882       (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
23883     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
23884     SDValue ExA = DAG.getNode(ExAVX, dl, ExVT, A);
23885     SDValue ExB = DAG.getNode(ExAVX, dl, ExVT, B);
23886     SDValue Mul = DAG.getNode(ISD::MUL, dl, ExVT, ExA, ExB);
23887     Mul = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
23888     return DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
23889   }
23890 
23891   // For signed 512-bit vectors, split into 256-bit vectors to allow the
23892   // sign-extension to occur.
23893   if (VT == MVT::v64i8 && IsSigned)
23894     return split512IntArith(Op, DAG);
23895 
23896   // Signed AVX2 implementation - extend xmm subvectors to ymm.
23897   if (VT == MVT::v32i8 && IsSigned) {
23898     SDValue Lo = DAG.getIntPtrConstant(0, dl);
23899     SDValue Hi = DAG.getIntPtrConstant(NumElts / 2, dl);
23900 
23901     MVT ExVT = MVT::v16i16;
23902     SDValue ALo = extract128BitVector(A, 0, DAG, dl);
23903     SDValue BLo = extract128BitVector(B, 0, DAG, dl);
23904     SDValue AHi = extract128BitVector(A, NumElts / 2, DAG, dl);
23905     SDValue BHi = extract128BitVector(B, NumElts / 2, DAG, dl);
23906     ALo = DAG.getNode(ExAVX, dl, ExVT, ALo);
23907     BLo = DAG.getNode(ExAVX, dl, ExVT, BLo);
23908     AHi = DAG.getNode(ExAVX, dl, ExVT, AHi);
23909     BHi = DAG.getNode(ExAVX, dl, ExVT, BHi);
23910     Lo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
23911     Hi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
23912     Lo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Lo, 8, DAG);
23913     Hi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Hi, 8, DAG);
23914 
23915     // Bitcast back to VT and then pack all the even elements from Lo and Hi.
23916     // Shuffle lowering should turn this into PACKUS+PERMQ
23917     Lo = DAG.getBitcast(VT, Lo);
23918     Hi = DAG.getBitcast(VT, Hi);
23919     return DAG.getVectorShuffle(VT, dl, Lo, Hi,
23920                                 { 0,  2,  4,  6,  8, 10, 12, 14,
23921                                  16, 18, 20, 22, 24, 26, 28, 30,
23922                                  32, 34, 36, 38, 40, 42, 44, 46,
23923                                  48, 50, 52, 54, 56, 58, 60, 62});
23924   }
23925 
23926   // For signed v16i8 and all unsigned vXi8 we will unpack the low and high
23927   // half of each 128 bit lane to widen to a vXi16 type. Do the multiplies,
23928   // shift the results and pack the half lane results back together.
23929 
23930   MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
23931 
23932   static const int PSHUFDMask[] = { 8,  9, 10, 11, 12, 13, 14, 15,
23933                                    -1, -1, -1, -1, -1, -1, -1, -1};
23934 
23935   // Extract the lo parts and zero/sign extend to i16.
23936   // Only use SSE4.1 instructions for signed v16i8 where using unpack requires
23937   // shifts to sign extend. Using unpack for unsigned only requires an xor to
23938   // create zeros and a copy due to tied registers contraints pre-avx. But using
23939   // zero_extend_vector_inreg would require an additional pshufd for the high
23940   // part.
23941 
23942   SDValue ALo, AHi;
23943   if (IsSigned && VT == MVT::v16i8 && Subtarget.hasSSE41()) {
23944     ALo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, ExVT, A);
23945 
23946     AHi = DAG.getVectorShuffle(VT, dl, A, A, PSHUFDMask);
23947     AHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, ExVT, AHi);
23948   } else if (IsSigned) {
23949     ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), A));
23950     AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), A));
23951 
23952     ALo = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, ALo, 8, DAG);
23953     AHi = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, AHi, 8, DAG);
23954   } else {
23955     ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A,
23956                                           DAG.getConstant(0, dl, VT)));
23957     AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A,
23958                                           DAG.getConstant(0, dl, VT)));
23959   }
23960 
23961   SDValue BLo, BHi;
23962   if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
23963     // If the LHS is a constant, manually unpackl/unpackh and extend.
23964     SmallVector<SDValue, 16> LoOps, HiOps;
23965     for (unsigned i = 0; i != NumElts; i += 16) {
23966       for (unsigned j = 0; j != 8; ++j) {
23967         SDValue LoOp = B.getOperand(i + j);
23968         SDValue HiOp = B.getOperand(i + j + 8);
23969 
23970         if (IsSigned) {
23971           LoOp = DAG.getSExtOrTrunc(LoOp, dl, MVT::i16);
23972           HiOp = DAG.getSExtOrTrunc(HiOp, dl, MVT::i16);
23973         } else {
23974           LoOp = DAG.getZExtOrTrunc(LoOp, dl, MVT::i16);
23975           HiOp = DAG.getZExtOrTrunc(HiOp, dl, MVT::i16);
23976         }
23977 
23978         LoOps.push_back(LoOp);
23979         HiOps.push_back(HiOp);
23980       }
23981     }
23982 
23983     BLo = DAG.getBuildVector(ExVT, dl, LoOps);
23984     BHi = DAG.getBuildVector(ExVT, dl, HiOps);
23985   } else if (IsSigned && VT == MVT::v16i8 && Subtarget.hasSSE41()) {
23986     BLo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, ExVT, B);
23987 
23988     BHi = DAG.getVectorShuffle(VT, dl, B, B, PSHUFDMask);
23989     BHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, ExVT, BHi);
23990   } else if (IsSigned) {
23991     BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), B));
23992     BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), B));
23993 
23994     BLo = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, BLo, 8, DAG);
23995     BHi = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, BHi, 8, DAG);
23996   } else {
23997     BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B,
23998                                           DAG.getConstant(0, dl, VT)));
23999     BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B,
24000                                           DAG.getConstant(0, dl, VT)));
24001   }
24002 
24003   // Multiply, lshr the upper 8bits to the lower 8bits of the lo/hi results and
24004   // pack back to vXi8.
24005   SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
24006   SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
24007   RLo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, RLo, 8, DAG);
24008   RHi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, RHi, 8, DAG);
24009 
24010   // Bitcast back to VT and then pack all the even elements from Lo and Hi.
24011   return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
24012 }
24013 
LowerWin64_i128OP(SDValue Op,SelectionDAG & DAG) const24014 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
24015   assert(Subtarget.isTargetWin64() && "Unexpected target");
24016   EVT VT = Op.getValueType();
24017   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
24018          "Unexpected return type for lowering");
24019 
24020   RTLIB::Libcall LC;
24021   bool isSigned;
24022   switch (Op->getOpcode()) {
24023   default: llvm_unreachable("Unexpected request for libcall!");
24024   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
24025   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
24026   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
24027   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
24028   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
24029   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
24030   }
24031 
24032   SDLoc dl(Op);
24033   SDValue InChain = DAG.getEntryNode();
24034 
24035   TargetLowering::ArgListTy Args;
24036   TargetLowering::ArgListEntry Entry;
24037   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
24038     EVT ArgVT = Op->getOperand(i).getValueType();
24039     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
24040            "Unexpected argument type for lowering");
24041     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
24042     Entry.Node = StackPtr;
24043     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr,
24044                            MachinePointerInfo(), /* Alignment = */ 16);
24045     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
24046     Entry.Ty = PointerType::get(ArgTy,0);
24047     Entry.IsSExt = false;
24048     Entry.IsZExt = false;
24049     Args.push_back(Entry);
24050   }
24051 
24052   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
24053                                          getPointerTy(DAG.getDataLayout()));
24054 
24055   TargetLowering::CallLoweringInfo CLI(DAG);
24056   CLI.setDebugLoc(dl)
24057       .setChain(InChain)
24058       .setLibCallee(
24059           getLibcallCallingConv(LC),
24060           static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()), Callee,
24061           std::move(Args))
24062       .setInRegister()
24063       .setSExtResult(isSigned)
24064       .setZExtResult(!isSigned);
24065 
24066   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
24067   return DAG.getBitcast(VT, CallInfo.first);
24068 }
24069 
24070 // Return true if the required (according to Opcode) shift-imm form is natively
24071 // supported by the Subtarget
SupportedVectorShiftWithImm(MVT VT,const X86Subtarget & Subtarget,unsigned Opcode)24072 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget &Subtarget,
24073                                         unsigned Opcode) {
24074   if (VT.getScalarSizeInBits() < 16)
24075     return false;
24076 
24077   if (VT.is512BitVector() && Subtarget.hasAVX512() &&
24078       (VT.getScalarSizeInBits() > 16 || Subtarget.hasBWI()))
24079     return true;
24080 
24081   bool LShift = (VT.is128BitVector() && Subtarget.hasSSE2()) ||
24082                 (VT.is256BitVector() && Subtarget.hasInt256());
24083 
24084   bool AShift = LShift && (Subtarget.hasAVX512() ||
24085                            (VT != MVT::v2i64 && VT != MVT::v4i64));
24086   return (Opcode == ISD::SRA) ? AShift : LShift;
24087 }
24088 
24089 // The shift amount is a variable, but it is the same for all vector lanes.
24090 // These instructions are defined together with shift-immediate.
24091 static
SupportedVectorShiftWithBaseAmnt(MVT VT,const X86Subtarget & Subtarget,unsigned Opcode)24092 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget &Subtarget,
24093                                       unsigned Opcode) {
24094   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
24095 }
24096 
24097 // Return true if the required (according to Opcode) variable-shift form is
24098 // natively supported by the Subtarget
SupportedVectorVarShift(MVT VT,const X86Subtarget & Subtarget,unsigned Opcode)24099 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget &Subtarget,
24100                                     unsigned Opcode) {
24101 
24102   if (!Subtarget.hasInt256() || VT.getScalarSizeInBits() < 16)
24103     return false;
24104 
24105   // vXi16 supported only on AVX-512, BWI
24106   if (VT.getScalarSizeInBits() == 16 && !Subtarget.hasBWI())
24107     return false;
24108 
24109   if (Subtarget.hasAVX512())
24110     return true;
24111 
24112   bool LShift = VT.is128BitVector() || VT.is256BitVector();
24113   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
24114   return (Opcode == ISD::SRA) ? AShift : LShift;
24115 }
24116 
LowerScalarImmediateShift(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)24117 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
24118                                          const X86Subtarget &Subtarget) {
24119   MVT VT = Op.getSimpleValueType();
24120   SDLoc dl(Op);
24121   SDValue R = Op.getOperand(0);
24122   SDValue Amt = Op.getOperand(1);
24123   unsigned X86Opc = getTargetVShiftUniformOpcode(Op.getOpcode(), false);
24124 
24125   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
24126     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
24127     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
24128     SDValue Ex = DAG.getBitcast(ExVT, R);
24129 
24130     // ashr(R, 63) === cmp_slt(R, 0)
24131     if (ShiftAmt == 63 && Subtarget.hasSSE42()) {
24132       assert((VT != MVT::v4i64 || Subtarget.hasInt256()) &&
24133              "Unsupported PCMPGT op");
24134       return DAG.getNode(X86ISD::PCMPGT, dl, VT, DAG.getConstant(0, dl, VT), R);
24135     }
24136 
24137     if (ShiftAmt >= 32) {
24138       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
24139       SDValue Upper =
24140           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
24141       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
24142                                                  ShiftAmt - 32, DAG);
24143       if (VT == MVT::v2i64)
24144         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
24145       if (VT == MVT::v4i64)
24146         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
24147                                   {9, 1, 11, 3, 13, 5, 15, 7});
24148     } else {
24149       // SRA upper i32, SRL whole i64 and select lower i32.
24150       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
24151                                                  ShiftAmt, DAG);
24152       SDValue Lower =
24153           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
24154       Lower = DAG.getBitcast(ExVT, Lower);
24155       if (VT == MVT::v2i64)
24156         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
24157       if (VT == MVT::v4i64)
24158         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
24159                                   {8, 1, 10, 3, 12, 5, 14, 7});
24160     }
24161     return DAG.getBitcast(VT, Ex);
24162   };
24163 
24164   // Optimize shl/srl/sra with constant shift amount.
24165   APInt APIntShiftAmt;
24166   if (!isConstantSplat(Amt, APIntShiftAmt))
24167     return SDValue();
24168   uint64_t ShiftAmt = APIntShiftAmt.getZExtValue();
24169 
24170   if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
24171     return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
24172 
24173   // i64 SRA needs to be performed as partial shifts.
24174   if (((!Subtarget.hasXOP() && VT == MVT::v2i64) ||
24175        (Subtarget.hasInt256() && VT == MVT::v4i64)) &&
24176       Op.getOpcode() == ISD::SRA)
24177     return ArithmeticShiftRight64(ShiftAmt);
24178 
24179   if (VT == MVT::v16i8 || (Subtarget.hasInt256() && VT == MVT::v32i8) ||
24180       VT == MVT::v64i8) {
24181     unsigned NumElts = VT.getVectorNumElements();
24182     MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
24183 
24184     // Simple i8 add case
24185     if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
24186       return DAG.getNode(ISD::ADD, dl, VT, R, R);
24187 
24188     // ashr(R, 7)  === cmp_slt(R, 0)
24189     if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
24190       SDValue Zeros = DAG.getConstant(0, dl, VT);
24191       if (VT.is512BitVector()) {
24192         assert(VT == MVT::v64i8 && "Unexpected element type!");
24193         SDValue CMP = DAG.getSetCC(dl, MVT::v64i1, Zeros, R, ISD::SETGT);
24194         return DAG.getNode(ISD::SIGN_EXTEND, dl, VT, CMP);
24195       }
24196       return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
24197     }
24198 
24199     // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
24200     if (VT == MVT::v16i8 && Subtarget.hasXOP())
24201       return SDValue();
24202 
24203     if (Op.getOpcode() == ISD::SHL) {
24204       // Make a large shift.
24205       SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT, R,
24206                                                ShiftAmt, DAG);
24207       SHL = DAG.getBitcast(VT, SHL);
24208       // Zero out the rightmost bits.
24209       return DAG.getNode(ISD::AND, dl, VT, SHL,
24210                          DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, VT));
24211     }
24212     if (Op.getOpcode() == ISD::SRL) {
24213       // Make a large shift.
24214       SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT, R,
24215                                                ShiftAmt, DAG);
24216       SRL = DAG.getBitcast(VT, SRL);
24217       // Zero out the leftmost bits.
24218       return DAG.getNode(ISD::AND, dl, VT, SRL,
24219                          DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, VT));
24220     }
24221     if (Op.getOpcode() == ISD::SRA) {
24222       // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
24223       SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
24224 
24225       SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
24226       Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
24227       Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
24228       return Res;
24229     }
24230     llvm_unreachable("Unknown shift opcode.");
24231   }
24232 
24233   return SDValue();
24234 }
24235 
24236 // If V is a splat value, return the source vector and splat index;
IsSplatVector(SDValue V,int & SplatIdx,SelectionDAG & DAG)24237 static SDValue IsSplatVector(SDValue V, int &SplatIdx, SelectionDAG &DAG) {
24238   V = peekThroughEXTRACT_SUBVECTORs(V);
24239 
24240   EVT VT = V.getValueType();
24241   unsigned Opcode = V.getOpcode();
24242   switch (Opcode) {
24243   default: {
24244     APInt UndefElts;
24245     APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
24246     if (DAG.isSplatValue(V, DemandedElts, UndefElts)) {
24247       // Handle case where all demanded elements are UNDEF.
24248       if (DemandedElts.isSubsetOf(UndefElts)) {
24249         SplatIdx = 0;
24250         return DAG.getUNDEF(VT);
24251       }
24252       SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
24253       return V;
24254     }
24255     break;
24256   }
24257   case ISD::VECTOR_SHUFFLE: {
24258     // Check if this is a shuffle node doing a splat.
24259     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
24260     // getTargetVShiftNode currently struggles without the splat source.
24261     auto *SVN = cast<ShuffleVectorSDNode>(V);
24262     if (!SVN->isSplat())
24263       break;
24264     int Idx = SVN->getSplatIndex();
24265     int NumElts = V.getValueType().getVectorNumElements();
24266     SplatIdx = Idx % NumElts;
24267     return V.getOperand(Idx / NumElts);
24268   }
24269   }
24270 
24271   return SDValue();
24272 }
24273 
GetSplatValue(SDValue V,const SDLoc & dl,SelectionDAG & DAG)24274 static SDValue GetSplatValue(SDValue V, const SDLoc &dl,
24275                              SelectionDAG &DAG) {
24276   int SplatIdx;
24277   if (SDValue SrcVector = IsSplatVector(V, SplatIdx, DAG))
24278     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24279                        SrcVector.getValueType().getScalarType(), SrcVector,
24280                        DAG.getIntPtrConstant(SplatIdx, dl));
24281   return SDValue();
24282 }
24283 
LowerScalarVariableShift(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)24284 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
24285                                         const X86Subtarget &Subtarget) {
24286   MVT VT = Op.getSimpleValueType();
24287   SDLoc dl(Op);
24288   SDValue R = Op.getOperand(0);
24289   SDValue Amt = Op.getOperand(1);
24290   unsigned Opcode = Op.getOpcode();
24291   unsigned X86OpcI = getTargetVShiftUniformOpcode(Opcode, false);
24292   unsigned X86OpcV = getTargetVShiftUniformOpcode(Opcode, true);
24293 
24294   if (SDValue BaseShAmt = GetSplatValue(Amt, dl, DAG)) {
24295     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Opcode)) {
24296       MVT EltVT = VT.getVectorElementType();
24297       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
24298       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
24299         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
24300       else if (EltVT.bitsLT(MVT::i32))
24301         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
24302 
24303       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, Subtarget, DAG);
24304     }
24305 
24306     // vXi8 shifts - shift as v8i16 + mask result.
24307     if (((VT == MVT::v16i8 && !Subtarget.canExtendTo512DQ()) ||
24308          (VT == MVT::v32i8 && !Subtarget.canExtendTo512BW()) ||
24309          VT == MVT::v64i8) &&
24310         !Subtarget.hasXOP()) {
24311       unsigned NumElts = VT.getVectorNumElements();
24312       MVT ExtVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
24313       if (SupportedVectorShiftWithBaseAmnt(ExtVT, Subtarget, Opcode)) {
24314         unsigned LogicalOp = (Opcode == ISD::SHL ? ISD::SHL : ISD::SRL);
24315         unsigned LogicalX86Op = getTargetVShiftUniformOpcode(LogicalOp, false);
24316         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
24317 
24318         // Create the mask using vXi16 shifts. For shift-rights we need to move
24319         // the upper byte down before splatting the vXi8 mask.
24320         SDValue BitMask = DAG.getConstant(-1, dl, ExtVT);
24321         BitMask = getTargetVShiftNode(LogicalX86Op, dl, ExtVT, BitMask,
24322                                       BaseShAmt, Subtarget, DAG);
24323         if (Opcode != ISD::SHL)
24324           BitMask = getTargetVShiftByConstNode(LogicalX86Op, dl, ExtVT, BitMask,
24325                                                8, DAG);
24326         BitMask = DAG.getBitcast(VT, BitMask);
24327         BitMask = DAG.getVectorShuffle(VT, dl, BitMask, BitMask,
24328                                        SmallVector<int, 64>(NumElts, 0));
24329 
24330         SDValue Res = getTargetVShiftNode(LogicalX86Op, dl, ExtVT,
24331                                           DAG.getBitcast(ExtVT, R), BaseShAmt,
24332                                           Subtarget, DAG);
24333         Res = DAG.getBitcast(VT, Res);
24334         Res = DAG.getNode(ISD::AND, dl, VT, Res, BitMask);
24335 
24336         if (Opcode == ISD::SRA) {
24337           // ashr(R, Amt) === sub(xor(lshr(R, Amt), SignMask), SignMask)
24338           // SignMask = lshr(SignBit, Amt) - safe to do this with PSRLW.
24339           SDValue SignMask = DAG.getConstant(0x8080, dl, ExtVT);
24340           SignMask = getTargetVShiftNode(LogicalX86Op, dl, ExtVT, SignMask,
24341                                          BaseShAmt, Subtarget, DAG);
24342           SignMask = DAG.getBitcast(VT, SignMask);
24343           Res = DAG.getNode(ISD::XOR, dl, VT, Res, SignMask);
24344           Res = DAG.getNode(ISD::SUB, dl, VT, Res, SignMask);
24345         }
24346         return Res;
24347       }
24348     }
24349   }
24350 
24351   // Check cases (mainly 32-bit) where i64 is expanded into high and low parts.
24352   if (VT == MVT::v2i64 && Amt.getOpcode() == ISD::BITCAST &&
24353       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
24354     Amt = Amt.getOperand(0);
24355     unsigned Ratio = 64 / Amt.getScalarValueSizeInBits();
24356     std::vector<SDValue> Vals(Ratio);
24357     for (unsigned i = 0; i != Ratio; ++i)
24358       Vals[i] = Amt.getOperand(i);
24359     for (unsigned i = Ratio, e = Amt.getNumOperands(); i != e; i += Ratio) {
24360       for (unsigned j = 0; j != Ratio; ++j)
24361         if (Vals[j] != Amt.getOperand(i + j))
24362           return SDValue();
24363     }
24364 
24365     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
24366       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
24367   }
24368   return SDValue();
24369 }
24370 
24371 // Convert a shift/rotate left amount to a multiplication scale factor.
convertShiftLeftToScale(SDValue Amt,const SDLoc & dl,const X86Subtarget & Subtarget,SelectionDAG & DAG)24372 static SDValue convertShiftLeftToScale(SDValue Amt, const SDLoc &dl,
24373                                        const X86Subtarget &Subtarget,
24374                                        SelectionDAG &DAG) {
24375   MVT VT = Amt.getSimpleValueType();
24376   if (!(VT == MVT::v8i16 || VT == MVT::v4i32 ||
24377         (Subtarget.hasInt256() && VT == MVT::v16i16) ||
24378         (!Subtarget.hasAVX512() && VT == MVT::v16i8)))
24379     return SDValue();
24380 
24381   if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
24382     SmallVector<SDValue, 8> Elts;
24383     MVT SVT = VT.getVectorElementType();
24384     unsigned SVTBits = SVT.getSizeInBits();
24385     APInt One(SVTBits, 1);
24386     unsigned NumElems = VT.getVectorNumElements();
24387 
24388     for (unsigned i = 0; i != NumElems; ++i) {
24389       SDValue Op = Amt->getOperand(i);
24390       if (Op->isUndef()) {
24391         Elts.push_back(Op);
24392         continue;
24393       }
24394 
24395       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
24396       APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
24397       uint64_t ShAmt = C.getZExtValue();
24398       if (ShAmt >= SVTBits) {
24399         Elts.push_back(DAG.getUNDEF(SVT));
24400         continue;
24401       }
24402       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
24403     }
24404     return DAG.getBuildVector(VT, dl, Elts);
24405   }
24406 
24407   // If the target doesn't support variable shifts, use either FP conversion
24408   // or integer multiplication to avoid shifting each element individually.
24409   if (VT == MVT::v4i32) {
24410     Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
24411     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt,
24412                       DAG.getConstant(0x3f800000U, dl, VT));
24413     Amt = DAG.getBitcast(MVT::v4f32, Amt);
24414     return DAG.getNode(ISD::FP_TO_SINT, dl, VT, Amt);
24415   }
24416 
24417   // AVX2 can more effectively perform this as a zext/trunc to/from v8i32.
24418   if (VT == MVT::v8i16 && !Subtarget.hasAVX2()) {
24419     SDValue Z = DAG.getConstant(0, dl, VT);
24420     SDValue Lo = DAG.getBitcast(MVT::v4i32, getUnpackl(DAG, dl, VT, Amt, Z));
24421     SDValue Hi = DAG.getBitcast(MVT::v4i32, getUnpackh(DAG, dl, VT, Amt, Z));
24422     Lo = convertShiftLeftToScale(Lo, dl, Subtarget, DAG);
24423     Hi = convertShiftLeftToScale(Hi, dl, Subtarget, DAG);
24424     if (Subtarget.hasSSE41())
24425       return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
24426 
24427     return DAG.getVectorShuffle(VT, dl, DAG.getBitcast(VT, Lo),
24428                                         DAG.getBitcast(VT, Hi),
24429                                         {0, 2, 4, 6, 8, 10, 12, 14});
24430   }
24431 
24432   return SDValue();
24433 }
24434 
LowerShift(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)24435 static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
24436                           SelectionDAG &DAG) {
24437   MVT VT = Op.getSimpleValueType();
24438   SDLoc dl(Op);
24439   SDValue R = Op.getOperand(0);
24440   SDValue Amt = Op.getOperand(1);
24441   unsigned EltSizeInBits = VT.getScalarSizeInBits();
24442   bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
24443 
24444   unsigned Opc = Op.getOpcode();
24445   unsigned X86OpcV = getTargetVShiftUniformOpcode(Opc, true);
24446   unsigned X86OpcI = getTargetVShiftUniformOpcode(Opc, false);
24447 
24448   assert(VT.isVector() && "Custom lowering only for vector shifts!");
24449   assert(Subtarget.hasSSE2() && "Only custom lower when we have SSE2!");
24450 
24451   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
24452     return V;
24453 
24454   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
24455     return V;
24456 
24457   if (SupportedVectorVarShift(VT, Subtarget, Opc))
24458     return Op;
24459 
24460   // XOP has 128-bit variable logical/arithmetic shifts.
24461   // +ve/-ve Amt = shift left/right.
24462   if (Subtarget.hasXOP() && (VT == MVT::v2i64 || VT == MVT::v4i32 ||
24463                              VT == MVT::v8i16 || VT == MVT::v16i8)) {
24464     if (Opc == ISD::SRL || Opc == ISD::SRA) {
24465       SDValue Zero = DAG.getConstant(0, dl, VT);
24466       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
24467     }
24468     if (Opc == ISD::SHL || Opc == ISD::SRL)
24469       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
24470     if (Opc == ISD::SRA)
24471       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
24472   }
24473 
24474   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
24475   // shifts per-lane and then shuffle the partial results back together.
24476   if (VT == MVT::v2i64 && Opc != ISD::SRA) {
24477     // Splat the shift amounts so the scalar shifts above will catch it.
24478     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
24479     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
24480     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
24481     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
24482     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
24483   }
24484 
24485   // i64 vector arithmetic shift can be emulated with the transform:
24486   // M = lshr(SIGN_MASK, Amt)
24487   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
24488   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget.hasInt256())) &&
24489       Opc == ISD::SRA) {
24490     SDValue S = DAG.getConstant(APInt::getSignMask(64), dl, VT);
24491     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
24492     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
24493     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
24494     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
24495     return R;
24496   }
24497 
24498   // If possible, lower this shift as a sequence of two shifts by
24499   // constant plus a BLENDing shuffle instead of scalarizing it.
24500   // Example:
24501   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
24502   //
24503   // Could be rewritten as:
24504   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
24505   //
24506   // The advantage is that the two shifts from the example would be
24507   // lowered as X86ISD::VSRLI nodes in parallel before blending.
24508   if (ConstantAmt && (VT == MVT::v8i16 || VT == MVT::v4i32 ||
24509                       (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
24510     SDValue Amt1, Amt2;
24511     unsigned NumElts = VT.getVectorNumElements();
24512     SmallVector<int, 8> ShuffleMask;
24513     for (unsigned i = 0; i != NumElts; ++i) {
24514       SDValue A = Amt->getOperand(i);
24515       if (A.isUndef()) {
24516         ShuffleMask.push_back(SM_SentinelUndef);
24517         continue;
24518       }
24519       if (!Amt1 || Amt1 == A) {
24520         ShuffleMask.push_back(i);
24521         Amt1 = A;
24522         continue;
24523       }
24524       if (!Amt2 || Amt2 == A) {
24525         ShuffleMask.push_back(i + NumElts);
24526         Amt2 = A;
24527         continue;
24528       }
24529       break;
24530     }
24531 
24532     // Only perform this blend if we can perform it without loading a mask.
24533     if (ShuffleMask.size() == NumElts && Amt1 && Amt2 &&
24534         (VT != MVT::v16i16 ||
24535          is128BitLaneRepeatedShuffleMask(VT, ShuffleMask)) &&
24536         (VT == MVT::v4i32 || Subtarget.hasSSE41() || Opc != ISD::SHL ||
24537          canWidenShuffleElements(ShuffleMask))) {
24538       auto *Cst1 = dyn_cast<ConstantSDNode>(Amt1);
24539       auto *Cst2 = dyn_cast<ConstantSDNode>(Amt2);
24540       if (Cst1 && Cst2 && Cst1->getAPIntValue().ult(EltSizeInBits) &&
24541           Cst2->getAPIntValue().ult(EltSizeInBits)) {
24542         SDValue Shift1 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
24543                                                     Cst1->getZExtValue(), DAG);
24544         SDValue Shift2 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
24545                                                     Cst2->getZExtValue(), DAG);
24546         return DAG.getVectorShuffle(VT, dl, Shift1, Shift2, ShuffleMask);
24547       }
24548     }
24549   }
24550 
24551   // If possible, lower this packed shift into a vector multiply instead of
24552   // expanding it into a sequence of scalar shifts.
24553   if (Opc == ISD::SHL)
24554     if (SDValue Scale = convertShiftLeftToScale(Amt, dl, Subtarget, DAG))
24555       return DAG.getNode(ISD::MUL, dl, VT, R, Scale);
24556 
24557   // Constant ISD::SRL can be performed efficiently on vXi16 vectors as we
24558   // can replace with ISD::MULHU, creating scale factor from (NumEltBits - Amt).
24559   if (Opc == ISD::SRL && ConstantAmt &&
24560       (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
24561     SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
24562     SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
24563     if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
24564       SDValue Zero = DAG.getConstant(0, dl, VT);
24565       SDValue ZAmt = DAG.getSetCC(dl, VT, Amt, Zero, ISD::SETEQ);
24566       SDValue Res = DAG.getNode(ISD::MULHU, dl, VT, R, Scale);
24567       return DAG.getSelect(dl, VT, ZAmt, R, Res);
24568     }
24569   }
24570 
24571   // Constant ISD::SRA can be performed efficiently on vXi16 vectors as we
24572   // can replace with ISD::MULHS, creating scale factor from (NumEltBits - Amt).
24573   // TODO: Special case handling for shift by 0/1, really we can afford either
24574   // of these cases in pre-SSE41/XOP/AVX512 but not both.
24575   if (Opc == ISD::SRA && ConstantAmt &&
24576       (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256())) &&
24577       ((Subtarget.hasSSE41() && !Subtarget.hasXOP() &&
24578         !Subtarget.hasAVX512()) ||
24579        DAG.isKnownNeverZero(Amt))) {
24580     SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
24581     SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
24582     if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
24583       SDValue Amt0 =
24584           DAG.getSetCC(dl, VT, Amt, DAG.getConstant(0, dl, VT), ISD::SETEQ);
24585       SDValue Amt1 =
24586           DAG.getSetCC(dl, VT, Amt, DAG.getConstant(1, dl, VT), ISD::SETEQ);
24587       SDValue Sra1 =
24588           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, 1, DAG);
24589       SDValue Res = DAG.getNode(ISD::MULHS, dl, VT, R, Scale);
24590       Res = DAG.getSelect(dl, VT, Amt0, R, Res);
24591       return DAG.getSelect(dl, VT, Amt1, Sra1, Res);
24592     }
24593   }
24594 
24595   // v4i32 Non Uniform Shifts.
24596   // If the shift amount is constant we can shift each lane using the SSE2
24597   // immediate shifts, else we need to zero-extend each lane to the lower i64
24598   // and shift using the SSE2 variable shifts.
24599   // The separate results can then be blended together.
24600   if (VT == MVT::v4i32) {
24601     SDValue Amt0, Amt1, Amt2, Amt3;
24602     if (ConstantAmt) {
24603       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
24604       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
24605       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
24606       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
24607     } else {
24608       // The SSE2 shifts use the lower i64 as the same shift amount for
24609       // all lanes and the upper i64 is ignored. On AVX we're better off
24610       // just zero-extending, but for SSE just duplicating the top 16-bits is
24611       // cheaper and has the same effect for out of range values.
24612       if (Subtarget.hasAVX()) {
24613         SDValue Z = DAG.getConstant(0, dl, VT);
24614         Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
24615         Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
24616         Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
24617         Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
24618       } else {
24619         SDValue Amt01 = DAG.getBitcast(MVT::v8i16, Amt);
24620         SDValue Amt23 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
24621                                              {4, 5, 6, 7, -1, -1, -1, -1});
24622         Amt0 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
24623                                     {0, 1, 1, 1, -1, -1, -1, -1});
24624         Amt1 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
24625                                     {2, 3, 3, 3, -1, -1, -1, -1});
24626         Amt2 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt23, Amt23,
24627                                     {0, 1, 1, 1, -1, -1, -1, -1});
24628         Amt3 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt23, Amt23,
24629                                     {2, 3, 3, 3, -1, -1, -1, -1});
24630       }
24631     }
24632 
24633     unsigned ShOpc = ConstantAmt ? Opc : X86OpcV;
24634     SDValue R0 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt0));
24635     SDValue R1 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt1));
24636     SDValue R2 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt2));
24637     SDValue R3 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt3));
24638 
24639     // Merge the shifted lane results optimally with/without PBLENDW.
24640     // TODO - ideally shuffle combining would handle this.
24641     if (Subtarget.hasSSE41()) {
24642       SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
24643       SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
24644       return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
24645     }
24646     SDValue R01 = DAG.getVectorShuffle(VT, dl, R0, R1, {0, -1, -1, 5});
24647     SDValue R23 = DAG.getVectorShuffle(VT, dl, R2, R3, {2, -1, -1, 7});
24648     return DAG.getVectorShuffle(VT, dl, R01, R23, {0, 3, 4, 7});
24649   }
24650 
24651   // It's worth extending once and using the vXi16/vXi32 shifts for smaller
24652   // types, but without AVX512 the extra overheads to get from vXi8 to vXi32
24653   // make the existing SSE solution better.
24654   // NOTE: We honor prefered vector width before promoting to 512-bits.
24655   if ((Subtarget.hasInt256() && VT == MVT::v8i16) ||
24656       (Subtarget.canExtendTo512DQ() && VT == MVT::v16i16) ||
24657       (Subtarget.canExtendTo512DQ() && VT == MVT::v16i8) ||
24658       (Subtarget.canExtendTo512BW() && VT == MVT::v32i8) ||
24659       (Subtarget.hasBWI() && Subtarget.hasVLX() && VT == MVT::v16i8)) {
24660     assert((!Subtarget.hasBWI() || VT == MVT::v32i8 || VT == MVT::v16i8) &&
24661            "Unexpected vector type");
24662     MVT EvtSVT = Subtarget.hasBWI() ? MVT::i16 : MVT::i32;
24663     MVT ExtVT = MVT::getVectorVT(EvtSVT, VT.getVectorNumElements());
24664     unsigned ExtOpc = Opc == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
24665     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
24666     Amt = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Amt);
24667     return DAG.getNode(ISD::TRUNCATE, dl, VT,
24668                        DAG.getNode(Opc, dl, ExtVT, R, Amt));
24669   }
24670 
24671   // Constant ISD::SRA/SRL can be performed efficiently on vXi8 vectors as we
24672   // extend to vXi16 to perform a MUL scale effectively as a MUL_LOHI.
24673   if (ConstantAmt && (Opc == ISD::SRA || Opc == ISD::SRL) &&
24674       (VT == MVT::v16i8 || VT == MVT::v64i8 ||
24675        (VT == MVT::v32i8 && Subtarget.hasInt256())) &&
24676       !Subtarget.hasXOP()) {
24677     int NumElts = VT.getVectorNumElements();
24678     SDValue Cst8 = DAG.getConstant(8, dl, MVT::i8);
24679 
24680     // Extend constant shift amount to vXi16 (it doesn't matter if the type
24681     // isn't legal).
24682     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
24683     Amt = DAG.getZExtOrTrunc(Amt, dl, ExVT);
24684     Amt = DAG.getNode(ISD::SUB, dl, ExVT, DAG.getConstant(8, dl, ExVT), Amt);
24685     Amt = DAG.getNode(ISD::SHL, dl, ExVT, DAG.getConstant(1, dl, ExVT), Amt);
24686     assert(ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()) &&
24687            "Constant build vector expected");
24688 
24689     if (VT == MVT::v16i8 && Subtarget.hasInt256()) {
24690       R = Opc == ISD::SRA ? DAG.getSExtOrTrunc(R, dl, ExVT)
24691                           : DAG.getZExtOrTrunc(R, dl, ExVT);
24692       R = DAG.getNode(ISD::MUL, dl, ExVT, R, Amt);
24693       R = DAG.getNode(X86ISD::VSRLI, dl, ExVT, R, Cst8);
24694       return DAG.getZExtOrTrunc(R, dl, VT);
24695     }
24696 
24697     SmallVector<SDValue, 16> LoAmt, HiAmt;
24698     for (int i = 0; i != NumElts; i += 16) {
24699       for (int j = 0; j != 8; ++j) {
24700         LoAmt.push_back(Amt.getOperand(i + j));
24701         HiAmt.push_back(Amt.getOperand(i + j + 8));
24702       }
24703     }
24704 
24705     MVT VT16 = MVT::getVectorVT(MVT::i16, NumElts / 2);
24706     SDValue LoA = DAG.getBuildVector(VT16, dl, LoAmt);
24707     SDValue HiA = DAG.getBuildVector(VT16, dl, HiAmt);
24708 
24709     SDValue LoR = DAG.getBitcast(VT16, getUnpackl(DAG, dl, VT, R, R));
24710     SDValue HiR = DAG.getBitcast(VT16, getUnpackh(DAG, dl, VT, R, R));
24711     LoR = DAG.getNode(X86OpcI, dl, VT16, LoR, Cst8);
24712     HiR = DAG.getNode(X86OpcI, dl, VT16, HiR, Cst8);
24713     LoR = DAG.getNode(ISD::MUL, dl, VT16, LoR, LoA);
24714     HiR = DAG.getNode(ISD::MUL, dl, VT16, HiR, HiA);
24715     LoR = DAG.getNode(X86ISD::VSRLI, dl, VT16, LoR, Cst8);
24716     HiR = DAG.getNode(X86ISD::VSRLI, dl, VT16, HiR, Cst8);
24717     return DAG.getNode(X86ISD::PACKUS, dl, VT, LoR, HiR);
24718   }
24719 
24720   if (VT == MVT::v16i8 ||
24721       (VT == MVT::v32i8 && Subtarget.hasInt256() && !Subtarget.hasXOP()) ||
24722       (VT == MVT::v64i8 && Subtarget.hasBWI())) {
24723     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
24724 
24725     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
24726       if (VT.is512BitVector()) {
24727         // On AVX512BW targets we make use of the fact that VSELECT lowers
24728         // to a masked blend which selects bytes based just on the sign bit
24729         // extracted to a mask.
24730         MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
24731         V0 = DAG.getBitcast(VT, V0);
24732         V1 = DAG.getBitcast(VT, V1);
24733         Sel = DAG.getBitcast(VT, Sel);
24734         Sel = DAG.getSetCC(dl, MaskVT, DAG.getConstant(0, dl, VT), Sel,
24735                            ISD::SETGT);
24736         return DAG.getBitcast(SelVT, DAG.getSelect(dl, VT, Sel, V0, V1));
24737       } else if (Subtarget.hasSSE41()) {
24738         // On SSE41 targets we make use of the fact that VSELECT lowers
24739         // to PBLENDVB which selects bytes based just on the sign bit.
24740         V0 = DAG.getBitcast(VT, V0);
24741         V1 = DAG.getBitcast(VT, V1);
24742         Sel = DAG.getBitcast(VT, Sel);
24743         return DAG.getBitcast(SelVT, DAG.getSelect(dl, VT, Sel, V0, V1));
24744       }
24745       // On pre-SSE41 targets we test for the sign bit by comparing to
24746       // zero - a negative value will set all bits of the lanes to true
24747       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
24748       SDValue Z = DAG.getConstant(0, dl, SelVT);
24749       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
24750       return DAG.getSelect(dl, SelVT, C, V0, V1);
24751     };
24752 
24753     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
24754     // We can safely do this using i16 shifts as we're only interested in
24755     // the 3 lower bits of each byte.
24756     Amt = DAG.getBitcast(ExtVT, Amt);
24757     Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ExtVT, Amt, 5, DAG);
24758     Amt = DAG.getBitcast(VT, Amt);
24759 
24760     if (Opc == ISD::SHL || Opc == ISD::SRL) {
24761       // r = VSELECT(r, shift(r, 4), a);
24762       SDValue M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(4, dl, VT));
24763       R = SignBitSelect(VT, Amt, M, R);
24764 
24765       // a += a
24766       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
24767 
24768       // r = VSELECT(r, shift(r, 2), a);
24769       M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(2, dl, VT));
24770       R = SignBitSelect(VT, Amt, M, R);
24771 
24772       // a += a
24773       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
24774 
24775       // return VSELECT(r, shift(r, 1), a);
24776       M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(1, dl, VT));
24777       R = SignBitSelect(VT, Amt, M, R);
24778       return R;
24779     }
24780 
24781     if (Opc == ISD::SRA) {
24782       // For SRA we need to unpack each byte to the higher byte of a i16 vector
24783       // so we can correctly sign extend. We don't care what happens to the
24784       // lower byte.
24785       SDValue ALo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
24786       SDValue AHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
24787       SDValue RLo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), R);
24788       SDValue RHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), R);
24789       ALo = DAG.getBitcast(ExtVT, ALo);
24790       AHi = DAG.getBitcast(ExtVT, AHi);
24791       RLo = DAG.getBitcast(ExtVT, RLo);
24792       RHi = DAG.getBitcast(ExtVT, RHi);
24793 
24794       // r = VSELECT(r, shift(r, 4), a);
24795       SDValue MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 4, DAG);
24796       SDValue MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 4, DAG);
24797       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
24798       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
24799 
24800       // a += a
24801       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
24802       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
24803 
24804       // r = VSELECT(r, shift(r, 2), a);
24805       MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 2, DAG);
24806       MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 2, DAG);
24807       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
24808       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
24809 
24810       // a += a
24811       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
24812       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
24813 
24814       // r = VSELECT(r, shift(r, 1), a);
24815       MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 1, DAG);
24816       MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 1, DAG);
24817       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
24818       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
24819 
24820       // Logical shift the result back to the lower byte, leaving a zero upper
24821       // byte meaning that we can safely pack with PACKUSWB.
24822       RLo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RLo, 8, DAG);
24823       RHi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RHi, 8, DAG);
24824       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
24825     }
24826   }
24827 
24828   if (Subtarget.hasInt256() && !Subtarget.hasXOP() && VT == MVT::v16i16) {
24829     MVT ExtVT = MVT::v8i32;
24830     SDValue Z = DAG.getConstant(0, dl, VT);
24831     SDValue ALo = getUnpackl(DAG, dl, VT, Amt, Z);
24832     SDValue AHi = getUnpackh(DAG, dl, VT, Amt, Z);
24833     SDValue RLo = getUnpackl(DAG, dl, VT, Z, R);
24834     SDValue RHi = getUnpackh(DAG, dl, VT, Z, R);
24835     ALo = DAG.getBitcast(ExtVT, ALo);
24836     AHi = DAG.getBitcast(ExtVT, AHi);
24837     RLo = DAG.getBitcast(ExtVT, RLo);
24838     RHi = DAG.getBitcast(ExtVT, RHi);
24839     SDValue Lo = DAG.getNode(Opc, dl, ExtVT, RLo, ALo);
24840     SDValue Hi = DAG.getNode(Opc, dl, ExtVT, RHi, AHi);
24841     Lo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Lo, 16, DAG);
24842     Hi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Hi, 16, DAG);
24843     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
24844   }
24845 
24846   if (VT == MVT::v8i16) {
24847     // If we have a constant shift amount, the non-SSE41 path is best as
24848     // avoiding bitcasts make it easier to constant fold and reduce to PBLENDW.
24849     bool UseSSE41 = Subtarget.hasSSE41() &&
24850                     !ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
24851 
24852     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
24853       // On SSE41 targets we make use of the fact that VSELECT lowers
24854       // to PBLENDVB which selects bytes based just on the sign bit.
24855       if (UseSSE41) {
24856         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
24857         V0 = DAG.getBitcast(ExtVT, V0);
24858         V1 = DAG.getBitcast(ExtVT, V1);
24859         Sel = DAG.getBitcast(ExtVT, Sel);
24860         return DAG.getBitcast(VT, DAG.getSelect(dl, ExtVT, Sel, V0, V1));
24861       }
24862       // On pre-SSE41 targets we splat the sign bit - a negative value will
24863       // set all bits of the lanes to true and VSELECT uses that in
24864       // its OR(AND(V0,C),AND(V1,~C)) lowering.
24865       SDValue C =
24866           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Sel, 15, DAG);
24867       return DAG.getSelect(dl, VT, C, V0, V1);
24868     };
24869 
24870     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
24871     if (UseSSE41) {
24872       // On SSE41 targets we need to replicate the shift mask in both
24873       // bytes for PBLENDVB.
24874       Amt = DAG.getNode(
24875           ISD::OR, dl, VT,
24876           getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 4, DAG),
24877           getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG));
24878     } else {
24879       Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG);
24880     }
24881 
24882     // r = VSELECT(r, shift(r, 8), a);
24883     SDValue M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 8, DAG);
24884     R = SignBitSelect(Amt, M, R);
24885 
24886     // a += a
24887     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
24888 
24889     // r = VSELECT(r, shift(r, 4), a);
24890     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 4, DAG);
24891     R = SignBitSelect(Amt, M, R);
24892 
24893     // a += a
24894     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
24895 
24896     // r = VSELECT(r, shift(r, 2), a);
24897     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 2, DAG);
24898     R = SignBitSelect(Amt, M, R);
24899 
24900     // a += a
24901     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
24902 
24903     // return VSELECT(r, shift(r, 1), a);
24904     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 1, DAG);
24905     R = SignBitSelect(Amt, M, R);
24906     return R;
24907   }
24908 
24909   // Decompose 256-bit shifts into 128-bit shifts.
24910   if (VT.is256BitVector())
24911     return split256IntArith(Op, DAG);
24912 
24913   return SDValue();
24914 }
24915 
LowerRotate(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)24916 static SDValue LowerRotate(SDValue Op, const X86Subtarget &Subtarget,
24917                            SelectionDAG &DAG) {
24918   MVT VT = Op.getSimpleValueType();
24919   assert(VT.isVector() && "Custom lowering only for vector rotates!");
24920 
24921   SDLoc DL(Op);
24922   SDValue R = Op.getOperand(0);
24923   SDValue Amt = Op.getOperand(1);
24924   unsigned Opcode = Op.getOpcode();
24925   unsigned EltSizeInBits = VT.getScalarSizeInBits();
24926   int NumElts = VT.getVectorNumElements();
24927 
24928   // Check for constant splat rotation amount.
24929   APInt UndefElts;
24930   SmallVector<APInt, 32> EltBits;
24931   int CstSplatIndex = -1;
24932   if (getTargetConstantBitsFromNode(Amt, EltSizeInBits, UndefElts, EltBits))
24933     for (int i = 0; i != NumElts; ++i)
24934       if (!UndefElts[i]) {
24935         if (CstSplatIndex < 0 || EltBits[i] == EltBits[CstSplatIndex]) {
24936           CstSplatIndex = i;
24937           continue;
24938         }
24939         CstSplatIndex = -1;
24940         break;
24941       }
24942 
24943   // AVX512 implicitly uses modulo rotation amounts.
24944   if (Subtarget.hasAVX512() && 32 <= EltSizeInBits) {
24945     // Attempt to rotate by immediate.
24946     if (0 <= CstSplatIndex) {
24947       unsigned Op = (Opcode == ISD::ROTL ? X86ISD::VROTLI : X86ISD::VROTRI);
24948       uint64_t RotateAmt = EltBits[CstSplatIndex].urem(EltSizeInBits);
24949       return DAG.getNode(Op, DL, VT, R,
24950                          DAG.getConstant(RotateAmt, DL, MVT::i8));
24951     }
24952 
24953     // Else, fall-back on VPROLV/VPRORV.
24954     return Op;
24955   }
24956 
24957   assert((Opcode == ISD::ROTL) && "Only ROTL supported");
24958 
24959   // XOP has 128-bit vector variable + immediate rotates.
24960   // +ve/-ve Amt = rotate left/right - just need to handle ISD::ROTL.
24961   // XOP implicitly uses modulo rotation amounts.
24962   if (Subtarget.hasXOP()) {
24963     if (VT.is256BitVector())
24964       return split256IntArith(Op, DAG);
24965     assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
24966 
24967     // Attempt to rotate by immediate.
24968     if (0 <= CstSplatIndex) {
24969       uint64_t RotateAmt = EltBits[CstSplatIndex].urem(EltSizeInBits);
24970       return DAG.getNode(X86ISD::VROTLI, DL, VT, R,
24971                          DAG.getConstant(RotateAmt, DL, MVT::i8));
24972     }
24973 
24974     // Use general rotate by variable (per-element).
24975     return Op;
24976   }
24977 
24978   // Split 256-bit integers on pre-AVX2 targets.
24979   if (VT.is256BitVector() && !Subtarget.hasAVX2())
24980     return split256IntArith(Op, DAG);
24981 
24982   assert((VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 ||
24983           ((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8) &&
24984            Subtarget.hasAVX2())) &&
24985          "Only vXi32/vXi16/vXi8 vector rotates supported");
24986 
24987   // Rotate by an uniform constant - expand back to shifts.
24988   if (0 <= CstSplatIndex)
24989     return SDValue();
24990 
24991   bool IsSplatAmt = DAG.isSplatValue(Amt);
24992 
24993   // v16i8/v32i8: Split rotation into rot4/rot2/rot1 stages and select by
24994   // the amount bit.
24995   if (EltSizeInBits == 8 && !IsSplatAmt) {
24996     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()))
24997       return SDValue();
24998 
24999     // We don't need ModuloAmt here as we just peek at individual bits.
25000     MVT ExtVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
25001 
25002     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
25003       if (Subtarget.hasSSE41()) {
25004         // On SSE41 targets we make use of the fact that VSELECT lowers
25005         // to PBLENDVB which selects bytes based just on the sign bit.
25006         V0 = DAG.getBitcast(VT, V0);
25007         V1 = DAG.getBitcast(VT, V1);
25008         Sel = DAG.getBitcast(VT, Sel);
25009         return DAG.getBitcast(SelVT, DAG.getSelect(DL, VT, Sel, V0, V1));
25010       }
25011       // On pre-SSE41 targets we test for the sign bit by comparing to
25012       // zero - a negative value will set all bits of the lanes to true
25013       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
25014       SDValue Z = DAG.getConstant(0, DL, SelVT);
25015       SDValue C = DAG.getNode(X86ISD::PCMPGT, DL, SelVT, Z, Sel);
25016       return DAG.getSelect(DL, SelVT, C, V0, V1);
25017     };
25018 
25019     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
25020     // We can safely do this using i16 shifts as we're only interested in
25021     // the 3 lower bits of each byte.
25022     Amt = DAG.getBitcast(ExtVT, Amt);
25023     Amt = DAG.getNode(ISD::SHL, DL, ExtVT, Amt, DAG.getConstant(5, DL, ExtVT));
25024     Amt = DAG.getBitcast(VT, Amt);
25025 
25026     // r = VSELECT(r, rot(r, 4), a);
25027     SDValue M;
25028     M = DAG.getNode(
25029         ISD::OR, DL, VT,
25030         DAG.getNode(ISD::SHL, DL, VT, R, DAG.getConstant(4, DL, VT)),
25031         DAG.getNode(ISD::SRL, DL, VT, R, DAG.getConstant(4, DL, VT)));
25032     R = SignBitSelect(VT, Amt, M, R);
25033 
25034     // a += a
25035     Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
25036 
25037     // r = VSELECT(r, rot(r, 2), a);
25038     M = DAG.getNode(
25039         ISD::OR, DL, VT,
25040         DAG.getNode(ISD::SHL, DL, VT, R, DAG.getConstant(2, DL, VT)),
25041         DAG.getNode(ISD::SRL, DL, VT, R, DAG.getConstant(6, DL, VT)));
25042     R = SignBitSelect(VT, Amt, M, R);
25043 
25044     // a += a
25045     Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
25046 
25047     // return VSELECT(r, rot(r, 1), a);
25048     M = DAG.getNode(
25049         ISD::OR, DL, VT,
25050         DAG.getNode(ISD::SHL, DL, VT, R, DAG.getConstant(1, DL, VT)),
25051         DAG.getNode(ISD::SRL, DL, VT, R, DAG.getConstant(7, DL, VT)));
25052     return SignBitSelect(VT, Amt, M, R);
25053   }
25054 
25055   // ISD::ROT* uses modulo rotate amounts.
25056   Amt = DAG.getNode(ISD::AND, DL, VT, Amt,
25057                     DAG.getConstant(EltSizeInBits - 1, DL, VT));
25058 
25059   bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
25060   bool LegalVarShifts = SupportedVectorVarShift(VT, Subtarget, ISD::SHL) &&
25061                         SupportedVectorVarShift(VT, Subtarget, ISD::SRL);
25062 
25063   // Fallback for splats + all supported variable shifts.
25064   // Fallback for non-constants AVX2 vXi16 as well.
25065   if (IsSplatAmt || LegalVarShifts || (Subtarget.hasAVX2() && !ConstantAmt)) {
25066     SDValue AmtR = DAG.getConstant(EltSizeInBits, DL, VT);
25067     AmtR = DAG.getNode(ISD::SUB, DL, VT, AmtR, Amt);
25068     SDValue SHL = DAG.getNode(ISD::SHL, DL, VT, R, Amt);
25069     SDValue SRL = DAG.getNode(ISD::SRL, DL, VT, R, AmtR);
25070     return DAG.getNode(ISD::OR, DL, VT, SHL, SRL);
25071   }
25072 
25073   // As with shifts, convert the rotation amount to a multiplication factor.
25074   SDValue Scale = convertShiftLeftToScale(Amt, DL, Subtarget, DAG);
25075   assert(Scale && "Failed to convert ROTL amount to scale");
25076 
25077   // v8i16/v16i16: perform unsigned multiply hi/lo and OR the results.
25078   if (EltSizeInBits == 16) {
25079     SDValue Lo = DAG.getNode(ISD::MUL, DL, VT, R, Scale);
25080     SDValue Hi = DAG.getNode(ISD::MULHU, DL, VT, R, Scale);
25081     return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
25082   }
25083 
25084   // v4i32: make use of the PMULUDQ instruction to multiply 2 lanes of v4i32
25085   // to v2i64 results at a time. The upper 32-bits contain the wrapped bits
25086   // that can then be OR'd with the lower 32-bits.
25087   assert(VT == MVT::v4i32 && "Only v4i32 vector rotate expected");
25088   static const int OddMask[] = {1, -1, 3, -1};
25089   SDValue R13 = DAG.getVectorShuffle(VT, DL, R, R, OddMask);
25090   SDValue Scale13 = DAG.getVectorShuffle(VT, DL, Scale, Scale, OddMask);
25091 
25092   SDValue Res02 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
25093                               DAG.getBitcast(MVT::v2i64, R),
25094                               DAG.getBitcast(MVT::v2i64, Scale));
25095   SDValue Res13 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
25096                               DAG.getBitcast(MVT::v2i64, R13),
25097                               DAG.getBitcast(MVT::v2i64, Scale13));
25098   Res02 = DAG.getBitcast(VT, Res02);
25099   Res13 = DAG.getBitcast(VT, Res13);
25100 
25101   return DAG.getNode(ISD::OR, DL, VT,
25102                      DAG.getVectorShuffle(VT, DL, Res02, Res13, {0, 4, 2, 6}),
25103                      DAG.getVectorShuffle(VT, DL, Res02, Res13, {1, 5, 3, 7}));
25104 }
25105 
25106 /// Returns true if the operand type is exactly twice the native width, and
25107 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
25108 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
25109 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
needsCmpXchgNb(Type * MemType) const25110 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
25111   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
25112 
25113   if (OpWidth == 64)
25114     return !Subtarget.is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
25115   else if (OpWidth == 128)
25116     return Subtarget.hasCmpxchg16b();
25117   else
25118     return false;
25119 }
25120 
shouldExpandAtomicStoreInIR(StoreInst * SI) const25121 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
25122   return needsCmpXchgNb(SI->getValueOperand()->getType());
25123 }
25124 
25125 // Note: this turns large loads into lock cmpxchg8b/16b.
25126 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
25127 TargetLowering::AtomicExpansionKind
shouldExpandAtomicLoadInIR(LoadInst * LI) const25128 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
25129   auto PTy = cast<PointerType>(LI->getPointerOperandType());
25130   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
25131                                                : AtomicExpansionKind::None;
25132 }
25133 
25134 TargetLowering::AtomicExpansionKind
shouldExpandAtomicRMWInIR(AtomicRMWInst * AI) const25135 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
25136   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
25137   Type *MemType = AI->getType();
25138 
25139   // If the operand is too big, we must see if cmpxchg8/16b is available
25140   // and default to library calls otherwise.
25141   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
25142     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
25143                                    : AtomicExpansionKind::None;
25144   }
25145 
25146   AtomicRMWInst::BinOp Op = AI->getOperation();
25147   switch (Op) {
25148   default:
25149     llvm_unreachable("Unknown atomic operation");
25150   case AtomicRMWInst::Xchg:
25151   case AtomicRMWInst::Add:
25152   case AtomicRMWInst::Sub:
25153     // It's better to use xadd, xsub or xchg for these in all cases.
25154     return AtomicExpansionKind::None;
25155   case AtomicRMWInst::Or:
25156   case AtomicRMWInst::And:
25157   case AtomicRMWInst::Xor:
25158     // If the atomicrmw's result isn't actually used, we can just add a "lock"
25159     // prefix to a normal instruction for these operations.
25160     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
25161                             : AtomicExpansionKind::None;
25162   case AtomicRMWInst::Nand:
25163   case AtomicRMWInst::Max:
25164   case AtomicRMWInst::Min:
25165   case AtomicRMWInst::UMax:
25166   case AtomicRMWInst::UMin:
25167     // These always require a non-trivial set of data operations on x86. We must
25168     // use a cmpxchg loop.
25169     return AtomicExpansionKind::CmpXChg;
25170   }
25171 }
25172 
25173 LoadInst *
lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst * AI) const25174 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
25175   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
25176   Type *MemType = AI->getType();
25177   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
25178   // there is no benefit in turning such RMWs into loads, and it is actually
25179   // harmful as it introduces a mfence.
25180   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
25181     return nullptr;
25182 
25183   auto Builder = IRBuilder<>(AI);
25184   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
25185   auto SSID = AI->getSyncScopeID();
25186   // We must restrict the ordering to avoid generating loads with Release or
25187   // ReleaseAcquire orderings.
25188   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
25189   auto Ptr = AI->getPointerOperand();
25190 
25191   // Before the load we need a fence. Here is an example lifted from
25192   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
25193   // is required:
25194   // Thread 0:
25195   //   x.store(1, relaxed);
25196   //   r1 = y.fetch_add(0, release);
25197   // Thread 1:
25198   //   y.fetch_add(42, acquire);
25199   //   r2 = x.load(relaxed);
25200   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
25201   // lowered to just a load without a fence. A mfence flushes the store buffer,
25202   // making the optimization clearly correct.
25203   // FIXME: it is required if isReleaseOrStronger(Order) but it is not clear
25204   // otherwise, we might be able to be more aggressive on relaxed idempotent
25205   // rmw. In practice, they do not look useful, so we don't try to be
25206   // especially clever.
25207   if (SSID == SyncScope::SingleThread)
25208     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
25209     // the IR level, so we must wrap it in an intrinsic.
25210     return nullptr;
25211 
25212   if (!Subtarget.hasMFence())
25213     // FIXME: it might make sense to use a locked operation here but on a
25214     // different cache-line to prevent cache-line bouncing. In practice it
25215     // is probably a small win, and x86 processors without mfence are rare
25216     // enough that we do not bother.
25217     return nullptr;
25218 
25219   Function *MFence =
25220       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
25221   Builder.CreateCall(MFence, {});
25222 
25223   // Finally we can emit the atomic load.
25224   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
25225           AI->getType()->getPrimitiveSizeInBits());
25226   Loaded->setAtomic(Order, SSID);
25227   AI->replaceAllUsesWith(Loaded);
25228   AI->eraseFromParent();
25229   return Loaded;
25230 }
25231 
LowerATOMIC_FENCE(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)25232 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget &Subtarget,
25233                                  SelectionDAG &DAG) {
25234   SDLoc dl(Op);
25235   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
25236     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
25237   SyncScope::ID FenceSSID = static_cast<SyncScope::ID>(
25238     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
25239 
25240   // The only fence that needs an instruction is a sequentially-consistent
25241   // cross-thread fence.
25242   if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
25243       FenceSSID == SyncScope::System) {
25244     if (Subtarget.hasMFence())
25245       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
25246 
25247     SDValue Chain = Op.getOperand(0);
25248     SDValue Zero = DAG.getTargetConstant(0, dl, MVT::i32);
25249     SDValue Ops[] = {
25250       DAG.getRegister(X86::ESP, MVT::i32),     // Base
25251       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
25252       DAG.getRegister(0, MVT::i32),            // Index
25253       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
25254       DAG.getRegister(0, MVT::i32),            // Segment.
25255       Zero,
25256       Chain
25257     };
25258     SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, dl, MVT::Other, Ops);
25259     return SDValue(Res, 0);
25260   }
25261 
25262   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
25263   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
25264 }
25265 
LowerCMP_SWAP(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)25266 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget &Subtarget,
25267                              SelectionDAG &DAG) {
25268   MVT T = Op.getSimpleValueType();
25269   SDLoc DL(Op);
25270   unsigned Reg = 0;
25271   unsigned size = 0;
25272   switch(T.SimpleTy) {
25273   default: llvm_unreachable("Invalid value type!");
25274   case MVT::i8:  Reg = X86::AL;  size = 1; break;
25275   case MVT::i16: Reg = X86::AX;  size = 2; break;
25276   case MVT::i32: Reg = X86::EAX; size = 4; break;
25277   case MVT::i64:
25278     assert(Subtarget.is64Bit() && "Node not type legal!");
25279     Reg = X86::RAX; size = 8;
25280     break;
25281   }
25282   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
25283                                   Op.getOperand(2), SDValue());
25284   SDValue Ops[] = { cpIn.getValue(0),
25285                     Op.getOperand(1),
25286                     Op.getOperand(3),
25287                     DAG.getTargetConstant(size, DL, MVT::i8),
25288                     cpIn.getValue(1) };
25289   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
25290   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
25291   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
25292                                            Ops, T, MMO);
25293 
25294   SDValue cpOut =
25295     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
25296   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
25297                                       MVT::i32, cpOut.getValue(2));
25298   SDValue Success = getSETCC(X86::COND_E, EFLAGS, DL, DAG);
25299 
25300   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
25301   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
25302   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
25303   return SDValue();
25304 }
25305 
25306 // Create MOVMSKB, taking into account whether we need to split for AVX1.
getPMOVMSKB(const SDLoc & DL,SDValue V,SelectionDAG & DAG,const X86Subtarget & Subtarget)25307 static SDValue getPMOVMSKB(const SDLoc &DL, SDValue V, SelectionDAG &DAG,
25308                            const X86Subtarget &Subtarget) {
25309   MVT InVT = V.getSimpleValueType();
25310 
25311   if (InVT == MVT::v32i8 && !Subtarget.hasInt256()) {
25312     SDValue Lo, Hi;
25313     std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
25314     Lo = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Lo);
25315     Hi = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Hi);
25316     Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
25317                      DAG.getConstant(16, DL, MVT::i8));
25318     return DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi);
25319   }
25320 
25321   return DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
25322 }
25323 
LowerBITCAST(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)25324 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget &Subtarget,
25325                             SelectionDAG &DAG) {
25326   SDValue Src = Op.getOperand(0);
25327   MVT SrcVT = Src.getSimpleValueType();
25328   MVT DstVT = Op.getSimpleValueType();
25329 
25330   // Legalize (v64i1 (bitcast i64 (X))) by splitting the i64, bitcasting each
25331   // half to v32i1 and concatenating the result.
25332   if (SrcVT == MVT::i64 && DstVT == MVT::v64i1) {
25333     assert(!Subtarget.is64Bit() && "Expected 32-bit mode");
25334     assert(Subtarget.hasBWI() && "Expected BWI target");
25335     SDLoc dl(Op);
25336     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Src,
25337                              DAG.getIntPtrConstant(0, dl));
25338     Lo = DAG.getBitcast(MVT::v32i1, Lo);
25339     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Src,
25340                              DAG.getIntPtrConstant(1, dl));
25341     Hi = DAG.getBitcast(MVT::v32i1, Hi);
25342     return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
25343   }
25344 
25345   // Custom splitting for BWI types when AVX512F is available but BWI isn't.
25346   if ((SrcVT == MVT::v32i16 || SrcVT == MVT::v64i8) && DstVT.isVector() &&
25347     DAG.getTargetLoweringInfo().isTypeLegal(DstVT)) {
25348     SDLoc dl(Op);
25349     SDValue Lo, Hi;
25350     std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
25351     EVT CastVT = MVT::getVectorVT(DstVT.getVectorElementType(),
25352                                   DstVT.getVectorNumElements() / 2);
25353     Lo = DAG.getBitcast(CastVT, Lo);
25354     Hi = DAG.getBitcast(CastVT, Hi);
25355     return DAG.getNode(ISD::CONCAT_VECTORS, dl, DstVT, Lo, Hi);
25356   }
25357 
25358   // Use MOVMSK for vector to scalar conversion to prevent scalarization.
25359   if ((SrcVT == MVT::v16i1 || SrcVT == MVT::v32i1) && DstVT.isScalarInteger()) {
25360     assert(!Subtarget.hasAVX512() && "Should use K-registers with AVX512");
25361     MVT SExtVT = SrcVT == MVT::v16i1 ? MVT::v16i8 : MVT::v32i8;
25362     SDLoc DL(Op);
25363     SDValue V = DAG.getSExtOrTrunc(Src, DL, SExtVT);
25364     V = getPMOVMSKB(DL, V, DAG, Subtarget);
25365     return DAG.getZExtOrTrunc(V, DL, DstVT);
25366   }
25367 
25368   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 ||
25369       SrcVT == MVT::i64) {
25370     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
25371     if (DstVT != MVT::f64 && DstVT != MVT::i64 &&
25372         !(DstVT == MVT::x86mmx && SrcVT.isVector()))
25373       // This conversion needs to be expanded.
25374       return SDValue();
25375 
25376     SDLoc dl(Op);
25377     if (SrcVT.isVector()) {
25378       // Widen the vector in input in the case of MVT::v2i32.
25379       // Example: from MVT::v2i32 to MVT::v4i32.
25380       MVT NewVT = MVT::getVectorVT(SrcVT.getVectorElementType(),
25381                                    SrcVT.getVectorNumElements() * 2);
25382       Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewVT, Src,
25383                         DAG.getUNDEF(SrcVT));
25384     } else {
25385       assert(SrcVT == MVT::i64 && !Subtarget.is64Bit() &&
25386              "Unexpected source type in LowerBITCAST");
25387       Src = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Src);
25388     }
25389 
25390     MVT V2X64VT = DstVT == MVT::f64 ? MVT::v2f64 : MVT::v2i64;
25391     Src = DAG.getNode(ISD::BITCAST, dl, V2X64VT, Src);
25392 
25393     if (DstVT == MVT::x86mmx)
25394       return DAG.getNode(X86ISD::MOVDQ2Q, dl, DstVT, Src);
25395 
25396     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, DstVT, Src,
25397                        DAG.getIntPtrConstant(0, dl));
25398   }
25399 
25400   assert(Subtarget.is64Bit() && !Subtarget.hasSSE2() &&
25401          Subtarget.hasMMX() && "Unexpected custom BITCAST");
25402   assert((DstVT == MVT::i64 ||
25403           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
25404          "Unexpected custom BITCAST");
25405   // i64 <=> MMX conversions are Legal.
25406   if (SrcVT==MVT::i64 && DstVT.isVector())
25407     return Op;
25408   if (DstVT==MVT::i64 && SrcVT.isVector())
25409     return Op;
25410   // MMX <=> MMX conversions are Legal.
25411   if (SrcVT.isVector() && DstVT.isVector())
25412     return Op;
25413   // All other conversions need to be expanded.
25414   return SDValue();
25415 }
25416 
25417 /// Compute the horizontal sum of bytes in V for the elements of VT.
25418 ///
25419 /// Requires V to be a byte vector and VT to be an integer vector type with
25420 /// wider elements than V's type. The width of the elements of VT determines
25421 /// how many bytes of V are summed horizontally to produce each element of the
25422 /// result.
LowerHorizontalByteSum(SDValue V,MVT VT,const X86Subtarget & Subtarget,SelectionDAG & DAG)25423 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
25424                                       const X86Subtarget &Subtarget,
25425                                       SelectionDAG &DAG) {
25426   SDLoc DL(V);
25427   MVT ByteVecVT = V.getSimpleValueType();
25428   MVT EltVT = VT.getVectorElementType();
25429   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
25430          "Expected value to have byte element type.");
25431   assert(EltVT != MVT::i8 &&
25432          "Horizontal byte sum only makes sense for wider elements!");
25433   unsigned VecSize = VT.getSizeInBits();
25434   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
25435 
25436   // PSADBW instruction horizontally add all bytes and leave the result in i64
25437   // chunks, thus directly computes the pop count for v2i64 and v4i64.
25438   if (EltVT == MVT::i64) {
25439     SDValue Zeros = DAG.getConstant(0, DL, ByteVecVT);
25440     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
25441     V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
25442     return DAG.getBitcast(VT, V);
25443   }
25444 
25445   if (EltVT == MVT::i32) {
25446     // We unpack the low half and high half into i32s interleaved with zeros so
25447     // that we can use PSADBW to horizontally sum them. The most useful part of
25448     // this is that it lines up the results of two PSADBW instructions to be
25449     // two v2i64 vectors which concatenated are the 4 population counts. We can
25450     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
25451     SDValue Zeros = DAG.getConstant(0, DL, VT);
25452     SDValue V32 = DAG.getBitcast(VT, V);
25453     SDValue Low = getUnpackl(DAG, DL, VT, V32, Zeros);
25454     SDValue High = getUnpackh(DAG, DL, VT, V32, Zeros);
25455 
25456     // Do the horizontal sums into two v2i64s.
25457     Zeros = DAG.getConstant(0, DL, ByteVecVT);
25458     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
25459     Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
25460                       DAG.getBitcast(ByteVecVT, Low), Zeros);
25461     High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
25462                        DAG.getBitcast(ByteVecVT, High), Zeros);
25463 
25464     // Merge them together.
25465     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
25466     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
25467                     DAG.getBitcast(ShortVecVT, Low),
25468                     DAG.getBitcast(ShortVecVT, High));
25469 
25470     return DAG.getBitcast(VT, V);
25471   }
25472 
25473   // The only element type left is i16.
25474   assert(EltVT == MVT::i16 && "Unknown how to handle type");
25475 
25476   // To obtain pop count for each i16 element starting from the pop count for
25477   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
25478   // right by 8. It is important to shift as i16s as i8 vector shift isn't
25479   // directly supported.
25480   SDValue ShifterV = DAG.getConstant(8, DL, VT);
25481   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
25482   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
25483                   DAG.getBitcast(ByteVecVT, V));
25484   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
25485 }
25486 
LowerVectorCTPOPInRegLUT(SDValue Op,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)25487 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, const SDLoc &DL,
25488                                         const X86Subtarget &Subtarget,
25489                                         SelectionDAG &DAG) {
25490   MVT VT = Op.getSimpleValueType();
25491   MVT EltVT = VT.getVectorElementType();
25492   int NumElts = VT.getVectorNumElements();
25493   (void)EltVT;
25494   assert(EltVT == MVT::i8 && "Only vXi8 vector CTPOP lowering supported.");
25495 
25496   // Implement a lookup table in register by using an algorithm based on:
25497   // http://wm.ite.pl/articles/sse-popcount.html
25498   //
25499   // The general idea is that every lower byte nibble in the input vector is an
25500   // index into a in-register pre-computed pop count table. We then split up the
25501   // input vector in two new ones: (1) a vector with only the shifted-right
25502   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
25503   // masked out higher ones) for each byte. PSHUFB is used separately with both
25504   // to index the in-register table. Next, both are added and the result is a
25505   // i8 vector where each element contains the pop count for input byte.
25506   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
25507                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
25508                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
25509                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
25510 
25511   SmallVector<SDValue, 64> LUTVec;
25512   for (int i = 0; i < NumElts; ++i)
25513     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
25514   SDValue InRegLUT = DAG.getBuildVector(VT, DL, LUTVec);
25515   SDValue M0F = DAG.getConstant(0x0F, DL, VT);
25516 
25517   // High nibbles
25518   SDValue FourV = DAG.getConstant(4, DL, VT);
25519   SDValue HiNibbles = DAG.getNode(ISD::SRL, DL, VT, Op, FourV);
25520 
25521   // Low nibbles
25522   SDValue LoNibbles = DAG.getNode(ISD::AND, DL, VT, Op, M0F);
25523 
25524   // The input vector is used as the shuffle mask that index elements into the
25525   // LUT. After counting low and high nibbles, add the vector to obtain the
25526   // final pop count per i8 element.
25527   SDValue HiPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, HiNibbles);
25528   SDValue LoPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, LoNibbles);
25529   return DAG.getNode(ISD::ADD, DL, VT, HiPopCnt, LoPopCnt);
25530 }
25531 
25532 // Please ensure that any codegen change from LowerVectorCTPOP is reflected in
25533 // updated cost models in X86TTIImpl::getIntrinsicInstrCost.
LowerVectorCTPOP(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)25534 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget &Subtarget,
25535                                 SelectionDAG &DAG) {
25536   MVT VT = Op.getSimpleValueType();
25537   assert((VT.is512BitVector() || VT.is256BitVector() || VT.is128BitVector()) &&
25538          "Unknown CTPOP type to handle");
25539   SDLoc DL(Op.getNode());
25540   SDValue Op0 = Op.getOperand(0);
25541 
25542   // TRUNC(CTPOP(ZEXT(X))) to make use of vXi32/vXi64 VPOPCNT instructions.
25543   if (Subtarget.hasVPOPCNTDQ()) {
25544     unsigned NumElems = VT.getVectorNumElements();
25545     assert((VT.getVectorElementType() == MVT::i8 ||
25546             VT.getVectorElementType() == MVT::i16) && "Unexpected type");
25547     if (NumElems < 16 || (NumElems == 16 && Subtarget.canExtendTo512DQ())) {
25548       MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
25549       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, Op0);
25550       Op = DAG.getNode(ISD::CTPOP, DL, NewVT, Op);
25551       return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
25552     }
25553   }
25554 
25555   // Decompose 256-bit ops into smaller 128-bit ops.
25556   if (VT.is256BitVector() && !Subtarget.hasInt256())
25557     return Lower256IntUnary(Op, DAG);
25558 
25559   // Decompose 512-bit ops into smaller 256-bit ops.
25560   if (VT.is512BitVector() && !Subtarget.hasBWI())
25561     return Lower512IntUnary(Op, DAG);
25562 
25563   // For element types greater than i8, do vXi8 pop counts and a bytesum.
25564   if (VT.getScalarType() != MVT::i8) {
25565     MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
25566     SDValue ByteOp = DAG.getBitcast(ByteVT, Op0);
25567     SDValue PopCnt8 = DAG.getNode(ISD::CTPOP, DL, ByteVT, ByteOp);
25568     return LowerHorizontalByteSum(PopCnt8, VT, Subtarget, DAG);
25569   }
25570 
25571   // We can't use the fast LUT approach, so fall back on LegalizeDAG.
25572   if (!Subtarget.hasSSSE3())
25573     return SDValue();
25574 
25575   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
25576 }
25577 
LowerCTPOP(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)25578 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget &Subtarget,
25579                           SelectionDAG &DAG) {
25580   assert(Op.getSimpleValueType().isVector() &&
25581          "We only do custom lowering for vector population count.");
25582   return LowerVectorCTPOP(Op, Subtarget, DAG);
25583 }
25584 
LowerBITREVERSE_XOP(SDValue Op,SelectionDAG & DAG)25585 static SDValue LowerBITREVERSE_XOP(SDValue Op, SelectionDAG &DAG) {
25586   MVT VT = Op.getSimpleValueType();
25587   SDValue In = Op.getOperand(0);
25588   SDLoc DL(Op);
25589 
25590   // For scalars, its still beneficial to transfer to/from the SIMD unit to
25591   // perform the BITREVERSE.
25592   if (!VT.isVector()) {
25593     MVT VecVT = MVT::getVectorVT(VT, 128 / VT.getSizeInBits());
25594     SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, In);
25595     Res = DAG.getNode(ISD::BITREVERSE, DL, VecVT, Res);
25596     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Res,
25597                        DAG.getIntPtrConstant(0, DL));
25598   }
25599 
25600   int NumElts = VT.getVectorNumElements();
25601   int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
25602 
25603   // Decompose 256-bit ops into smaller 128-bit ops.
25604   if (VT.is256BitVector())
25605     return Lower256IntUnary(Op, DAG);
25606 
25607   assert(VT.is128BitVector() &&
25608          "Only 128-bit vector bitreverse lowering supported.");
25609 
25610   // VPPERM reverses the bits of a byte with the permute Op (2 << 5), and we
25611   // perform the BSWAP in the shuffle.
25612   // Its best to shuffle using the second operand as this will implicitly allow
25613   // memory folding for multiple vectors.
25614   SmallVector<SDValue, 16> MaskElts;
25615   for (int i = 0; i != NumElts; ++i) {
25616     for (int j = ScalarSizeInBytes - 1; j >= 0; --j) {
25617       int SourceByte = 16 + (i * ScalarSizeInBytes) + j;
25618       int PermuteByte = SourceByte | (2 << 5);
25619       MaskElts.push_back(DAG.getConstant(PermuteByte, DL, MVT::i8));
25620     }
25621   }
25622 
25623   SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, MaskElts);
25624   SDValue Res = DAG.getBitcast(MVT::v16i8, In);
25625   Res = DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, DAG.getUNDEF(MVT::v16i8),
25626                     Res, Mask);
25627   return DAG.getBitcast(VT, Res);
25628 }
25629 
LowerBITREVERSE(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)25630 static SDValue LowerBITREVERSE(SDValue Op, const X86Subtarget &Subtarget,
25631                                SelectionDAG &DAG) {
25632   MVT VT = Op.getSimpleValueType();
25633 
25634   if (Subtarget.hasXOP() && !VT.is512BitVector())
25635     return LowerBITREVERSE_XOP(Op, DAG);
25636 
25637   assert(Subtarget.hasSSSE3() && "SSSE3 required for BITREVERSE");
25638 
25639   SDValue In = Op.getOperand(0);
25640   SDLoc DL(Op);
25641 
25642   unsigned NumElts = VT.getVectorNumElements();
25643   assert(VT.getScalarType() == MVT::i8 &&
25644          "Only byte vector BITREVERSE supported");
25645 
25646   // Decompose 256-bit ops into smaller 128-bit ops on pre-AVX2.
25647   if (VT.is256BitVector() && !Subtarget.hasInt256())
25648     return Lower256IntUnary(Op, DAG);
25649 
25650   // Perform BITREVERSE using PSHUFB lookups. Each byte is split into
25651   // two nibbles and a PSHUFB lookup to find the bitreverse of each
25652   // 0-15 value (moved to the other nibble).
25653   SDValue NibbleMask = DAG.getConstant(0xF, DL, VT);
25654   SDValue Lo = DAG.getNode(ISD::AND, DL, VT, In, NibbleMask);
25655   SDValue Hi = DAG.getNode(ISD::SRL, DL, VT, In, DAG.getConstant(4, DL, VT));
25656 
25657   const int LoLUT[16] = {
25658       /* 0 */ 0x00, /* 1 */ 0x80, /* 2 */ 0x40, /* 3 */ 0xC0,
25659       /* 4 */ 0x20, /* 5 */ 0xA0, /* 6 */ 0x60, /* 7 */ 0xE0,
25660       /* 8 */ 0x10, /* 9 */ 0x90, /* a */ 0x50, /* b */ 0xD0,
25661       /* c */ 0x30, /* d */ 0xB0, /* e */ 0x70, /* f */ 0xF0};
25662   const int HiLUT[16] = {
25663       /* 0 */ 0x00, /* 1 */ 0x08, /* 2 */ 0x04, /* 3 */ 0x0C,
25664       /* 4 */ 0x02, /* 5 */ 0x0A, /* 6 */ 0x06, /* 7 */ 0x0E,
25665       /* 8 */ 0x01, /* 9 */ 0x09, /* a */ 0x05, /* b */ 0x0D,
25666       /* c */ 0x03, /* d */ 0x0B, /* e */ 0x07, /* f */ 0x0F};
25667 
25668   SmallVector<SDValue, 16> LoMaskElts, HiMaskElts;
25669   for (unsigned i = 0; i < NumElts; ++i) {
25670     LoMaskElts.push_back(DAG.getConstant(LoLUT[i % 16], DL, MVT::i8));
25671     HiMaskElts.push_back(DAG.getConstant(HiLUT[i % 16], DL, MVT::i8));
25672   }
25673 
25674   SDValue LoMask = DAG.getBuildVector(VT, DL, LoMaskElts);
25675   SDValue HiMask = DAG.getBuildVector(VT, DL, HiMaskElts);
25676   Lo = DAG.getNode(X86ISD::PSHUFB, DL, VT, LoMask, Lo);
25677   Hi = DAG.getNode(X86ISD::PSHUFB, DL, VT, HiMask, Hi);
25678   return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
25679 }
25680 
lowerAtomicArithWithLOCK(SDValue N,SelectionDAG & DAG,const X86Subtarget & Subtarget)25681 static SDValue lowerAtomicArithWithLOCK(SDValue N, SelectionDAG &DAG,
25682                                         const X86Subtarget &Subtarget) {
25683   unsigned NewOpc = 0;
25684   switch (N->getOpcode()) {
25685   case ISD::ATOMIC_LOAD_ADD:
25686     NewOpc = X86ISD::LADD;
25687     break;
25688   case ISD::ATOMIC_LOAD_SUB:
25689     NewOpc = X86ISD::LSUB;
25690     break;
25691   case ISD::ATOMIC_LOAD_OR:
25692     NewOpc = X86ISD::LOR;
25693     break;
25694   case ISD::ATOMIC_LOAD_XOR:
25695     NewOpc = X86ISD::LXOR;
25696     break;
25697   case ISD::ATOMIC_LOAD_AND:
25698     NewOpc = X86ISD::LAND;
25699     break;
25700   default:
25701     llvm_unreachable("Unknown ATOMIC_LOAD_ opcode");
25702   }
25703 
25704   MachineMemOperand *MMO = cast<MemSDNode>(N)->getMemOperand();
25705 
25706   return DAG.getMemIntrinsicNode(
25707       NewOpc, SDLoc(N), DAG.getVTList(MVT::i32, MVT::Other),
25708       {N->getOperand(0), N->getOperand(1), N->getOperand(2)},
25709       /*MemVT=*/N->getSimpleValueType(0), MMO);
25710 }
25711 
25712 /// Lower atomic_load_ops into LOCK-prefixed operations.
lowerAtomicArith(SDValue N,SelectionDAG & DAG,const X86Subtarget & Subtarget)25713 static SDValue lowerAtomicArith(SDValue N, SelectionDAG &DAG,
25714                                 const X86Subtarget &Subtarget) {
25715   SDValue Chain = N->getOperand(0);
25716   SDValue LHS = N->getOperand(1);
25717   SDValue RHS = N->getOperand(2);
25718   unsigned Opc = N->getOpcode();
25719   MVT VT = N->getSimpleValueType(0);
25720   SDLoc DL(N);
25721 
25722   // We can lower atomic_load_add into LXADD. However, any other atomicrmw op
25723   // can only be lowered when the result is unused.  They should have already
25724   // been transformed into a cmpxchg loop in AtomicExpand.
25725   if (N->hasAnyUseOfValue(0)) {
25726     // Handle (atomic_load_sub p, v) as (atomic_load_add p, -v), to be able to
25727     // select LXADD if LOCK_SUB can't be selected.
25728     if (Opc == ISD::ATOMIC_LOAD_SUB) {
25729       AtomicSDNode *AN = cast<AtomicSDNode>(N.getNode());
25730       RHS = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), RHS);
25731       return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, VT, Chain, LHS,
25732                            RHS, AN->getMemOperand());
25733     }
25734     assert(Opc == ISD::ATOMIC_LOAD_ADD &&
25735            "Used AtomicRMW ops other than Add should have been expanded!");
25736     return N;
25737   }
25738 
25739   SDValue LockOp = lowerAtomicArithWithLOCK(N, DAG, Subtarget);
25740   // RAUW the chain, but don't worry about the result, as it's unused.
25741   assert(!N->hasAnyUseOfValue(0));
25742   DAG.ReplaceAllUsesOfValueWith(N.getValue(1), LockOp.getValue(1));
25743   return SDValue();
25744 }
25745 
LowerATOMIC_STORE(SDValue Op,SelectionDAG & DAG)25746 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
25747   SDNode *Node = Op.getNode();
25748   SDLoc dl(Node);
25749   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
25750 
25751   // Convert seq_cst store -> xchg
25752   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
25753   // FIXME: On 32-bit, store -> fist or movq would be more efficient
25754   //        (The only way to get a 16-byte store is cmpxchg16b)
25755   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
25756   if (cast<AtomicSDNode>(Node)->getOrdering() ==
25757           AtomicOrdering::SequentiallyConsistent ||
25758       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
25759     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
25760                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
25761                                  Node->getOperand(0),
25762                                  Node->getOperand(1), Node->getOperand(2),
25763                                  cast<AtomicSDNode>(Node)->getMemOperand());
25764     return Swap.getValue(1);
25765   }
25766   // Other atomic stores have a simple pattern.
25767   return Op;
25768 }
25769 
LowerADDSUBCARRY(SDValue Op,SelectionDAG & DAG)25770 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
25771   SDNode *N = Op.getNode();
25772   MVT VT = N->getSimpleValueType(0);
25773 
25774   // Let legalize expand this if it isn't a legal type yet.
25775   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25776     return SDValue();
25777 
25778   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
25779   SDLoc DL(N);
25780 
25781   // Set the carry flag.
25782   SDValue Carry = Op.getOperand(2);
25783   EVT CarryVT = Carry.getValueType();
25784   APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits());
25785   Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
25786                       Carry, DAG.getConstant(NegOne, DL, CarryVT));
25787 
25788   unsigned Opc = Op.getOpcode() == ISD::ADDCARRY ? X86ISD::ADC : X86ISD::SBB;
25789   SDValue Sum = DAG.getNode(Opc, DL, VTs, Op.getOperand(0),
25790                             Op.getOperand(1), Carry.getValue(1));
25791 
25792   SDValue SetCC = getSETCC(X86::COND_B, Sum.getValue(1), DL, DAG);
25793   if (N->getValueType(1) == MVT::i1)
25794     SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
25795 
25796   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
25797 }
25798 
LowerFSINCOS(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)25799 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget &Subtarget,
25800                             SelectionDAG &DAG) {
25801   assert(Subtarget.isTargetDarwin() && Subtarget.is64Bit());
25802 
25803   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
25804   // which returns the values as { float, float } (in XMM0) or
25805   // { double, double } (which is returned in XMM0, XMM1).
25806   SDLoc dl(Op);
25807   SDValue Arg = Op.getOperand(0);
25808   EVT ArgVT = Arg.getValueType();
25809   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
25810 
25811   TargetLowering::ArgListTy Args;
25812   TargetLowering::ArgListEntry Entry;
25813 
25814   Entry.Node = Arg;
25815   Entry.Ty = ArgTy;
25816   Entry.IsSExt = false;
25817   Entry.IsZExt = false;
25818   Args.push_back(Entry);
25819 
25820   bool isF64 = ArgVT == MVT::f64;
25821   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
25822   // the small struct {f32, f32} is returned in (eax, edx). For f64,
25823   // the results are returned via SRet in memory.
25824   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25825   RTLIB::Libcall LC = isF64 ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
25826   const char *LibcallName = TLI.getLibcallName(LC);
25827   SDValue Callee =
25828       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
25829 
25830   Type *RetTy = isF64 ? (Type *)StructType::get(ArgTy, ArgTy)
25831                       : (Type *)VectorType::get(ArgTy, 4);
25832 
25833   TargetLowering::CallLoweringInfo CLI(DAG);
25834   CLI.setDebugLoc(dl)
25835       .setChain(DAG.getEntryNode())
25836       .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args));
25837 
25838   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
25839 
25840   if (isF64)
25841     // Returned in xmm0 and xmm1.
25842     return CallResult.first;
25843 
25844   // Returned in bits 0:31 and 32:64 xmm0.
25845   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
25846                                CallResult.first, DAG.getIntPtrConstant(0, dl));
25847   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
25848                                CallResult.first, DAG.getIntPtrConstant(1, dl));
25849   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
25850   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
25851 }
25852 
25853 /// Widen a vector input to a vector of NVT.  The
25854 /// input vector must have the same element type as NVT.
ExtendToType(SDValue InOp,MVT NVT,SelectionDAG & DAG,bool FillWithZeroes=false)25855 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
25856                             bool FillWithZeroes = false) {
25857   // Check if InOp already has the right width.
25858   MVT InVT = InOp.getSimpleValueType();
25859   if (InVT == NVT)
25860     return InOp;
25861 
25862   if (InOp.isUndef())
25863     return DAG.getUNDEF(NVT);
25864 
25865   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
25866          "input and widen element type must match");
25867 
25868   unsigned InNumElts = InVT.getVectorNumElements();
25869   unsigned WidenNumElts = NVT.getVectorNumElements();
25870   assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
25871          "Unexpected request for vector widening");
25872 
25873   SDLoc dl(InOp);
25874   if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
25875       InOp.getNumOperands() == 2) {
25876     SDValue N1 = InOp.getOperand(1);
25877     if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
25878         N1.isUndef()) {
25879       InOp = InOp.getOperand(0);
25880       InVT = InOp.getSimpleValueType();
25881       InNumElts = InVT.getVectorNumElements();
25882     }
25883   }
25884   if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
25885       ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
25886     SmallVector<SDValue, 16> Ops;
25887     for (unsigned i = 0; i < InNumElts; ++i)
25888       Ops.push_back(InOp.getOperand(i));
25889 
25890     EVT EltVT = InOp.getOperand(0).getValueType();
25891 
25892     SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
25893       DAG.getUNDEF(EltVT);
25894     for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
25895       Ops.push_back(FillVal);
25896     return DAG.getBuildVector(NVT, dl, Ops);
25897   }
25898   SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
25899     DAG.getUNDEF(NVT);
25900   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
25901                      InOp, DAG.getIntPtrConstant(0, dl));
25902 }
25903 
LowerMSCATTER(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)25904 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget &Subtarget,
25905                              SelectionDAG &DAG) {
25906   assert(Subtarget.hasAVX512() &&
25907          "MGATHER/MSCATTER are supported on AVX-512 arch only");
25908 
25909   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
25910   SDValue Src = N->getValue();
25911   MVT VT = Src.getSimpleValueType();
25912   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
25913   SDLoc dl(Op);
25914 
25915   SDValue Scale = N->getScale();
25916   SDValue Index = N->getIndex();
25917   SDValue Mask = N->getMask();
25918   SDValue Chain = N->getChain();
25919   SDValue BasePtr = N->getBasePtr();
25920 
25921   if (VT == MVT::v2f32) {
25922     assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type");
25923     // If the index is v2i64 and we have VLX we can use xmm for data and index.
25924     if (Index.getValueType() == MVT::v2i64 && Subtarget.hasVLX()) {
25925       Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
25926                         DAG.getUNDEF(MVT::v2f32));
25927       SDVTList VTs = DAG.getVTList(MVT::v2i1, MVT::Other);
25928       SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
25929       SDValue NewScatter = DAG.getTargetMemSDNode<X86MaskedScatterSDNode>(
25930           VTs, Ops, dl, N->getMemoryVT(), N->getMemOperand());
25931       DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
25932       return SDValue(NewScatter.getNode(), 1);
25933     }
25934     return SDValue();
25935   }
25936 
25937   if (VT == MVT::v2i32) {
25938     assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type");
25939     Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
25940                       DAG.getUNDEF(MVT::v2i32));
25941     // If the index is v2i64 and we have VLX we can use xmm for data and index.
25942     if (Index.getValueType() == MVT::v2i64 && Subtarget.hasVLX()) {
25943       SDVTList VTs = DAG.getVTList(MVT::v2i1, MVT::Other);
25944       SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
25945       SDValue NewScatter = DAG.getTargetMemSDNode<X86MaskedScatterSDNode>(
25946           VTs, Ops, dl, N->getMemoryVT(), N->getMemOperand());
25947       DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
25948       return SDValue(NewScatter.getNode(), 1);
25949     }
25950     // Custom widen all the operands to avoid promotion.
25951     EVT NewIndexVT = EVT::getVectorVT(
25952         *DAG.getContext(), Index.getValueType().getVectorElementType(), 4);
25953     Index = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewIndexVT, Index,
25954                         DAG.getUNDEF(Index.getValueType()));
25955     Mask = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i1, Mask,
25956                        DAG.getConstant(0, dl, MVT::v2i1));
25957     SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
25958     return DAG.getMaskedScatter(DAG.getVTList(MVT::Other), N->getMemoryVT(), dl,
25959                                 Ops, N->getMemOperand());
25960   }
25961 
25962   MVT IndexVT = Index.getSimpleValueType();
25963   MVT MaskVT = Mask.getSimpleValueType();
25964 
25965   // If the index is v2i32, we're being called by type legalization and we
25966   // should just let the default handling take care of it.
25967   if (IndexVT == MVT::v2i32)
25968     return SDValue();
25969 
25970   // If we don't have VLX and neither the passthru or index is 512-bits, we
25971   // need to widen until one is.
25972   if (!Subtarget.hasVLX() && !VT.is512BitVector() &&
25973       !Index.getSimpleValueType().is512BitVector()) {
25974     // Determine how much we need to widen by to get a 512-bit type.
25975     unsigned Factor = std::min(512/VT.getSizeInBits(),
25976                                512/IndexVT.getSizeInBits());
25977     unsigned NumElts = VT.getVectorNumElements() * Factor;
25978 
25979     VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
25980     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
25981     MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
25982 
25983     Src = ExtendToType(Src, VT, DAG);
25984     Index = ExtendToType(Index, IndexVT, DAG);
25985     Mask = ExtendToType(Mask, MaskVT, DAG, true);
25986   }
25987 
25988   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
25989   SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
25990   SDValue NewScatter = DAG.getTargetMemSDNode<X86MaskedScatterSDNode>(
25991       VTs, Ops, dl, N->getMemoryVT(), N->getMemOperand());
25992   DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
25993   return SDValue(NewScatter.getNode(), 1);
25994 }
25995 
LowerMLOAD(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)25996 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget &Subtarget,
25997                           SelectionDAG &DAG) {
25998 
25999   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
26000   MVT VT = Op.getSimpleValueType();
26001   MVT ScalarVT = VT.getScalarType();
26002   SDValue Mask = N->getMask();
26003   SDLoc dl(Op);
26004 
26005   assert((!N->isExpandingLoad() || Subtarget.hasAVX512()) &&
26006          "Expanding masked load is supported on AVX-512 target only!");
26007 
26008   assert((!N->isExpandingLoad() || ScalarVT.getSizeInBits() >= 32) &&
26009          "Expanding masked load is supported for 32 and 64-bit types only!");
26010 
26011   assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
26012          "Cannot lower masked load op.");
26013 
26014   assert((ScalarVT.getSizeInBits() >= 32 ||
26015           (Subtarget.hasBWI() &&
26016               (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&
26017          "Unsupported masked load op.");
26018 
26019   // This operation is legal for targets with VLX, but without
26020   // VLX the vector should be widened to 512 bit
26021   unsigned NumEltsInWideVec = 512 / VT.getScalarSizeInBits();
26022   MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
26023   SDValue PassThru = ExtendToType(N->getPassThru(), WideDataVT, DAG);
26024 
26025   // Mask element has to be i1.
26026   assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
26027          "Unexpected mask type");
26028 
26029   MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
26030 
26031   Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
26032   SDValue NewLoad = DAG.getMaskedLoad(WideDataVT, dl, N->getChain(),
26033                                       N->getBasePtr(), Mask, PassThru,
26034                                       N->getMemoryVT(), N->getMemOperand(),
26035                                       N->getExtensionType(),
26036                                       N->isExpandingLoad());
26037 
26038   SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
26039                                NewLoad.getValue(0),
26040                                DAG.getIntPtrConstant(0, dl));
26041   SDValue RetOps[] = {Exract, NewLoad.getValue(1)};
26042   return DAG.getMergeValues(RetOps, dl);
26043 }
26044 
LowerMSTORE(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)26045 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget &Subtarget,
26046                            SelectionDAG &DAG) {
26047   MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
26048   SDValue DataToStore = N->getValue();
26049   MVT VT = DataToStore.getSimpleValueType();
26050   MVT ScalarVT = VT.getScalarType();
26051   SDValue Mask = N->getMask();
26052   SDLoc dl(Op);
26053 
26054   assert((!N->isCompressingStore() || Subtarget.hasAVX512()) &&
26055          "Expanding masked load is supported on AVX-512 target only!");
26056 
26057   assert((!N->isCompressingStore() || ScalarVT.getSizeInBits() >= 32) &&
26058          "Expanding masked load is supported for 32 and 64-bit types only!");
26059 
26060   assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
26061          "Cannot lower masked store op.");
26062 
26063   assert((ScalarVT.getSizeInBits() >= 32 ||
26064           (Subtarget.hasBWI() &&
26065               (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&
26066           "Unsupported masked store op.");
26067 
26068   // This operation is legal for targets with VLX, but without
26069   // VLX the vector should be widened to 512 bit
26070   unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
26071   MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
26072 
26073   // Mask element has to be i1.
26074   assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
26075          "Unexpected mask type");
26076 
26077   MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
26078 
26079   DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
26080   Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
26081   return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
26082                             Mask, N->getMemoryVT(), N->getMemOperand(),
26083                             N->isTruncatingStore(), N->isCompressingStore());
26084 }
26085 
LowerMGATHER(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)26086 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget &Subtarget,
26087                             SelectionDAG &DAG) {
26088   assert(Subtarget.hasAVX2() &&
26089          "MGATHER/MSCATTER are supported on AVX-512/AVX-2 arch only");
26090 
26091   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
26092   SDLoc dl(Op);
26093   MVT VT = Op.getSimpleValueType();
26094   SDValue Index = N->getIndex();
26095   SDValue Mask = N->getMask();
26096   SDValue PassThru = N->getPassThru();
26097   MVT IndexVT = Index.getSimpleValueType();
26098   MVT MaskVT = Mask.getSimpleValueType();
26099 
26100   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
26101 
26102   // If the index is v2i32, we're being called by type legalization.
26103   if (IndexVT == MVT::v2i32)
26104     return SDValue();
26105 
26106   // If we don't have VLX and neither the passthru or index is 512-bits, we
26107   // need to widen until one is.
26108   MVT OrigVT = VT;
26109   if (Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
26110       !IndexVT.is512BitVector()) {
26111     // Determine how much we need to widen by to get a 512-bit type.
26112     unsigned Factor = std::min(512/VT.getSizeInBits(),
26113                                512/IndexVT.getSizeInBits());
26114 
26115     unsigned NumElts = VT.getVectorNumElements() * Factor;
26116 
26117     VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
26118     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
26119     MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
26120 
26121     PassThru = ExtendToType(PassThru, VT, DAG);
26122     Index = ExtendToType(Index, IndexVT, DAG);
26123     Mask = ExtendToType(Mask, MaskVT, DAG, true);
26124   }
26125 
26126   SDValue Ops[] = { N->getChain(), PassThru, Mask, N->getBasePtr(), Index,
26127                     N->getScale() };
26128   SDValue NewGather = DAG.getTargetMemSDNode<X86MaskedGatherSDNode>(
26129       DAG.getVTList(VT, MaskVT, MVT::Other), Ops, dl, N->getMemoryVT(),
26130       N->getMemOperand());
26131   SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OrigVT,
26132                                 NewGather, DAG.getIntPtrConstant(0, dl));
26133   return DAG.getMergeValues({Extract, NewGather.getValue(2)}, dl);
26134 }
26135 
LowerGC_TRANSITION_START(SDValue Op,SelectionDAG & DAG) const26136 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
26137                                                     SelectionDAG &DAG) const {
26138   // TODO: Eventually, the lowering of these nodes should be informed by or
26139   // deferred to the GC strategy for the function in which they appear. For
26140   // now, however, they must be lowered to something. Since they are logically
26141   // no-ops in the case of a null GC strategy (or a GC strategy which does not
26142   // require special handling for these nodes), lower them as literal NOOPs for
26143   // the time being.
26144   SmallVector<SDValue, 2> Ops;
26145 
26146   Ops.push_back(Op.getOperand(0));
26147   if (Op->getGluedNode())
26148     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
26149 
26150   SDLoc OpDL(Op);
26151   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
26152   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
26153 
26154   return NOOP;
26155 }
26156 
LowerGC_TRANSITION_END(SDValue Op,SelectionDAG & DAG) const26157 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
26158                                                   SelectionDAG &DAG) const {
26159   // TODO: Eventually, the lowering of these nodes should be informed by or
26160   // deferred to the GC strategy for the function in which they appear. For
26161   // now, however, they must be lowered to something. Since they are logically
26162   // no-ops in the case of a null GC strategy (or a GC strategy which does not
26163   // require special handling for these nodes), lower them as literal NOOPs for
26164   // the time being.
26165   SmallVector<SDValue, 2> Ops;
26166 
26167   Ops.push_back(Op.getOperand(0));
26168   if (Op->getGluedNode())
26169     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
26170 
26171   SDLoc OpDL(Op);
26172   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
26173   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
26174 
26175   return NOOP;
26176 }
26177 
26178 /// Provide custom lowering hooks for some operations.
LowerOperation(SDValue Op,SelectionDAG & DAG) const26179 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
26180   switch (Op.getOpcode()) {
26181   default: llvm_unreachable("Should not custom lower this!");
26182   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
26183   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
26184     return LowerCMP_SWAP(Op, Subtarget, DAG);
26185   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
26186   case ISD::ATOMIC_LOAD_ADD:
26187   case ISD::ATOMIC_LOAD_SUB:
26188   case ISD::ATOMIC_LOAD_OR:
26189   case ISD::ATOMIC_LOAD_XOR:
26190   case ISD::ATOMIC_LOAD_AND:    return lowerAtomicArith(Op, DAG, Subtarget);
26191   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op, DAG);
26192   case ISD::BITREVERSE:         return LowerBITREVERSE(Op, Subtarget, DAG);
26193   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
26194   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
26195   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
26196   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
26197   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
26198   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
26199   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
26200   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
26201   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, Subtarget,DAG);
26202   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
26203   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
26204   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
26205   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
26206   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
26207   case ISD::SHL_PARTS:
26208   case ISD::SRA_PARTS:
26209   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
26210   case ISD::FSHL:
26211   case ISD::FSHR:               return LowerFunnelShift(Op, Subtarget, DAG);
26212   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
26213   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
26214   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
26215   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
26216   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
26217   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
26218   case ISD::ZERO_EXTEND_VECTOR_INREG:
26219   case ISD::SIGN_EXTEND_VECTOR_INREG:
26220     return LowerEXTEND_VECTOR_INREG(Op, Subtarget, DAG);
26221   case ISD::FP_TO_SINT:
26222   case ISD::FP_TO_UINT:         return LowerFP_TO_INT(Op, DAG);
26223   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
26224   case ISD::LOAD:               return LowerLoad(Op, Subtarget, DAG);
26225   case ISD::STORE:              return LowerStore(Op, Subtarget, DAG);
26226   case ISD::FADD:
26227   case ISD::FSUB:               return lowerFaddFsub(Op, DAG, Subtarget);
26228   case ISD::FABS:
26229   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
26230   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
26231   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
26232   case ISD::SETCC:              return LowerSETCC(Op, DAG);
26233   case ISD::SETCCCARRY:         return LowerSETCCCARRY(Op, DAG);
26234   case ISD::SELECT:             return LowerSELECT(Op, DAG);
26235   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
26236   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
26237   case ISD::VASTART:            return LowerVASTART(Op, DAG);
26238   case ISD::VAARG:              return LowerVAARG(Op, DAG);
26239   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
26240   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
26241   case ISD::INTRINSIC_VOID:
26242   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
26243   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
26244   case ISD::ADDROFRETURNADDR:   return LowerADDROFRETURNADDR(Op, DAG);
26245   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
26246   case ISD::FRAME_TO_ARGS_OFFSET:
26247                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
26248   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
26249   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
26250   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
26251   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
26252   case ISD::EH_SJLJ_SETUP_DISPATCH:
26253     return lowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
26254   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
26255   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
26256   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
26257   case ISD::CTLZ:
26258   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ(Op, Subtarget, DAG);
26259   case ISD::CTTZ:
26260   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, Subtarget, DAG);
26261   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
26262   case ISD::MULHS:
26263   case ISD::MULHU:              return LowerMULH(Op, Subtarget, DAG);
26264   case ISD::ROTL:
26265   case ISD::ROTR:               return LowerRotate(Op, Subtarget, DAG);
26266   case ISD::SRA:
26267   case ISD::SRL:
26268   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
26269   case ISD::SADDO:
26270   case ISD::UADDO:
26271   case ISD::SSUBO:
26272   case ISD::USUBO:
26273   case ISD::SMULO:
26274   case ISD::UMULO:              return LowerXALUO(Op, DAG);
26275   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
26276   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
26277   case ISD::ADDCARRY:
26278   case ISD::SUBCARRY:           return LowerADDSUBCARRY(Op, DAG);
26279   case ISD::ADD:
26280   case ISD::SUB:                return lowerAddSub(Op, DAG, Subtarget);
26281   case ISD::UADDSAT:
26282   case ISD::SADDSAT:
26283   case ISD::USUBSAT:
26284   case ISD::SSUBSAT:            return LowerADDSAT_SUBSAT(Op, DAG);
26285   case ISD::SMAX:
26286   case ISD::SMIN:
26287   case ISD::UMAX:
26288   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
26289   case ISD::ABS:                return LowerABS(Op, Subtarget, DAG);
26290   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
26291   case ISD::MLOAD:              return LowerMLOAD(Op, Subtarget, DAG);
26292   case ISD::MSTORE:             return LowerMSTORE(Op, Subtarget, DAG);
26293   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
26294   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
26295   case ISD::GC_TRANSITION_START:
26296                                 return LowerGC_TRANSITION_START(Op, DAG);
26297   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
26298   }
26299 }
26300 
26301 /// Places new result values for the node in Results (their number
26302 /// and types must exactly match those of the original return values of
26303 /// the node), or leaves Results empty, which indicates that the node is not
26304 /// to be custom lowered after all.
LowerOperationWrapper(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const26305 void X86TargetLowering::LowerOperationWrapper(SDNode *N,
26306                                               SmallVectorImpl<SDValue> &Results,
26307                                               SelectionDAG &DAG) const {
26308   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
26309 
26310   if (!Res.getNode())
26311     return;
26312 
26313   assert((N->getNumValues() <= Res->getNumValues()) &&
26314       "Lowering returned the wrong number of results!");
26315 
26316   // Places new result values base on N result number.
26317   // In some cases (LowerSINT_TO_FP for example) Res has more result values
26318   // than original node, chain should be dropped(last value).
26319   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
26320     Results.push_back(Res.getValue(I));
26321 }
26322 
26323 /// Replace a node with an illegal result type with a new node built out of
26324 /// custom code.
ReplaceNodeResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const26325 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
26326                                            SmallVectorImpl<SDValue>&Results,
26327                                            SelectionDAG &DAG) const {
26328   SDLoc dl(N);
26329   switch (N->getOpcode()) {
26330   default:
26331     llvm_unreachable("Do not know how to custom type legalize this operation!");
26332   case ISD::MUL: {
26333     EVT VT = N->getValueType(0);
26334     assert(VT.isVector() && "Unexpected VT");
26335     if (getTypeAction(*DAG.getContext(), VT) == TypePromoteInteger &&
26336         VT.getVectorNumElements() == 2) {
26337       // Promote to a pattern that will be turned into PMULUDQ.
26338       SDValue N0 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::v2i64,
26339                                N->getOperand(0));
26340       SDValue N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::v2i64,
26341                                N->getOperand(1));
26342       SDValue Mul = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, N0, N1);
26343       Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, VT, Mul));
26344     } else if (getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
26345                VT.getVectorElementType() == MVT::i8) {
26346       // Pre-promote these to vXi16 to avoid op legalization thinking all 16
26347       // elements are needed.
26348       MVT MulVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
26349       SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(0));
26350       SDValue Op1 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(1));
26351       SDValue Res = DAG.getNode(ISD::MUL, dl, MulVT, Op0, Op1);
26352       Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
26353       unsigned NumConcats = 16 / VT.getVectorNumElements();
26354       SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
26355       ConcatOps[0] = Res;
26356       Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i8, ConcatOps);
26357       Results.push_back(Res);
26358     }
26359     return;
26360   }
26361   case ISD::UADDSAT:
26362   case ISD::SADDSAT:
26363   case ISD::USUBSAT:
26364   case ISD::SSUBSAT:
26365   case X86ISD::VPMADDWD:
26366   case X86ISD::AVG: {
26367     // Legalize types for ISD::UADDSAT/SADDSAT/USUBSAT/SSUBSAT and
26368     // X86ISD::AVG/VPMADDWD by widening.
26369     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
26370 
26371     EVT VT = N->getValueType(0);
26372     EVT InVT = N->getOperand(0).getValueType();
26373     assert(VT.getSizeInBits() < 128 && 128 % VT.getSizeInBits() == 0 &&
26374            "Expected a VT that divides into 128 bits.");
26375     unsigned NumConcat = 128 / InVT.getSizeInBits();
26376 
26377     EVT InWideVT = EVT::getVectorVT(*DAG.getContext(),
26378                                     InVT.getVectorElementType(),
26379                                     NumConcat * InVT.getVectorNumElements());
26380     EVT WideVT = EVT::getVectorVT(*DAG.getContext(),
26381                                   VT.getVectorElementType(),
26382                                   NumConcat * VT.getVectorNumElements());
26383 
26384     SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
26385     Ops[0] = N->getOperand(0);
26386     SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
26387     Ops[0] = N->getOperand(1);
26388     SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
26389 
26390     SDValue Res = DAG.getNode(N->getOpcode(), dl, WideVT, InVec0, InVec1);
26391     if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
26392       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
26393                         DAG.getIntPtrConstant(0, dl));
26394     Results.push_back(Res);
26395     return;
26396   }
26397   case ISD::SETCC: {
26398     // Widen v2i32 (setcc v2f32). This is really needed for AVX512VL when
26399     // setCC result type is v2i1 because type legalzation will end up with
26400     // a v4i1 setcc plus an extend.
26401     assert(N->getValueType(0) == MVT::v2i32 && "Unexpected type");
26402     if (N->getOperand(0).getValueType() != MVT::v2f32 ||
26403         getTypeAction(*DAG.getContext(), MVT::v2i32) == TypeWidenVector)
26404       return;
26405     SDValue UNDEF = DAG.getUNDEF(MVT::v2f32);
26406     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
26407                               N->getOperand(0), UNDEF);
26408     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
26409                               N->getOperand(1), UNDEF);
26410     SDValue Res = DAG.getNode(ISD::SETCC, dl, MVT::v4i32, LHS, RHS,
26411                               N->getOperand(2));
26412     Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i32, Res,
26413                       DAG.getIntPtrConstant(0, dl));
26414     Results.push_back(Res);
26415     return;
26416   }
26417   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
26418   case X86ISD::FMINC:
26419   case X86ISD::FMIN:
26420   case X86ISD::FMAXC:
26421   case X86ISD::FMAX: {
26422     EVT VT = N->getValueType(0);
26423     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
26424     SDValue UNDEF = DAG.getUNDEF(VT);
26425     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
26426                               N->getOperand(0), UNDEF);
26427     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
26428                               N->getOperand(1), UNDEF);
26429     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
26430     return;
26431   }
26432   case ISD::SDIV:
26433   case ISD::UDIV:
26434   case ISD::SREM:
26435   case ISD::UREM: {
26436     EVT VT = N->getValueType(0);
26437     if (getTypeAction(*DAG.getContext(), VT) == TypeWidenVector) {
26438       // If this RHS is a constant splat vector we can widen this and let
26439       // division/remainder by constant optimize it.
26440       // TODO: Can we do something for non-splat?
26441       APInt SplatVal;
26442       if (ISD::isConstantSplatVector(N->getOperand(1).getNode(), SplatVal)) {
26443         unsigned NumConcats = 128 / VT.getSizeInBits();
26444         SmallVector<SDValue, 8> Ops0(NumConcats, DAG.getUNDEF(VT));
26445         Ops0[0] = N->getOperand(0);
26446         EVT ResVT = getTypeToTransformTo(*DAG.getContext(), VT);
26447         SDValue N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Ops0);
26448         SDValue N1 = DAG.getConstant(SplatVal, dl, ResVT);
26449         SDValue Res = DAG.getNode(N->getOpcode(), dl, ResVT, N0, N1);
26450         Results.push_back(Res);
26451       }
26452       return;
26453     }
26454 
26455     if (VT == MVT::v2i32) {
26456       // Legalize v2i32 div/rem by unrolling. Otherwise we promote to the
26457       // v2i64 and unroll later. But then we create i64 scalar ops which
26458       // might be slow in 64-bit mode or require a libcall in 32-bit mode.
26459       Results.push_back(DAG.UnrollVectorOp(N));
26460       return;
26461     }
26462 
26463     if (VT.isVector())
26464       return;
26465 
26466     LLVM_FALLTHROUGH;
26467   }
26468   case ISD::SDIVREM:
26469   case ISD::UDIVREM: {
26470     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
26471     Results.push_back(V);
26472     return;
26473   }
26474   case ISD::TRUNCATE: {
26475     MVT VT = N->getSimpleValueType(0);
26476     if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
26477       return;
26478 
26479     // The generic legalizer will try to widen the input type to the same
26480     // number of elements as the widened result type. But this isn't always
26481     // the best thing so do some custom legalization to avoid some cases.
26482     MVT WidenVT = getTypeToTransformTo(*DAG.getContext(), VT).getSimpleVT();
26483     SDValue In = N->getOperand(0);
26484     EVT InVT = In.getValueType();
26485 
26486     unsigned InBits = InVT.getSizeInBits();
26487     if (128 % InBits == 0) {
26488       // 128 bit and smaller inputs should avoid truncate all together and
26489       // just use a build_vector that will become a shuffle.
26490       // TODO: Widen and use a shuffle directly?
26491       MVT InEltVT = InVT.getSimpleVT().getVectorElementType();
26492       EVT EltVT = VT.getVectorElementType();
26493       unsigned WidenNumElts = WidenVT.getVectorNumElements();
26494       SmallVector<SDValue, 16> Ops(WidenNumElts, DAG.getUNDEF(EltVT));
26495       // Use the original element count so we don't do more scalar opts than
26496       // necessary.
26497       unsigned MinElts = VT.getVectorNumElements();
26498       for (unsigned i=0; i < MinElts; ++i) {
26499         SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, In,
26500                                   DAG.getIntPtrConstant(i, dl));
26501         Ops[i] = DAG.getNode(ISD::TRUNCATE, dl, EltVT, Val);
26502       }
26503       Results.push_back(DAG.getBuildVector(WidenVT, dl, Ops));
26504       return;
26505     }
26506     // With AVX512 there are some cases that can use a target specific
26507     // truncate node to go from 256/512 to less than 128 with zeros in the
26508     // upper elements of the 128 bit result.
26509     if (Subtarget.hasAVX512() && isTypeLegal(InVT)) {
26510       // We can use VTRUNC directly if for 256 bits with VLX or for any 512.
26511       if ((InBits == 256 && Subtarget.hasVLX()) || InBits == 512) {
26512         Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
26513         return;
26514       }
26515       // There's one case we can widen to 512 bits and use VTRUNC.
26516       if (InVT == MVT::v4i64 && VT == MVT::v4i8 && isTypeLegal(MVT::v8i64)) {
26517         In = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i64, In,
26518                          DAG.getUNDEF(MVT::v4i64));
26519         Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
26520         return;
26521       }
26522     }
26523     return;
26524   }
26525   case ISD::SIGN_EXTEND_VECTOR_INREG: {
26526     if (ExperimentalVectorWideningLegalization)
26527       return;
26528 
26529     EVT VT = N->getValueType(0);
26530     SDValue In = N->getOperand(0);
26531     EVT InVT = In.getValueType();
26532     if (!Subtarget.hasSSE41() && VT == MVT::v4i64 &&
26533         (InVT == MVT::v16i16 || InVT == MVT::v32i8)) {
26534       // Custom split this so we can extend i8/i16->i32 invec. This is better
26535       // since sign_extend_inreg i8/i16->i64 requires an extend to i32 using
26536       // sra. Then extending from i32 to i64 using pcmpgt. By custom splitting
26537       // we allow the sra from the extend to i32 to be shared by the split.
26538       EVT ExtractVT = EVT::getVectorVT(*DAG.getContext(),
26539                                        InVT.getVectorElementType(),
26540                                        InVT.getVectorNumElements() / 2);
26541       MVT ExtendVT = MVT::getVectorVT(MVT::i32,
26542                                       VT.getVectorNumElements());
26543       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ExtractVT,
26544                        In, DAG.getIntPtrConstant(0, dl));
26545       In = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, MVT::v4i32, In);
26546 
26547       // Fill a vector with sign bits for each element.
26548       SDValue Zero = DAG.getConstant(0, dl, ExtendVT);
26549       SDValue SignBits = DAG.getSetCC(dl, ExtendVT, Zero, In, ISD::SETGT);
26550 
26551       EVT LoVT, HiVT;
26552       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
26553 
26554       // Create an unpackl and unpackh to interleave the sign bits then bitcast
26555       // to vXi64.
26556       SDValue Lo = getUnpackl(DAG, dl, ExtendVT, In, SignBits);
26557       Lo = DAG.getNode(ISD::BITCAST, dl, LoVT, Lo);
26558       SDValue Hi = getUnpackh(DAG, dl, ExtendVT, In, SignBits);
26559       Hi = DAG.getNode(ISD::BITCAST, dl, HiVT, Hi);
26560 
26561       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
26562       Results.push_back(Res);
26563       return;
26564     }
26565     return;
26566   }
26567   case ISD::SIGN_EXTEND:
26568   case ISD::ZERO_EXTEND: {
26569     if (!ExperimentalVectorWideningLegalization)
26570       return;
26571 
26572     EVT VT = N->getValueType(0);
26573     SDValue In = N->getOperand(0);
26574     EVT InVT = In.getValueType();
26575     if (!Subtarget.hasSSE41() && VT == MVT::v4i64 &&
26576         (InVT == MVT::v4i16 || InVT == MVT::v4i8)) {
26577       // Custom split this so we can extend i8/i16->i32 invec. This is better
26578       // since sign_extend_inreg i8/i16->i64 requires an extend to i32 using
26579       // sra. Then extending from i32 to i64 using pcmpgt. By custom splitting
26580       // we allow the sra from the extend to i32 to be shared by the split.
26581       In = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, In);
26582 
26583       // Fill a vector with sign bits for each element.
26584       SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
26585       SDValue SignBits = DAG.getSetCC(dl, MVT::v4i32, Zero, In, ISD::SETGT);
26586 
26587       // Create an unpackl and unpackh to interleave the sign bits then bitcast
26588       // to v2i64.
26589       SDValue Lo = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
26590                                         {0, 4, 1, 5});
26591       Lo = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Lo);
26592       SDValue Hi = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
26593                                         {2, 6, 3, 7});
26594       Hi = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Hi);
26595 
26596       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
26597       Results.push_back(Res);
26598       return;
26599     }
26600 
26601     if ((VT == MVT::v16i32 || VT == MVT::v8i64) && InVT.is128BitVector()) {
26602       // Perform custom splitting instead of the two stage extend we would get
26603       // by default.
26604       EVT LoVT, HiVT;
26605       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
26606       assert(isTypeLegal(LoVT) && "Split VT not legal?");
26607 
26608       bool IsSigned = N->getOpcode() == ISD::SIGN_EXTEND;
26609 
26610       SDValue Lo = getExtendInVec(IsSigned, dl, LoVT, In, DAG);
26611 
26612       // We need to shift the input over by half the number of elements.
26613       unsigned NumElts = InVT.getVectorNumElements();
26614       unsigned HalfNumElts = NumElts / 2;
26615       SmallVector<int, 16> ShufMask(NumElts, SM_SentinelUndef);
26616       for (unsigned i = 0; i != HalfNumElts; ++i)
26617         ShufMask[i] = i + HalfNumElts;
26618 
26619       SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
26620       Hi = getExtendInVec(IsSigned, dl, HiVT, Hi, DAG);
26621 
26622       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
26623       Results.push_back(Res);
26624     }
26625     return;
26626   }
26627   case ISD::FP_TO_SINT:
26628   case ISD::FP_TO_UINT: {
26629     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
26630     EVT VT = N->getValueType(0);
26631     SDValue Src = N->getOperand(0);
26632     EVT SrcVT = Src.getValueType();
26633 
26634     // Promote these manually to avoid over promotion to v2i64. Type
26635     // legalization will revisit the v2i32 operation for more cleanup.
26636     if ((VT == MVT::v2i8 || VT == MVT::v2i16) &&
26637         getTypeAction(*DAG.getContext(), VT) == TypePromoteInteger) {
26638       // AVX512DQ provides instructions that produce a v2i64 result.
26639       if (Subtarget.hasDQI())
26640         return;
26641 
26642       SDValue Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v2i32, Src);
26643       Res = DAG.getNode(N->getOpcode() == ISD::FP_TO_UINT ? ISD::AssertZext
26644                                                           : ISD::AssertSext,
26645                         dl, MVT::v2i32, Res,
26646                         DAG.getValueType(VT.getVectorElementType()));
26647       Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
26648       Results.push_back(Res);
26649       return;
26650     }
26651 
26652     if (VT.isVector() && VT.getScalarSizeInBits() < 32) {
26653       if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
26654         return;
26655 
26656       // Try to create a 128 bit vector, but don't exceed a 32 bit element.
26657       unsigned NewEltWidth = std::min(128 / VT.getVectorNumElements(), 32U);
26658       MVT PromoteVT = MVT::getVectorVT(MVT::getIntegerVT(NewEltWidth),
26659                                        VT.getVectorNumElements());
26660       SDValue Res = DAG.getNode(ISD::FP_TO_SINT, dl, PromoteVT, Src);
26661 
26662       // Preserve what we know about the size of the original result. Except
26663       // when the result is v2i32 since we can't widen the assert.
26664       if (PromoteVT != MVT::v2i32)
26665         Res = DAG.getNode(N->getOpcode() == ISD::FP_TO_UINT ? ISD::AssertZext
26666                                                             : ISD::AssertSext,
26667                           dl, PromoteVT, Res,
26668                           DAG.getValueType(VT.getVectorElementType()));
26669 
26670       // Truncate back to the original width.
26671       Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
26672 
26673       // Now widen to 128 bits.
26674       unsigned NumConcats = 128 / VT.getSizeInBits();
26675       MVT ConcatVT = MVT::getVectorVT(VT.getSimpleVT().getVectorElementType(),
26676                                       VT.getVectorNumElements() * NumConcats);
26677       SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
26678       ConcatOps[0] = Res;
26679       Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatVT, ConcatOps);
26680       Results.push_back(Res);
26681       return;
26682     }
26683 
26684 
26685     if (VT == MVT::v2i32) {
26686       assert((IsSigned || Subtarget.hasAVX512()) &&
26687              "Can only handle signed conversion without AVX512");
26688       assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
26689       bool Widenv2i32 =
26690         getTypeAction(*DAG.getContext(), MVT::v2i32) == TypeWidenVector;
26691       if (Src.getValueType() == MVT::v2f64) {
26692         unsigned Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
26693         if (!IsSigned && !Subtarget.hasVLX()) {
26694           // If v2i32 is widened, we can defer to the generic legalizer.
26695           if (Widenv2i32)
26696             return;
26697           // Custom widen by doubling to a legal vector with. Isel will
26698           // further widen to v8f64.
26699           Opc = ISD::FP_TO_UINT;
26700           Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f64,
26701                             Src, DAG.getUNDEF(MVT::v2f64));
26702         }
26703         SDValue Res = DAG.getNode(Opc, dl, MVT::v4i32, Src);
26704         if (!Widenv2i32)
26705           Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i32, Res,
26706                             DAG.getIntPtrConstant(0, dl));
26707         Results.push_back(Res);
26708         return;
26709       }
26710       if (SrcVT == MVT::v2f32 &&
26711           getTypeAction(*DAG.getContext(), VT) != TypeWidenVector) {
26712         SDValue Idx = DAG.getIntPtrConstant(0, dl);
26713         SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
26714                                   DAG.getUNDEF(MVT::v2f32));
26715         Res = DAG.getNode(IsSigned ? ISD::FP_TO_SINT
26716                                    : ISD::FP_TO_UINT, dl, MVT::v4i32, Res);
26717         Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i32, Res, Idx);
26718         Results.push_back(Res);
26719         return;
26720       }
26721 
26722       // The FP_TO_INTHelper below only handles f32/f64/f80 scalar inputs,
26723       // so early out here.
26724       return;
26725     }
26726 
26727     if (Subtarget.hasDQI() && VT == MVT::i64 &&
26728         (SrcVT == MVT::f32 || SrcVT == MVT::f64)) {
26729       assert(!Subtarget.is64Bit() && "i64 should be legal");
26730       unsigned NumElts = Subtarget.hasVLX() ? 4 : 8;
26731       // Using a 256-bit input here to guarantee 128-bit input for f32 case.
26732       // TODO: Use 128-bit vectors for f64 case?
26733       // TODO: Use 128-bit vectors for f32 by using CVTTP2SI/CVTTP2UI.
26734       MVT VecVT = MVT::getVectorVT(MVT::i64, NumElts);
26735       MVT VecInVT = MVT::getVectorVT(SrcVT.getSimpleVT(), NumElts);
26736 
26737       SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
26738       SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecInVT,
26739                                 DAG.getConstantFP(0.0, dl, VecInVT), Src,
26740                                 ZeroIdx);
26741       Res = DAG.getNode(N->getOpcode(), SDLoc(N), VecVT, Res);
26742       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Res, ZeroIdx);
26743       Results.push_back(Res);
26744       return;
26745     }
26746 
26747     std::pair<SDValue,SDValue> Vals =
26748         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
26749     SDValue FIST = Vals.first, StackSlot = Vals.second;
26750     if (FIST.getNode()) {
26751       // Return a load from the stack slot.
26752       if (StackSlot.getNode())
26753         Results.push_back(
26754             DAG.getLoad(VT, dl, FIST, StackSlot, MachinePointerInfo()));
26755       else
26756         Results.push_back(FIST);
26757     }
26758     return;
26759   }
26760   case ISD::SINT_TO_FP: {
26761     assert(Subtarget.hasDQI() && Subtarget.hasVLX() && "Requires AVX512DQVL!");
26762     SDValue Src = N->getOperand(0);
26763     if (N->getValueType(0) != MVT::v2f32 || Src.getValueType() != MVT::v2i64)
26764       return;
26765     Results.push_back(DAG.getNode(X86ISD::CVTSI2P, dl, MVT::v4f32, Src));
26766     return;
26767   }
26768   case ISD::UINT_TO_FP: {
26769     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
26770     EVT VT = N->getValueType(0);
26771     if (VT != MVT::v2f32)
26772       return;
26773     SDValue Src = N->getOperand(0);
26774     EVT SrcVT = Src.getValueType();
26775     if (Subtarget.hasDQI() && Subtarget.hasVLX() && SrcVT == MVT::v2i64) {
26776       Results.push_back(DAG.getNode(X86ISD::CVTUI2P, dl, MVT::v4f32, Src));
26777       return;
26778     }
26779     if (SrcVT != MVT::v2i32)
26780       return;
26781     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64, Src);
26782     SDValue VBias =
26783         DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl, MVT::v2f64);
26784     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
26785                              DAG.getBitcast(MVT::v2i64, VBias));
26786     Or = DAG.getBitcast(MVT::v2f64, Or);
26787     // TODO: Are there any fast-math-flags to propagate here?
26788     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
26789     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
26790     return;
26791   }
26792   case ISD::FP_ROUND: {
26793     if (!isTypeLegal(N->getOperand(0).getValueType()))
26794         return;
26795     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
26796     Results.push_back(V);
26797     return;
26798   }
26799   case ISD::FP_EXTEND: {
26800     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
26801     // No other ValueType for FP_EXTEND should reach this point.
26802     assert(N->getValueType(0) == MVT::v2f32 &&
26803            "Do not know how to legalize this Node");
26804     return;
26805   }
26806   case ISD::INTRINSIC_W_CHAIN: {
26807     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
26808     switch (IntNo) {
26809     default : llvm_unreachable("Do not know how to custom type "
26810                                "legalize this intrinsic operation!");
26811     case Intrinsic::x86_rdtsc:
26812       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
26813                                      Results);
26814     case Intrinsic::x86_rdtscp:
26815       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
26816                                      Results);
26817     case Intrinsic::x86_rdpmc:
26818       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
26819 
26820     case Intrinsic::x86_xgetbv:
26821       return getExtendedControlRegister(N, dl, DAG, Subtarget, Results);
26822     }
26823   }
26824   case ISD::INTRINSIC_WO_CHAIN: {
26825     if (SDValue V = LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), DAG))
26826       Results.push_back(V);
26827     return;
26828   }
26829   case ISD::READCYCLECOUNTER: {
26830     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
26831                                    Results);
26832   }
26833   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
26834     EVT T = N->getValueType(0);
26835     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
26836     bool Regs64bit = T == MVT::i128;
26837     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
26838     SDValue cpInL, cpInH;
26839     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
26840                         DAG.getConstant(0, dl, HalfT));
26841     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
26842                         DAG.getConstant(1, dl, HalfT));
26843     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
26844                              Regs64bit ? X86::RAX : X86::EAX,
26845                              cpInL, SDValue());
26846     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
26847                              Regs64bit ? X86::RDX : X86::EDX,
26848                              cpInH, cpInL.getValue(1));
26849     SDValue swapInL, swapInH;
26850     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
26851                           DAG.getConstant(0, dl, HalfT));
26852     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
26853                           DAG.getConstant(1, dl, HalfT));
26854     swapInH =
26855         DAG.getCopyToReg(cpInH.getValue(0), dl, Regs64bit ? X86::RCX : X86::ECX,
26856                          swapInH, cpInH.getValue(1));
26857     // If the current function needs the base pointer, RBX,
26858     // we shouldn't use cmpxchg directly.
26859     // Indeed the lowering of that instruction will clobber
26860     // that register and since RBX will be a reserved register
26861     // the register allocator will not make sure its value will
26862     // be properly saved and restored around this live-range.
26863     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
26864     SDValue Result;
26865     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
26866     unsigned BasePtr = TRI->getBaseRegister();
26867     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
26868     if (TRI->hasBasePointer(DAG.getMachineFunction()) &&
26869         (BasePtr == X86::RBX || BasePtr == X86::EBX)) {
26870       // ISel prefers the LCMPXCHG64 variant.
26871       // If that assert breaks, that means it is not the case anymore,
26872       // and we need to teach LCMPXCHG8_SAVE_EBX_DAG how to save RBX,
26873       // not just EBX. This is a matter of accepting i64 input for that
26874       // pseudo, and restoring into the register of the right wide
26875       // in expand pseudo. Everything else should just work.
26876       assert(((Regs64bit == (BasePtr == X86::RBX)) || BasePtr == X86::EBX) &&
26877              "Saving only half of the RBX");
26878       unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_SAVE_RBX_DAG
26879                                   : X86ISD::LCMPXCHG8_SAVE_EBX_DAG;
26880       SDValue RBXSave = DAG.getCopyFromReg(swapInH.getValue(0), dl,
26881                                            Regs64bit ? X86::RBX : X86::EBX,
26882                                            HalfT, swapInH.getValue(1));
26883       SDValue Ops[] = {/*Chain*/ RBXSave.getValue(1), N->getOperand(1), swapInL,
26884                        RBXSave,
26885                        /*Glue*/ RBXSave.getValue(2)};
26886       Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
26887     } else {
26888       unsigned Opcode =
26889           Regs64bit ? X86ISD::LCMPXCHG16_DAG : X86ISD::LCMPXCHG8_DAG;
26890       swapInL = DAG.getCopyToReg(swapInH.getValue(0), dl,
26891                                  Regs64bit ? X86::RBX : X86::EBX, swapInL,
26892                                  swapInH.getValue(1));
26893       SDValue Ops[] = {swapInL.getValue(0), N->getOperand(1),
26894                        swapInL.getValue(1)};
26895       Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
26896     }
26897     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
26898                                         Regs64bit ? X86::RAX : X86::EAX,
26899                                         HalfT, Result.getValue(1));
26900     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
26901                                         Regs64bit ? X86::RDX : X86::EDX,
26902                                         HalfT, cpOutL.getValue(2));
26903     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
26904 
26905     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
26906                                         MVT::i32, cpOutH.getValue(2));
26907     SDValue Success = getSETCC(X86::COND_E, EFLAGS, dl, DAG);
26908     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
26909 
26910     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
26911     Results.push_back(Success);
26912     Results.push_back(EFLAGS.getValue(1));
26913     return;
26914   }
26915   case ISD::ATOMIC_SWAP:
26916   case ISD::ATOMIC_LOAD_ADD:
26917   case ISD::ATOMIC_LOAD_SUB:
26918   case ISD::ATOMIC_LOAD_AND:
26919   case ISD::ATOMIC_LOAD_OR:
26920   case ISD::ATOMIC_LOAD_XOR:
26921   case ISD::ATOMIC_LOAD_NAND:
26922   case ISD::ATOMIC_LOAD_MIN:
26923   case ISD::ATOMIC_LOAD_MAX:
26924   case ISD::ATOMIC_LOAD_UMIN:
26925   case ISD::ATOMIC_LOAD_UMAX:
26926   case ISD::ATOMIC_LOAD: {
26927     // Delegate to generic TypeLegalization. Situations we can really handle
26928     // should have already been dealt with by AtomicExpandPass.cpp.
26929     break;
26930   }
26931   case ISD::BITCAST: {
26932     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
26933     EVT DstVT = N->getValueType(0);
26934     EVT SrcVT = N->getOperand(0).getValueType();
26935 
26936     // If this is a bitcast from a v64i1 k-register to a i64 on a 32-bit target
26937     // we can split using the k-register rather than memory.
26938     if (SrcVT == MVT::v64i1 && DstVT == MVT::i64 && Subtarget.hasBWI()) {
26939       assert(!Subtarget.is64Bit() && "Expected 32-bit mode");
26940       SDValue Lo, Hi;
26941       std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
26942       Lo = DAG.getBitcast(MVT::i32, Lo);
26943       Hi = DAG.getBitcast(MVT::i32, Hi);
26944       SDValue Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
26945       Results.push_back(Res);
26946       return;
26947     }
26948 
26949     // Custom splitting for BWI types when AVX512F is available but BWI isn't.
26950     if ((DstVT == MVT::v32i16 || DstVT == MVT::v64i8) &&
26951         SrcVT.isVector() && isTypeLegal(SrcVT)) {
26952       SDValue Lo, Hi;
26953       std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
26954       MVT CastVT = (DstVT == MVT::v32i16) ? MVT::v16i16 : MVT::v32i8;
26955       Lo = DAG.getBitcast(CastVT, Lo);
26956       Hi = DAG.getBitcast(CastVT, Hi);
26957       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, DstVT, Lo, Hi);
26958       Results.push_back(Res);
26959       return;
26960     }
26961 
26962     if (SrcVT != MVT::f64 ||
26963         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8) ||
26964         getTypeAction(*DAG.getContext(), DstVT) == TypeWidenVector)
26965       return;
26966 
26967     unsigned NumElts = DstVT.getVectorNumElements();
26968     EVT SVT = DstVT.getVectorElementType();
26969     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
26970     SDValue Res;
26971     Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, N->getOperand(0));
26972     Res = DAG.getBitcast(WiderVT, Res);
26973     Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, Res,
26974                       DAG.getIntPtrConstant(0, dl));
26975     Results.push_back(Res);
26976     return;
26977   }
26978   case ISD::MGATHER: {
26979     EVT VT = N->getValueType(0);
26980     if (VT == MVT::v2f32 && (Subtarget.hasVLX() || !Subtarget.hasAVX512())) {
26981       auto *Gather = cast<MaskedGatherSDNode>(N);
26982       SDValue Index = Gather->getIndex();
26983       if (Index.getValueType() != MVT::v2i64)
26984         return;
26985       SDValue Mask = Gather->getMask();
26986       assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type");
26987       SDValue PassThru = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
26988                                      Gather->getPassThru(),
26989                                      DAG.getUNDEF(MVT::v2f32));
26990       if (!Subtarget.hasVLX()) {
26991         // We need to widen the mask, but the instruction will only use 2
26992         // of its elements. So we can use undef.
26993         Mask = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i1, Mask,
26994                            DAG.getUNDEF(MVT::v2i1));
26995         Mask = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Mask);
26996       }
26997       SDValue Ops[] = { Gather->getChain(), PassThru, Mask,
26998                         Gather->getBasePtr(), Index, Gather->getScale() };
26999       SDValue Res = DAG.getTargetMemSDNode<X86MaskedGatherSDNode>(
27000         DAG.getVTList(MVT::v4f32, Mask.getValueType(), MVT::Other), Ops, dl,
27001         Gather->getMemoryVT(), Gather->getMemOperand());
27002       Results.push_back(Res);
27003       Results.push_back(Res.getValue(2));
27004       return;
27005     }
27006     if (VT == MVT::v2i32) {
27007       auto *Gather = cast<MaskedGatherSDNode>(N);
27008       SDValue Index = Gather->getIndex();
27009       SDValue Mask = Gather->getMask();
27010       assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type");
27011       SDValue PassThru = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32,
27012                                      Gather->getPassThru(),
27013                                      DAG.getUNDEF(MVT::v2i32));
27014       // If the index is v2i64 we can use it directly.
27015       if (Index.getValueType() == MVT::v2i64 &&
27016           (Subtarget.hasVLX() || !Subtarget.hasAVX512())) {
27017         if (!Subtarget.hasVLX()) {
27018           // We need to widen the mask, but the instruction will only use 2
27019           // of its elements. So we can use undef.
27020           Mask = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i1, Mask,
27021                              DAG.getUNDEF(MVT::v2i1));
27022           Mask = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Mask);
27023         }
27024         SDValue Ops[] = { Gather->getChain(), PassThru, Mask,
27025                           Gather->getBasePtr(), Index, Gather->getScale() };
27026         SDValue Res = DAG.getTargetMemSDNode<X86MaskedGatherSDNode>(
27027           DAG.getVTList(MVT::v4i32, Mask.getValueType(), MVT::Other), Ops, dl,
27028           Gather->getMemoryVT(), Gather->getMemOperand());
27029         SDValue Chain = Res.getValue(2);
27030         if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
27031           Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i32, Res,
27032                             DAG.getIntPtrConstant(0, dl));
27033         Results.push_back(Res);
27034         Results.push_back(Chain);
27035         return;
27036       }
27037       if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector) {
27038         EVT IndexVT = Index.getValueType();
27039         EVT NewIndexVT = EVT::getVectorVT(*DAG.getContext(),
27040                                           IndexVT.getScalarType(), 4);
27041         // Otherwise we need to custom widen everything to avoid promotion.
27042         Index = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewIndexVT, Index,
27043                             DAG.getUNDEF(IndexVT));
27044         Mask = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i1, Mask,
27045                            DAG.getConstant(0, dl, MVT::v2i1));
27046         SDValue Ops[] = { Gather->getChain(), PassThru, Mask,
27047                           Gather->getBasePtr(), Index, Gather->getScale() };
27048         SDValue Res = DAG.getMaskedGather(DAG.getVTList(MVT::v4i32, MVT::Other),
27049                                           Gather->getMemoryVT(), dl, Ops,
27050                                           Gather->getMemOperand());
27051         SDValue Chain = Res.getValue(1);
27052         if (getTypeAction(*DAG.getContext(), MVT::v2i32) != TypeWidenVector)
27053           Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i32, Res,
27054                             DAG.getIntPtrConstant(0, dl));
27055         Results.push_back(Res);
27056         Results.push_back(Chain);
27057         return;
27058       }
27059     }
27060     return;
27061   }
27062   case ISD::LOAD: {
27063     // Use an f64/i64 load and a scalar_to_vector for v2f32/v2i32 loads. This
27064     // avoids scalarizing in 32-bit mode. In 64-bit mode this avoids a int->fp
27065     // cast since type legalization will try to use an i64 load.
27066     MVT VT = N->getSimpleValueType(0);
27067     assert(VT.isVector() && VT.getSizeInBits() == 64 && "Unexpected VT");
27068     if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
27069       return;
27070     if (!ISD::isNON_EXTLoad(N))
27071       return;
27072     auto *Ld = cast<LoadSDNode>(N);
27073     MVT LdVT = Subtarget.is64Bit() && VT.isInteger() ? MVT::i64 : MVT::f64;
27074     SDValue Res = DAG.getLoad(LdVT, dl, Ld->getChain(), Ld->getBasePtr(),
27075                               Ld->getPointerInfo(),
27076                               Ld->getAlignment(),
27077                               Ld->getMemOperand()->getFlags());
27078     SDValue Chain = Res.getValue(1);
27079     MVT WideVT = MVT::getVectorVT(LdVT, 2);
27080     Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, WideVT, Res);
27081     MVT CastVT = MVT::getVectorVT(VT.getVectorElementType(),
27082                                   VT.getVectorNumElements() * 2);
27083     Res = DAG.getBitcast(CastVT, Res);
27084     Results.push_back(Res);
27085     Results.push_back(Chain);
27086     return;
27087   }
27088   }
27089 }
27090 
getTargetNodeName(unsigned Opcode) const27091 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
27092   switch ((X86ISD::NodeType)Opcode) {
27093   case X86ISD::FIRST_NUMBER:       break;
27094   case X86ISD::BSF:                return "X86ISD::BSF";
27095   case X86ISD::BSR:                return "X86ISD::BSR";
27096   case X86ISD::SHLD:               return "X86ISD::SHLD";
27097   case X86ISD::SHRD:               return "X86ISD::SHRD";
27098   case X86ISD::FAND:               return "X86ISD::FAND";
27099   case X86ISD::FANDN:              return "X86ISD::FANDN";
27100   case X86ISD::FOR:                return "X86ISD::FOR";
27101   case X86ISD::FXOR:               return "X86ISD::FXOR";
27102   case X86ISD::FILD:               return "X86ISD::FILD";
27103   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
27104   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
27105   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
27106   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
27107   case X86ISD::FLD:                return "X86ISD::FLD";
27108   case X86ISD::FST:                return "X86ISD::FST";
27109   case X86ISD::CALL:               return "X86ISD::CALL";
27110   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
27111   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
27112   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
27113   case X86ISD::BT:                 return "X86ISD::BT";
27114   case X86ISD::CMP:                return "X86ISD::CMP";
27115   case X86ISD::COMI:               return "X86ISD::COMI";
27116   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
27117   case X86ISD::CMPM:               return "X86ISD::CMPM";
27118   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
27119   case X86ISD::SETCC:              return "X86ISD::SETCC";
27120   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
27121   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
27122   case X86ISD::FSETCCM:            return "X86ISD::FSETCCM";
27123   case X86ISD::FSETCCM_RND:        return "X86ISD::FSETCCM_RND";
27124   case X86ISD::CMOV:               return "X86ISD::CMOV";
27125   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
27126   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
27127   case X86ISD::IRET:               return "X86ISD::IRET";
27128   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
27129   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
27130   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
27131   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
27132   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
27133   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
27134   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
27135   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
27136   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
27137   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
27138   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
27139   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
27140   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
27141   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
27142   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
27143   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
27144   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
27145   case X86ISD::HADD:               return "X86ISD::HADD";
27146   case X86ISD::HSUB:               return "X86ISD::HSUB";
27147   case X86ISD::FHADD:              return "X86ISD::FHADD";
27148   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
27149   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
27150   case X86ISD::FMAX:               return "X86ISD::FMAX";
27151   case X86ISD::FMAXS:              return "X86ISD::FMAXS";
27152   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
27153   case X86ISD::FMAXS_RND:          return "X86ISD::FMAX_RND";
27154   case X86ISD::FMIN:               return "X86ISD::FMIN";
27155   case X86ISD::FMINS:              return "X86ISD::FMINS";
27156   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
27157   case X86ISD::FMINS_RND:          return "X86ISD::FMINS_RND";
27158   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
27159   case X86ISD::FMINC:              return "X86ISD::FMINC";
27160   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
27161   case X86ISD::FRCP:               return "X86ISD::FRCP";
27162   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
27163   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
27164   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
27165   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
27166   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
27167   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
27168   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
27169   case X86ISD::EH_SJLJ_SETUP_DISPATCH:
27170     return "X86ISD::EH_SJLJ_SETUP_DISPATCH";
27171   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
27172   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
27173   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
27174   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
27175   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
27176   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
27177   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
27178   case X86ISD::LCMPXCHG8_SAVE_EBX_DAG:
27179     return "X86ISD::LCMPXCHG8_SAVE_EBX_DAG";
27180   case X86ISD::LCMPXCHG16_SAVE_RBX_DAG:
27181     return "X86ISD::LCMPXCHG16_SAVE_RBX_DAG";
27182   case X86ISD::LADD:               return "X86ISD::LADD";
27183   case X86ISD::LSUB:               return "X86ISD::LSUB";
27184   case X86ISD::LOR:                return "X86ISD::LOR";
27185   case X86ISD::LXOR:               return "X86ISD::LXOR";
27186   case X86ISD::LAND:               return "X86ISD::LAND";
27187   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
27188   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
27189   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
27190   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
27191   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
27192   case X86ISD::VMTRUNC:            return "X86ISD::VMTRUNC";
27193   case X86ISD::VMTRUNCS:           return "X86ISD::VMTRUNCS";
27194   case X86ISD::VMTRUNCUS:          return "X86ISD::VMTRUNCUS";
27195   case X86ISD::VTRUNCSTORES:       return "X86ISD::VTRUNCSTORES";
27196   case X86ISD::VTRUNCSTOREUS:      return "X86ISD::VTRUNCSTOREUS";
27197   case X86ISD::VMTRUNCSTORES:      return "X86ISD::VMTRUNCSTORES";
27198   case X86ISD::VMTRUNCSTOREUS:     return "X86ISD::VMTRUNCSTOREUS";
27199   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
27200   case X86ISD::VFPEXT_RND:         return "X86ISD::VFPEXT_RND";
27201   case X86ISD::VFPEXTS_RND:        return "X86ISD::VFPEXTS_RND";
27202   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
27203   case X86ISD::VMFPROUND:          return "X86ISD::VMFPROUND";
27204   case X86ISD::VFPROUND_RND:       return "X86ISD::VFPROUND_RND";
27205   case X86ISD::VFPROUNDS_RND:      return "X86ISD::VFPROUNDS_RND";
27206   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
27207   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
27208   case X86ISD::VSHL:               return "X86ISD::VSHL";
27209   case X86ISD::VSRL:               return "X86ISD::VSRL";
27210   case X86ISD::VSRA:               return "X86ISD::VSRA";
27211   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
27212   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
27213   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
27214   case X86ISD::VSHLV:              return "X86ISD::VSHLV";
27215   case X86ISD::VSRLV:              return "X86ISD::VSRLV";
27216   case X86ISD::VSRAV:              return "X86ISD::VSRAV";
27217   case X86ISD::VROTLI:             return "X86ISD::VROTLI";
27218   case X86ISD::VROTRI:             return "X86ISD::VROTRI";
27219   case X86ISD::VPPERM:             return "X86ISD::VPPERM";
27220   case X86ISD::CMPP:               return "X86ISD::CMPP";
27221   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
27222   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
27223   case X86ISD::PHMINPOS:           return "X86ISD::PHMINPOS";
27224   case X86ISD::ADD:                return "X86ISD::ADD";
27225   case X86ISD::SUB:                return "X86ISD::SUB";
27226   case X86ISD::ADC:                return "X86ISD::ADC";
27227   case X86ISD::SBB:                return "X86ISD::SBB";
27228   case X86ISD::SMUL:               return "X86ISD::SMUL";
27229   case X86ISD::UMUL:               return "X86ISD::UMUL";
27230   case X86ISD::OR:                 return "X86ISD::OR";
27231   case X86ISD::XOR:                return "X86ISD::XOR";
27232   case X86ISD::AND:                return "X86ISD::AND";
27233   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
27234   case X86ISD::BZHI:               return "X86ISD::BZHI";
27235   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
27236   case X86ISD::MOVMSK:             return "X86ISD::MOVMSK";
27237   case X86ISD::PTEST:              return "X86ISD::PTEST";
27238   case X86ISD::TESTP:              return "X86ISD::TESTP";
27239   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
27240   case X86ISD::KTEST:              return "X86ISD::KTEST";
27241   case X86ISD::KADD:               return "X86ISD::KADD";
27242   case X86ISD::KSHIFTL:            return "X86ISD::KSHIFTL";
27243   case X86ISD::KSHIFTR:            return "X86ISD::KSHIFTR";
27244   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
27245   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
27246   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
27247   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
27248   case X86ISD::VSHLD:              return "X86ISD::VSHLD";
27249   case X86ISD::VSHRD:              return "X86ISD::VSHRD";
27250   case X86ISD::VSHLDV:             return "X86ISD::VSHLDV";
27251   case X86ISD::VSHRDV:             return "X86ISD::VSHRDV";
27252   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
27253   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
27254   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
27255   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
27256   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
27257   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
27258   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
27259   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
27260   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
27261   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
27262   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
27263   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
27264   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
27265   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
27266   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
27267   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
27268   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
27269   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
27270   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
27271   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
27272   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
27273   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
27274   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
27275   case X86ISD::VPTERNLOG:          return "X86ISD::VPTERNLOG";
27276   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
27277   case X86ISD::VFIXUPIMMS:         return "X86ISD::VFIXUPIMMS";
27278   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
27279   case X86ISD::VRANGE_RND:         return "X86ISD::VRANGE_RND";
27280   case X86ISD::VRANGES:            return "X86ISD::VRANGES";
27281   case X86ISD::VRANGES_RND:        return "X86ISD::VRANGES_RND";
27282   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
27283   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
27284   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
27285   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
27286   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
27287   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
27288   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
27289   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
27290   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
27291   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
27292   case X86ISD::SAHF:               return "X86ISD::SAHF";
27293   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
27294   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
27295   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
27296   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
27297   case X86ISD::VPSHA:              return "X86ISD::VPSHA";
27298   case X86ISD::VPSHL:              return "X86ISD::VPSHL";
27299   case X86ISD::VPCOM:              return "X86ISD::VPCOM";
27300   case X86ISD::VPCOMU:             return "X86ISD::VPCOMU";
27301   case X86ISD::VPERMIL2:           return "X86ISD::VPERMIL2";
27302   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
27303   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
27304   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
27305   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
27306   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
27307   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
27308   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
27309   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
27310   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
27311   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
27312   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
27313   case X86ISD::VPMADD52H:          return "X86ISD::VPMADD52H";
27314   case X86ISD::VPMADD52L:          return "X86ISD::VPMADD52L";
27315   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
27316   case X86ISD::VRNDSCALE_RND:      return "X86ISD::VRNDSCALE_RND";
27317   case X86ISD::VRNDSCALES:         return "X86ISD::VRNDSCALES";
27318   case X86ISD::VRNDSCALES_RND:     return "X86ISD::VRNDSCALES_RND";
27319   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
27320   case X86ISD::VREDUCE_RND:        return "X86ISD::VREDUCE_RND";
27321   case X86ISD::VREDUCES:           return "X86ISD::VREDUCES";
27322   case X86ISD::VREDUCES_RND:       return "X86ISD::VREDUCES_RND";
27323   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
27324   case X86ISD::VGETMANT_RND:       return "X86ISD::VGETMANT_RND";
27325   case X86ISD::VGETMANTS:          return "X86ISD::VGETMANTS";
27326   case X86ISD::VGETMANTS_RND:      return "X86ISD::VGETMANTS_RND";
27327   case X86ISD::PCMPESTR:           return "X86ISD::PCMPESTR";
27328   case X86ISD::PCMPISTR:           return "X86ISD::PCMPISTR";
27329   case X86ISD::XTEST:              return "X86ISD::XTEST";
27330   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
27331   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
27332   case X86ISD::SELECTS:            return "X86ISD::SELECTS";
27333   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
27334   case X86ISD::RCP14:              return "X86ISD::RCP14";
27335   case X86ISD::RCP14S:             return "X86ISD::RCP14S";
27336   case X86ISD::RCP28:              return "X86ISD::RCP28";
27337   case X86ISD::RCP28S:             return "X86ISD::RCP28S";
27338   case X86ISD::EXP2:               return "X86ISD::EXP2";
27339   case X86ISD::RSQRT14:            return "X86ISD::RSQRT14";
27340   case X86ISD::RSQRT14S:           return "X86ISD::RSQRT14S";
27341   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
27342   case X86ISD::RSQRT28S:           return "X86ISD::RSQRT28S";
27343   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
27344   case X86ISD::FADDS_RND:          return "X86ISD::FADDS_RND";
27345   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
27346   case X86ISD::FSUBS_RND:          return "X86ISD::FSUBS_RND";
27347   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
27348   case X86ISD::FMULS_RND:          return "X86ISD::FMULS_RND";
27349   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
27350   case X86ISD::FDIVS_RND:          return "X86ISD::FDIVS_RND";
27351   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
27352   case X86ISD::FSQRTS_RND:         return "X86ISD::FSQRTS_RND";
27353   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
27354   case X86ISD::FGETEXPS_RND:       return "X86ISD::FGETEXPS_RND";
27355   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
27356   case X86ISD::SCALEFS:            return "X86ISD::SCALEFS";
27357   case X86ISD::AVG:                return "X86ISD::AVG";
27358   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
27359   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
27360   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
27361   case X86ISD::CVTTP2SI:           return "X86ISD::CVTTP2SI";
27362   case X86ISD::CVTTP2UI:           return "X86ISD::CVTTP2UI";
27363   case X86ISD::MCVTTP2SI:          return "X86ISD::MCVTTP2SI";
27364   case X86ISD::MCVTTP2UI:          return "X86ISD::MCVTTP2UI";
27365   case X86ISD::CVTTP2SI_RND:       return "X86ISD::CVTTP2SI_RND";
27366   case X86ISD::CVTTP2UI_RND:       return "X86ISD::CVTTP2UI_RND";
27367   case X86ISD::CVTTS2SI:           return "X86ISD::CVTTS2SI";
27368   case X86ISD::CVTTS2UI:           return "X86ISD::CVTTS2UI";
27369   case X86ISD::CVTTS2SI_RND:       return "X86ISD::CVTTS2SI_RND";
27370   case X86ISD::CVTTS2UI_RND:       return "X86ISD::CVTTS2UI_RND";
27371   case X86ISD::CVTSI2P:            return "X86ISD::CVTSI2P";
27372   case X86ISD::CVTUI2P:            return "X86ISD::CVTUI2P";
27373   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
27374   case X86ISD::VFPCLASSS:          return "X86ISD::VFPCLASSS";
27375   case X86ISD::MULTISHIFT:         return "X86ISD::MULTISHIFT";
27376   case X86ISD::SCALAR_SINT_TO_FP_RND: return "X86ISD::SCALAR_SINT_TO_FP_RND";
27377   case X86ISD::SCALAR_UINT_TO_FP_RND: return "X86ISD::SCALAR_UINT_TO_FP_RND";
27378   case X86ISD::CVTPS2PH:           return "X86ISD::CVTPS2PH";
27379   case X86ISD::MCVTPS2PH:          return "X86ISD::MCVTPS2PH";
27380   case X86ISD::CVTPH2PS:           return "X86ISD::CVTPH2PS";
27381   case X86ISD::CVTPH2PS_RND:       return "X86ISD::CVTPH2PS_RND";
27382   case X86ISD::CVTP2SI:            return "X86ISD::CVTP2SI";
27383   case X86ISD::CVTP2UI:            return "X86ISD::CVTP2UI";
27384   case X86ISD::MCVTP2SI:           return "X86ISD::MCVTP2SI";
27385   case X86ISD::MCVTP2UI:           return "X86ISD::MCVTP2UI";
27386   case X86ISD::CVTP2SI_RND:        return "X86ISD::CVTP2SI_RND";
27387   case X86ISD::CVTP2UI_RND:        return "X86ISD::CVTP2UI_RND";
27388   case X86ISD::CVTS2SI:            return "X86ISD::CVTS2SI";
27389   case X86ISD::CVTS2UI:            return "X86ISD::CVTS2UI";
27390   case X86ISD::CVTS2SI_RND:        return "X86ISD::CVTS2SI_RND";
27391   case X86ISD::CVTS2UI_RND:        return "X86ISD::CVTS2UI_RND";
27392   case X86ISD::LWPINS:             return "X86ISD::LWPINS";
27393   case X86ISD::MGATHER:            return "X86ISD::MGATHER";
27394   case X86ISD::MSCATTER:           return "X86ISD::MSCATTER";
27395   case X86ISD::VPDPBUSD:           return "X86ISD::VPDPBUSD";
27396   case X86ISD::VPDPBUSDS:          return "X86ISD::VPDPBUSDS";
27397   case X86ISD::VPDPWSSD:           return "X86ISD::VPDPWSSD";
27398   case X86ISD::VPDPWSSDS:          return "X86ISD::VPDPWSSDS";
27399   case X86ISD::VPSHUFBITQMB:       return "X86ISD::VPSHUFBITQMB";
27400   case X86ISD::GF2P8MULB:          return "X86ISD::GF2P8MULB";
27401   case X86ISD::GF2P8AFFINEQB:      return "X86ISD::GF2P8AFFINEQB";
27402   case X86ISD::GF2P8AFFINEINVQB:   return "X86ISD::GF2P8AFFINEINVQB";
27403   case X86ISD::NT_CALL:            return "X86ISD::NT_CALL";
27404   case X86ISD::NT_BRIND:           return "X86ISD::NT_BRIND";
27405   case X86ISD::UMWAIT:             return "X86ISD::UMWAIT";
27406   case X86ISD::TPAUSE:             return "X86ISD::TPAUSE";
27407   }
27408   return nullptr;
27409 }
27410 
27411 /// Return true if the addressing mode represented by AM is legal for this
27412 /// target, for a load/store of the specified type.
isLegalAddressingMode(const DataLayout & DL,const AddrMode & AM,Type * Ty,unsigned AS,Instruction * I) const27413 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
27414                                               const AddrMode &AM, Type *Ty,
27415                                               unsigned AS,
27416                                               Instruction *I) const {
27417   // X86 supports extremely general addressing modes.
27418   CodeModel::Model M = getTargetMachine().getCodeModel();
27419 
27420   // X86 allows a sign-extended 32-bit immediate field as a displacement.
27421   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
27422     return false;
27423 
27424   if (AM.BaseGV) {
27425     unsigned GVFlags = Subtarget.classifyGlobalReference(AM.BaseGV);
27426 
27427     // If a reference to this global requires an extra load, we can't fold it.
27428     if (isGlobalStubReference(GVFlags))
27429       return false;
27430 
27431     // If BaseGV requires a register for the PIC base, we cannot also have a
27432     // BaseReg specified.
27433     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
27434       return false;
27435 
27436     // If lower 4G is not available, then we must use rip-relative addressing.
27437     if ((M != CodeModel::Small || isPositionIndependent()) &&
27438         Subtarget.is64Bit() && (AM.BaseOffs || AM.Scale > 1))
27439       return false;
27440   }
27441 
27442   switch (AM.Scale) {
27443   case 0:
27444   case 1:
27445   case 2:
27446   case 4:
27447   case 8:
27448     // These scales always work.
27449     break;
27450   case 3:
27451   case 5:
27452   case 9:
27453     // These scales are formed with basereg+scalereg.  Only accept if there is
27454     // no basereg yet.
27455     if (AM.HasBaseReg)
27456       return false;
27457     break;
27458   default:  // Other stuff never works.
27459     return false;
27460   }
27461 
27462   return true;
27463 }
27464 
isVectorShiftByScalarCheap(Type * Ty) const27465 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
27466   unsigned Bits = Ty->getScalarSizeInBits();
27467 
27468   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
27469   // particularly cheaper than those without.
27470   if (Bits == 8)
27471     return false;
27472 
27473   // XOP has v16i8/v8i16/v4i32/v2i64 variable vector shifts.
27474   if (Subtarget.hasXOP() && Ty->getPrimitiveSizeInBits() == 128 &&
27475       (Bits == 8 || Bits == 16 || Bits == 32 || Bits == 64))
27476     return false;
27477 
27478   // AVX2 has vpsllv[dq] instructions (and other shifts) that make variable
27479   // shifts just as cheap as scalar ones.
27480   if (Subtarget.hasAVX2() && (Bits == 32 || Bits == 64))
27481     return false;
27482 
27483   // AVX512BW has shifts such as vpsllvw.
27484   if (Subtarget.hasBWI() && Bits == 16)
27485       return false;
27486 
27487   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
27488   // fully general vector.
27489   return true;
27490 }
27491 
isTruncateFree(Type * Ty1,Type * Ty2) const27492 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
27493   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
27494     return false;
27495   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
27496   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
27497   return NumBits1 > NumBits2;
27498 }
27499 
allowTruncateForTailCall(Type * Ty1,Type * Ty2) const27500 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
27501   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
27502     return false;
27503 
27504   if (!isTypeLegal(EVT::getEVT(Ty1)))
27505     return false;
27506 
27507   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
27508 
27509   // Assuming the caller doesn't have a zeroext or signext return parameter,
27510   // truncation all the way down to i1 is valid.
27511   return true;
27512 }
27513 
isLegalICmpImmediate(int64_t Imm) const27514 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
27515   return isInt<32>(Imm);
27516 }
27517 
isLegalAddImmediate(int64_t Imm) const27518 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
27519   // Can also use sub to handle negated immediates.
27520   return isInt<32>(Imm);
27521 }
27522 
isLegalStoreImmediate(int64_t Imm) const27523 bool X86TargetLowering::isLegalStoreImmediate(int64_t Imm) const {
27524   return isInt<32>(Imm);
27525 }
27526 
isTruncateFree(EVT VT1,EVT VT2) const27527 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
27528   if (!VT1.isInteger() || !VT2.isInteger())
27529     return false;
27530   unsigned NumBits1 = VT1.getSizeInBits();
27531   unsigned NumBits2 = VT2.getSizeInBits();
27532   return NumBits1 > NumBits2;
27533 }
27534 
isZExtFree(Type * Ty1,Type * Ty2) const27535 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
27536   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
27537   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget.is64Bit();
27538 }
27539 
isZExtFree(EVT VT1,EVT VT2) const27540 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
27541   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
27542   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget.is64Bit();
27543 }
27544 
isZExtFree(SDValue Val,EVT VT2) const27545 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
27546   EVT VT1 = Val.getValueType();
27547   if (isZExtFree(VT1, VT2))
27548     return true;
27549 
27550   if (Val.getOpcode() != ISD::LOAD)
27551     return false;
27552 
27553   if (!VT1.isSimple() || !VT1.isInteger() ||
27554       !VT2.isSimple() || !VT2.isInteger())
27555     return false;
27556 
27557   switch (VT1.getSimpleVT().SimpleTy) {
27558   default: break;
27559   case MVT::i8:
27560   case MVT::i16:
27561   case MVT::i32:
27562     // X86 has 8, 16, and 32-bit zero-extending loads.
27563     return true;
27564   }
27565 
27566   return false;
27567 }
27568 
isVectorLoadExtDesirable(SDValue ExtVal) const27569 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
27570   EVT SrcVT = ExtVal.getOperand(0).getValueType();
27571 
27572   // There is no extending load for vXi1.
27573   if (SrcVT.getScalarType() == MVT::i1)
27574     return false;
27575 
27576   return true;
27577 }
27578 
27579 bool
isFMAFasterThanFMulAndFAdd(EVT VT) const27580 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
27581   if (!Subtarget.hasAnyFMA())
27582     return false;
27583 
27584   VT = VT.getScalarType();
27585 
27586   if (!VT.isSimple())
27587     return false;
27588 
27589   switch (VT.getSimpleVT().SimpleTy) {
27590   case MVT::f32:
27591   case MVT::f64:
27592     return true;
27593   default:
27594     break;
27595   }
27596 
27597   return false;
27598 }
27599 
isNarrowingProfitable(EVT VT1,EVT VT2) const27600 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
27601   // i16 instructions are longer (0x66 prefix) and potentially slower.
27602   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
27603 }
27604 
27605 /// Targets can use this to indicate that they only support *some*
27606 /// VECTOR_SHUFFLE operations, those with specific masks.
27607 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
27608 /// are assumed to be legal.
isShuffleMaskLegal(ArrayRef<int> M,EVT VT) const27609 bool X86TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
27610   if (!VT.isSimple())
27611     return false;
27612 
27613   // Not for i1 vectors
27614   if (VT.getSimpleVT().getScalarType() == MVT::i1)
27615     return false;
27616 
27617   // Very little shuffling can be done for 64-bit vectors right now.
27618   if (VT.getSimpleVT().getSizeInBits() == 64)
27619     return false;
27620 
27621   // We only care that the types being shuffled are legal. The lowering can
27622   // handle any possible shuffle mask that results.
27623   return isTypeLegal(VT.getSimpleVT());
27624 }
27625 
isVectorClearMaskLegal(ArrayRef<int> Mask,EVT VT) const27626 bool X86TargetLowering::isVectorClearMaskLegal(ArrayRef<int> Mask,
27627                                                EVT VT) const {
27628   // Don't convert an 'and' into a shuffle that we don't directly support.
27629   // vpblendw and vpshufb for 256-bit vectors are not available on AVX1.
27630   if (!Subtarget.hasAVX2())
27631     if (VT == MVT::v32i8 || VT == MVT::v16i16)
27632       return false;
27633 
27634   // Just delegate to the generic legality, clear masks aren't special.
27635   return isShuffleMaskLegal(Mask, VT);
27636 }
27637 
areJTsAllowed(const Function * Fn) const27638 bool X86TargetLowering::areJTsAllowed(const Function *Fn) const {
27639   // If the subtarget is using retpolines, we need to not generate jump tables.
27640   if (Subtarget.useRetpolineIndirectBranches())
27641     return false;
27642 
27643   // Otherwise, fallback on the generic logic.
27644   return TargetLowering::areJTsAllowed(Fn);
27645 }
27646 
27647 //===----------------------------------------------------------------------===//
27648 //                           X86 Scheduler Hooks
27649 //===----------------------------------------------------------------------===//
27650 
27651 /// Utility function to emit xbegin specifying the start of an RTM region.
emitXBegin(MachineInstr & MI,MachineBasicBlock * MBB,const TargetInstrInfo * TII)27652 static MachineBasicBlock *emitXBegin(MachineInstr &MI, MachineBasicBlock *MBB,
27653                                      const TargetInstrInfo *TII) {
27654   DebugLoc DL = MI.getDebugLoc();
27655 
27656   const BasicBlock *BB = MBB->getBasicBlock();
27657   MachineFunction::iterator I = ++MBB->getIterator();
27658 
27659   // For the v = xbegin(), we generate
27660   //
27661   // thisMBB:
27662   //  xbegin sinkMBB
27663   //
27664   // mainMBB:
27665   //  s0 = -1
27666   //
27667   // fallBB:
27668   //  eax = # XABORT_DEF
27669   //  s1 = eax
27670   //
27671   // sinkMBB:
27672   //  v = phi(s0/mainBB, s1/fallBB)
27673 
27674   MachineBasicBlock *thisMBB = MBB;
27675   MachineFunction *MF = MBB->getParent();
27676   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
27677   MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
27678   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
27679   MF->insert(I, mainMBB);
27680   MF->insert(I, fallMBB);
27681   MF->insert(I, sinkMBB);
27682 
27683   // Transfer the remainder of BB and its successor edges to sinkMBB.
27684   sinkMBB->splice(sinkMBB->begin(), MBB,
27685                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
27686   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
27687 
27688   MachineRegisterInfo &MRI = MF->getRegInfo();
27689   unsigned DstReg = MI.getOperand(0).getReg();
27690   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
27691   unsigned mainDstReg = MRI.createVirtualRegister(RC);
27692   unsigned fallDstReg = MRI.createVirtualRegister(RC);
27693 
27694   // thisMBB:
27695   //  xbegin fallMBB
27696   //  # fallthrough to mainMBB
27697   //  # abortion to fallMBB
27698   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(fallMBB);
27699   thisMBB->addSuccessor(mainMBB);
27700   thisMBB->addSuccessor(fallMBB);
27701 
27702   // mainMBB:
27703   //  mainDstReg := -1
27704   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), mainDstReg).addImm(-1);
27705   BuildMI(mainMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
27706   mainMBB->addSuccessor(sinkMBB);
27707 
27708   // fallMBB:
27709   //  ; pseudo instruction to model hardware's definition from XABORT
27710   //  EAX := XABORT_DEF
27711   //  fallDstReg := EAX
27712   BuildMI(fallMBB, DL, TII->get(X86::XABORT_DEF));
27713   BuildMI(fallMBB, DL, TII->get(TargetOpcode::COPY), fallDstReg)
27714       .addReg(X86::EAX);
27715   fallMBB->addSuccessor(sinkMBB);
27716 
27717   // sinkMBB:
27718   //  DstReg := phi(mainDstReg/mainBB, fallDstReg/fallBB)
27719   BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI), DstReg)
27720       .addReg(mainDstReg).addMBB(mainMBB)
27721       .addReg(fallDstReg).addMBB(fallMBB);
27722 
27723   MI.eraseFromParent();
27724   return sinkMBB;
27725 }
27726 
emitWRPKRU(MachineInstr & MI,MachineBasicBlock * BB,const X86Subtarget & Subtarget)27727 static MachineBasicBlock *emitWRPKRU(MachineInstr &MI, MachineBasicBlock *BB,
27728                                      const X86Subtarget &Subtarget) {
27729   DebugLoc dl = MI.getDebugLoc();
27730   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
27731 
27732   // insert input VAL into EAX
27733   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
27734       .addReg(MI.getOperand(0).getReg());
27735   // insert zero to ECX
27736   BuildMI(*BB, MI, dl, TII->get(X86::MOV32r0), X86::ECX);
27737 
27738   // insert zero to EDX
27739   BuildMI(*BB, MI, dl, TII->get(X86::MOV32r0), X86::EDX);
27740 
27741   // insert WRPKRU instruction
27742   BuildMI(*BB, MI, dl, TII->get(X86::WRPKRUr));
27743 
27744   MI.eraseFromParent(); // The pseudo is gone now.
27745   return BB;
27746 }
27747 
emitRDPKRU(MachineInstr & MI,MachineBasicBlock * BB,const X86Subtarget & Subtarget)27748 static MachineBasicBlock *emitRDPKRU(MachineInstr &MI, MachineBasicBlock *BB,
27749                                      const X86Subtarget &Subtarget) {
27750   DebugLoc dl = MI.getDebugLoc();
27751   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
27752 
27753   // insert zero to ECX
27754   BuildMI(*BB, MI, dl, TII->get(X86::MOV32r0), X86::ECX);
27755 
27756   // insert RDPKRU instruction
27757   BuildMI(*BB, MI, dl, TII->get(X86::RDPKRUr));
27758   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), MI.getOperand(0).getReg())
27759       .addReg(X86::EAX);
27760 
27761   MI.eraseFromParent(); // The pseudo is gone now.
27762   return BB;
27763 }
27764 
emitMonitor(MachineInstr & MI,MachineBasicBlock * BB,const X86Subtarget & Subtarget,unsigned Opc)27765 static MachineBasicBlock *emitMonitor(MachineInstr &MI, MachineBasicBlock *BB,
27766                                       const X86Subtarget &Subtarget,
27767                                       unsigned Opc) {
27768   DebugLoc dl = MI.getDebugLoc();
27769   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
27770   // Address into RAX/EAX, other two args into ECX, EDX.
27771   unsigned MemOpc = Subtarget.is64Bit() ? X86::LEA64r : X86::LEA32r;
27772   unsigned MemReg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
27773   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
27774   for (int i = 0; i < X86::AddrNumOperands; ++i)
27775     MIB.add(MI.getOperand(i));
27776 
27777   unsigned ValOps = X86::AddrNumOperands;
27778   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
27779       .addReg(MI.getOperand(ValOps).getReg());
27780   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
27781       .addReg(MI.getOperand(ValOps + 1).getReg());
27782 
27783   // The instruction doesn't actually take any operands though.
27784   BuildMI(*BB, MI, dl, TII->get(Opc));
27785 
27786   MI.eraseFromParent(); // The pseudo is gone now.
27787   return BB;
27788 }
27789 
emitClzero(MachineInstr * MI,MachineBasicBlock * BB,const X86Subtarget & Subtarget)27790 static MachineBasicBlock *emitClzero(MachineInstr *MI, MachineBasicBlock *BB,
27791                                       const X86Subtarget &Subtarget) {
27792   DebugLoc dl = MI->getDebugLoc();
27793   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
27794   // Address into RAX/EAX
27795   unsigned MemOpc = Subtarget.is64Bit() ? X86::LEA64r : X86::LEA32r;
27796   unsigned MemReg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
27797   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
27798   for (int i = 0; i < X86::AddrNumOperands; ++i)
27799     MIB.add(MI->getOperand(i));
27800 
27801   // The instruction doesn't actually take any operands though.
27802   BuildMI(*BB, MI, dl, TII->get(X86::CLZEROr));
27803 
27804   MI->eraseFromParent(); // The pseudo is gone now.
27805   return BB;
27806 }
27807 
27808 
27809 
27810 MachineBasicBlock *
EmitVAARG64WithCustomInserter(MachineInstr & MI,MachineBasicBlock * MBB) const27811 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr &MI,
27812                                                  MachineBasicBlock *MBB) const {
27813   // Emit va_arg instruction on X86-64.
27814 
27815   // Operands to this pseudo-instruction:
27816   // 0  ) Output        : destination address (reg)
27817   // 1-5) Input         : va_list address (addr, i64mem)
27818   // 6  ) ArgSize       : Size (in bytes) of vararg type
27819   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
27820   // 8  ) Align         : Alignment of type
27821   // 9  ) EFLAGS (implicit-def)
27822 
27823   assert(MI.getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
27824   static_assert(X86::AddrNumOperands == 5,
27825                 "VAARG_64 assumes 5 address operands");
27826 
27827   unsigned DestReg = MI.getOperand(0).getReg();
27828   MachineOperand &Base = MI.getOperand(1);
27829   MachineOperand &Scale = MI.getOperand(2);
27830   MachineOperand &Index = MI.getOperand(3);
27831   MachineOperand &Disp = MI.getOperand(4);
27832   MachineOperand &Segment = MI.getOperand(5);
27833   unsigned ArgSize = MI.getOperand(6).getImm();
27834   unsigned ArgMode = MI.getOperand(7).getImm();
27835   unsigned Align = MI.getOperand(8).getImm();
27836 
27837   // Memory Reference
27838   assert(MI.hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
27839   SmallVector<MachineMemOperand *, 1> MMOs(MI.memoperands_begin(),
27840                                            MI.memoperands_end());
27841 
27842   // Machine Information
27843   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
27844   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
27845   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
27846   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
27847   DebugLoc DL = MI.getDebugLoc();
27848 
27849   // struct va_list {
27850   //   i32   gp_offset
27851   //   i32   fp_offset
27852   //   i64   overflow_area (address)
27853   //   i64   reg_save_area (address)
27854   // }
27855   // sizeof(va_list) = 24
27856   // alignment(va_list) = 8
27857 
27858   unsigned TotalNumIntRegs = 6;
27859   unsigned TotalNumXMMRegs = 8;
27860   bool UseGPOffset = (ArgMode == 1);
27861   bool UseFPOffset = (ArgMode == 2);
27862   unsigned MaxOffset = TotalNumIntRegs * 8 +
27863                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
27864 
27865   /* Align ArgSize to a multiple of 8 */
27866   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
27867   bool NeedsAlign = (Align > 8);
27868 
27869   MachineBasicBlock *thisMBB = MBB;
27870   MachineBasicBlock *overflowMBB;
27871   MachineBasicBlock *offsetMBB;
27872   MachineBasicBlock *endMBB;
27873 
27874   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
27875   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
27876   unsigned OffsetReg = 0;
27877 
27878   if (!UseGPOffset && !UseFPOffset) {
27879     // If we only pull from the overflow region, we don't create a branch.
27880     // We don't need to alter control flow.
27881     OffsetDestReg = 0; // unused
27882     OverflowDestReg = DestReg;
27883 
27884     offsetMBB = nullptr;
27885     overflowMBB = thisMBB;
27886     endMBB = thisMBB;
27887   } else {
27888     // First emit code to check if gp_offset (or fp_offset) is below the bound.
27889     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
27890     // If not, pull from overflow_area. (branch to overflowMBB)
27891     //
27892     //       thisMBB
27893     //         |     .
27894     //         |        .
27895     //     offsetMBB   overflowMBB
27896     //         |        .
27897     //         |     .
27898     //        endMBB
27899 
27900     // Registers for the PHI in endMBB
27901     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
27902     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
27903 
27904     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
27905     MachineFunction *MF = MBB->getParent();
27906     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
27907     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
27908     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
27909 
27910     MachineFunction::iterator MBBIter = ++MBB->getIterator();
27911 
27912     // Insert the new basic blocks
27913     MF->insert(MBBIter, offsetMBB);
27914     MF->insert(MBBIter, overflowMBB);
27915     MF->insert(MBBIter, endMBB);
27916 
27917     // Transfer the remainder of MBB and its successor edges to endMBB.
27918     endMBB->splice(endMBB->begin(), thisMBB,
27919                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
27920     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
27921 
27922     // Make offsetMBB and overflowMBB successors of thisMBB
27923     thisMBB->addSuccessor(offsetMBB);
27924     thisMBB->addSuccessor(overflowMBB);
27925 
27926     // endMBB is a successor of both offsetMBB and overflowMBB
27927     offsetMBB->addSuccessor(endMBB);
27928     overflowMBB->addSuccessor(endMBB);
27929 
27930     // Load the offset value into a register
27931     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
27932     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
27933         .add(Base)
27934         .add(Scale)
27935         .add(Index)
27936         .addDisp(Disp, UseFPOffset ? 4 : 0)
27937         .add(Segment)
27938         .setMemRefs(MMOs);
27939 
27940     // Check if there is enough room left to pull this argument.
27941     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
27942       .addReg(OffsetReg)
27943       .addImm(MaxOffset + 8 - ArgSizeA8);
27944 
27945     // Branch to "overflowMBB" if offset >= max
27946     // Fall through to "offsetMBB" otherwise
27947     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
27948       .addMBB(overflowMBB);
27949   }
27950 
27951   // In offsetMBB, emit code to use the reg_save_area.
27952   if (offsetMBB) {
27953     assert(OffsetReg != 0);
27954 
27955     // Read the reg_save_area address.
27956     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
27957     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
27958         .add(Base)
27959         .add(Scale)
27960         .add(Index)
27961         .addDisp(Disp, 16)
27962         .add(Segment)
27963         .setMemRefs(MMOs);
27964 
27965     // Zero-extend the offset
27966     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
27967       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
27968         .addImm(0)
27969         .addReg(OffsetReg)
27970         .addImm(X86::sub_32bit);
27971 
27972     // Add the offset to the reg_save_area to get the final address.
27973     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
27974       .addReg(OffsetReg64)
27975       .addReg(RegSaveReg);
27976 
27977     // Compute the offset for the next argument
27978     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
27979     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
27980       .addReg(OffsetReg)
27981       .addImm(UseFPOffset ? 16 : 8);
27982 
27983     // Store it back into the va_list.
27984     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
27985         .add(Base)
27986         .add(Scale)
27987         .add(Index)
27988         .addDisp(Disp, UseFPOffset ? 4 : 0)
27989         .add(Segment)
27990         .addReg(NextOffsetReg)
27991         .setMemRefs(MMOs);
27992 
27993     // Jump to endMBB
27994     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
27995       .addMBB(endMBB);
27996   }
27997 
27998   //
27999   // Emit code to use overflow area
28000   //
28001 
28002   // Load the overflow_area address into a register.
28003   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
28004   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
28005       .add(Base)
28006       .add(Scale)
28007       .add(Index)
28008       .addDisp(Disp, 8)
28009       .add(Segment)
28010       .setMemRefs(MMOs);
28011 
28012   // If we need to align it, do so. Otherwise, just copy the address
28013   // to OverflowDestReg.
28014   if (NeedsAlign) {
28015     // Align the overflow address
28016     assert(isPowerOf2_32(Align) && "Alignment must be a power of 2");
28017     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
28018 
28019     // aligned_addr = (addr + (align-1)) & ~(align-1)
28020     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
28021       .addReg(OverflowAddrReg)
28022       .addImm(Align-1);
28023 
28024     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
28025       .addReg(TmpReg)
28026       .addImm(~(uint64_t)(Align-1));
28027   } else {
28028     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
28029       .addReg(OverflowAddrReg);
28030   }
28031 
28032   // Compute the next overflow address after this argument.
28033   // (the overflow address should be kept 8-byte aligned)
28034   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
28035   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
28036     .addReg(OverflowDestReg)
28037     .addImm(ArgSizeA8);
28038 
28039   // Store the new overflow address.
28040   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
28041       .add(Base)
28042       .add(Scale)
28043       .add(Index)
28044       .addDisp(Disp, 8)
28045       .add(Segment)
28046       .addReg(NextAddrReg)
28047       .setMemRefs(MMOs);
28048 
28049   // If we branched, emit the PHI to the front of endMBB.
28050   if (offsetMBB) {
28051     BuildMI(*endMBB, endMBB->begin(), DL,
28052             TII->get(X86::PHI), DestReg)
28053       .addReg(OffsetDestReg).addMBB(offsetMBB)
28054       .addReg(OverflowDestReg).addMBB(overflowMBB);
28055   }
28056 
28057   // Erase the pseudo instruction
28058   MI.eraseFromParent();
28059 
28060   return endMBB;
28061 }
28062 
EmitVAStartSaveXMMRegsWithCustomInserter(MachineInstr & MI,MachineBasicBlock * MBB) const28063 MachineBasicBlock *X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
28064     MachineInstr &MI, MachineBasicBlock *MBB) const {
28065   // Emit code to save XMM registers to the stack. The ABI says that the
28066   // number of registers to save is given in %al, so it's theoretically
28067   // possible to do an indirect jump trick to avoid saving all of them,
28068   // however this code takes a simpler approach and just executes all
28069   // of the stores if %al is non-zero. It's less code, and it's probably
28070   // easier on the hardware branch predictor, and stores aren't all that
28071   // expensive anyway.
28072 
28073   // Create the new basic blocks. One block contains all the XMM stores,
28074   // and one block is the final destination regardless of whether any
28075   // stores were performed.
28076   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
28077   MachineFunction *F = MBB->getParent();
28078   MachineFunction::iterator MBBIter = ++MBB->getIterator();
28079   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
28080   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
28081   F->insert(MBBIter, XMMSaveMBB);
28082   F->insert(MBBIter, EndMBB);
28083 
28084   // Transfer the remainder of MBB and its successor edges to EndMBB.
28085   EndMBB->splice(EndMBB->begin(), MBB,
28086                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
28087   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
28088 
28089   // The original block will now fall through to the XMM save block.
28090   MBB->addSuccessor(XMMSaveMBB);
28091   // The XMMSaveMBB will fall through to the end block.
28092   XMMSaveMBB->addSuccessor(EndMBB);
28093 
28094   // Now add the instructions.
28095   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
28096   DebugLoc DL = MI.getDebugLoc();
28097 
28098   unsigned CountReg = MI.getOperand(0).getReg();
28099   int64_t RegSaveFrameIndex = MI.getOperand(1).getImm();
28100   int64_t VarArgsFPOffset = MI.getOperand(2).getImm();
28101 
28102   if (!Subtarget.isCallingConvWin64(F->getFunction().getCallingConv())) {
28103     // If %al is 0, branch around the XMM save block.
28104     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
28105     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
28106     MBB->addSuccessor(EndMBB);
28107   }
28108 
28109   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
28110   // that was just emitted, but clearly shouldn't be "saved".
28111   assert((MI.getNumOperands() <= 3 ||
28112           !MI.getOperand(MI.getNumOperands() - 1).isReg() ||
28113           MI.getOperand(MI.getNumOperands() - 1).getReg() == X86::EFLAGS) &&
28114          "Expected last argument to be EFLAGS");
28115   unsigned MOVOpc = Subtarget.hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
28116   // In the XMM save block, save all the XMM argument registers.
28117   for (int i = 3, e = MI.getNumOperands() - 1; i != e; ++i) {
28118     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
28119     MachineMemOperand *MMO = F->getMachineMemOperand(
28120         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
28121         MachineMemOperand::MOStore,
28122         /*Size=*/16, /*Align=*/16);
28123     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
28124         .addFrameIndex(RegSaveFrameIndex)
28125         .addImm(/*Scale=*/1)
28126         .addReg(/*IndexReg=*/0)
28127         .addImm(/*Disp=*/Offset)
28128         .addReg(/*Segment=*/0)
28129         .addReg(MI.getOperand(i).getReg())
28130         .addMemOperand(MMO);
28131   }
28132 
28133   MI.eraseFromParent(); // The pseudo instruction is gone now.
28134 
28135   return EndMBB;
28136 }
28137 
28138 // The EFLAGS operand of SelectItr might be missing a kill marker
28139 // because there were multiple uses of EFLAGS, and ISel didn't know
28140 // which to mark. Figure out whether SelectItr should have had a
28141 // kill marker, and set it if it should. Returns the correct kill
28142 // marker value.
checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,MachineBasicBlock * BB,const TargetRegisterInfo * TRI)28143 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
28144                                      MachineBasicBlock* BB,
28145                                      const TargetRegisterInfo* TRI) {
28146   // Scan forward through BB for a use/def of EFLAGS.
28147   MachineBasicBlock::iterator miI(std::next(SelectItr));
28148   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
28149     const MachineInstr& mi = *miI;
28150     if (mi.readsRegister(X86::EFLAGS))
28151       return false;
28152     if (mi.definesRegister(X86::EFLAGS))
28153       break; // Should have kill-flag - update below.
28154   }
28155 
28156   // If we hit the end of the block, check whether EFLAGS is live into a
28157   // successor.
28158   if (miI == BB->end()) {
28159     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
28160                                           sEnd = BB->succ_end();
28161          sItr != sEnd; ++sItr) {
28162       MachineBasicBlock* succ = *sItr;
28163       if (succ->isLiveIn(X86::EFLAGS))
28164         return false;
28165     }
28166   }
28167 
28168   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
28169   // out. SelectMI should have a kill flag on EFLAGS.
28170   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
28171   return true;
28172 }
28173 
28174 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
28175 // together with other CMOV pseudo-opcodes into a single basic-block with
28176 // conditional jump around it.
isCMOVPseudo(MachineInstr & MI)28177 static bool isCMOVPseudo(MachineInstr &MI) {
28178   switch (MI.getOpcode()) {
28179   case X86::CMOV_FR32:
28180   case X86::CMOV_FR64:
28181   case X86::CMOV_GR8:
28182   case X86::CMOV_GR16:
28183   case X86::CMOV_GR32:
28184   case X86::CMOV_RFP32:
28185   case X86::CMOV_RFP64:
28186   case X86::CMOV_RFP80:
28187   case X86::CMOV_VR128:
28188   case X86::CMOV_VR128X:
28189   case X86::CMOV_VR256:
28190   case X86::CMOV_VR256X:
28191   case X86::CMOV_VR512:
28192   case X86::CMOV_VK2:
28193   case X86::CMOV_VK4:
28194   case X86::CMOV_VK8:
28195   case X86::CMOV_VK16:
28196   case X86::CMOV_VK32:
28197   case X86::CMOV_VK64:
28198     return true;
28199 
28200   default:
28201     return false;
28202   }
28203 }
28204 
28205 // Helper function, which inserts PHI functions into SinkMBB:
28206 //   %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
28207 // where %FalseValue(i) and %TrueValue(i) are taken from the consequent CMOVs
28208 // in [MIItBegin, MIItEnd) range. It returns the last MachineInstrBuilder for
28209 // the last PHI function inserted.
createPHIsForCMOVsInSinkBB(MachineBasicBlock::iterator MIItBegin,MachineBasicBlock::iterator MIItEnd,MachineBasicBlock * TrueMBB,MachineBasicBlock * FalseMBB,MachineBasicBlock * SinkMBB)28210 static MachineInstrBuilder createPHIsForCMOVsInSinkBB(
28211     MachineBasicBlock::iterator MIItBegin, MachineBasicBlock::iterator MIItEnd,
28212     MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
28213     MachineBasicBlock *SinkMBB) {
28214   MachineFunction *MF = TrueMBB->getParent();
28215   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
28216   DebugLoc DL = MIItBegin->getDebugLoc();
28217 
28218   X86::CondCode CC = X86::CondCode(MIItBegin->getOperand(3).getImm());
28219   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
28220 
28221   MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
28222 
28223   // As we are creating the PHIs, we have to be careful if there is more than
28224   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
28225   // PHIs have to reference the individual true/false inputs from earlier PHIs.
28226   // That also means that PHI construction must work forward from earlier to
28227   // later, and that the code must maintain a mapping from earlier PHI's
28228   // destination registers, and the registers that went into the PHI.
28229   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
28230   MachineInstrBuilder MIB;
28231 
28232   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
28233     unsigned DestReg = MIIt->getOperand(0).getReg();
28234     unsigned Op1Reg = MIIt->getOperand(1).getReg();
28235     unsigned Op2Reg = MIIt->getOperand(2).getReg();
28236 
28237     // If this CMOV we are generating is the opposite condition from
28238     // the jump we generated, then we have to swap the operands for the
28239     // PHI that is going to be generated.
28240     if (MIIt->getOperand(3).getImm() == OppCC)
28241       std::swap(Op1Reg, Op2Reg);
28242 
28243     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
28244       Op1Reg = RegRewriteTable[Op1Reg].first;
28245 
28246     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
28247       Op2Reg = RegRewriteTable[Op2Reg].second;
28248 
28249     MIB = BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(X86::PHI), DestReg)
28250               .addReg(Op1Reg)
28251               .addMBB(FalseMBB)
28252               .addReg(Op2Reg)
28253               .addMBB(TrueMBB);
28254 
28255     // Add this PHI to the rewrite table.
28256     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
28257   }
28258 
28259   return MIB;
28260 }
28261 
28262 // Lower cascaded selects in form of (SecondCmov (FirstCMOV F, T, cc1), T, cc2).
28263 MachineBasicBlock *
EmitLoweredCascadedSelect(MachineInstr & FirstCMOV,MachineInstr & SecondCascadedCMOV,MachineBasicBlock * ThisMBB) const28264 X86TargetLowering::EmitLoweredCascadedSelect(MachineInstr &FirstCMOV,
28265                                              MachineInstr &SecondCascadedCMOV,
28266                                              MachineBasicBlock *ThisMBB) const {
28267   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
28268   DebugLoc DL = FirstCMOV.getDebugLoc();
28269 
28270   // We lower cascaded CMOVs such as
28271   //
28272   //   (SecondCascadedCMOV (FirstCMOV F, T, cc1), T, cc2)
28273   //
28274   // to two successive branches.
28275   //
28276   // Without this, we would add a PHI between the two jumps, which ends up
28277   // creating a few copies all around. For instance, for
28278   //
28279   //    (sitofp (zext (fcmp une)))
28280   //
28281   // we would generate:
28282   //
28283   //         ucomiss %xmm1, %xmm0
28284   //         movss  <1.0f>, %xmm0
28285   //         movaps  %xmm0, %xmm1
28286   //         jne     .LBB5_2
28287   //         xorps   %xmm1, %xmm1
28288   // .LBB5_2:
28289   //         jp      .LBB5_4
28290   //         movaps  %xmm1, %xmm0
28291   // .LBB5_4:
28292   //         retq
28293   //
28294   // because this custom-inserter would have generated:
28295   //
28296   //   A
28297   //   | \
28298   //   |  B
28299   //   | /
28300   //   C
28301   //   | \
28302   //   |  D
28303   //   | /
28304   //   E
28305   //
28306   // A: X = ...; Y = ...
28307   // B: empty
28308   // C: Z = PHI [X, A], [Y, B]
28309   // D: empty
28310   // E: PHI [X, C], [Z, D]
28311   //
28312   // If we lower both CMOVs in a single step, we can instead generate:
28313   //
28314   //   A
28315   //   | \
28316   //   |  C
28317   //   | /|
28318   //   |/ |
28319   //   |  |
28320   //   |  D
28321   //   | /
28322   //   E
28323   //
28324   // A: X = ...; Y = ...
28325   // D: empty
28326   // E: PHI [X, A], [X, C], [Y, D]
28327   //
28328   // Which, in our sitofp/fcmp example, gives us something like:
28329   //
28330   //         ucomiss %xmm1, %xmm0
28331   //         movss  <1.0f>, %xmm0
28332   //         jne     .LBB5_4
28333   //         jp      .LBB5_4
28334   //         xorps   %xmm0, %xmm0
28335   // .LBB5_4:
28336   //         retq
28337   //
28338 
28339   // We lower cascaded CMOV into two successive branches to the same block.
28340   // EFLAGS is used by both, so mark it as live in the second.
28341   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
28342   MachineFunction *F = ThisMBB->getParent();
28343   MachineBasicBlock *FirstInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
28344   MachineBasicBlock *SecondInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
28345   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
28346 
28347   MachineFunction::iterator It = ++ThisMBB->getIterator();
28348   F->insert(It, FirstInsertedMBB);
28349   F->insert(It, SecondInsertedMBB);
28350   F->insert(It, SinkMBB);
28351 
28352   // For a cascaded CMOV, we lower it to two successive branches to
28353   // the same block (SinkMBB).  EFLAGS is used by both, so mark it as live in
28354   // the FirstInsertedMBB.
28355   FirstInsertedMBB->addLiveIn(X86::EFLAGS);
28356 
28357   // If the EFLAGS register isn't dead in the terminator, then claim that it's
28358   // live into the sink and copy blocks.
28359   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
28360   if (!SecondCascadedCMOV.killsRegister(X86::EFLAGS) &&
28361       !checkAndUpdateEFLAGSKill(SecondCascadedCMOV, ThisMBB, TRI)) {
28362     SecondInsertedMBB->addLiveIn(X86::EFLAGS);
28363     SinkMBB->addLiveIn(X86::EFLAGS);
28364   }
28365 
28366   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
28367   SinkMBB->splice(SinkMBB->begin(), ThisMBB,
28368                   std::next(MachineBasicBlock::iterator(FirstCMOV)),
28369                   ThisMBB->end());
28370   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
28371 
28372   // Fallthrough block for ThisMBB.
28373   ThisMBB->addSuccessor(FirstInsertedMBB);
28374   // The true block target of the first branch is always SinkMBB.
28375   ThisMBB->addSuccessor(SinkMBB);
28376   // Fallthrough block for FirstInsertedMBB.
28377   FirstInsertedMBB->addSuccessor(SecondInsertedMBB);
28378   // The true block for the branch of FirstInsertedMBB.
28379   FirstInsertedMBB->addSuccessor(SinkMBB);
28380   // This is fallthrough.
28381   SecondInsertedMBB->addSuccessor(SinkMBB);
28382 
28383   // Create the conditional branch instructions.
28384   X86::CondCode FirstCC = X86::CondCode(FirstCMOV.getOperand(3).getImm());
28385   unsigned Opc = X86::GetCondBranchFromCond(FirstCC);
28386   BuildMI(ThisMBB, DL, TII->get(Opc)).addMBB(SinkMBB);
28387 
28388   X86::CondCode SecondCC =
28389       X86::CondCode(SecondCascadedCMOV.getOperand(3).getImm());
28390   unsigned Opc2 = X86::GetCondBranchFromCond(SecondCC);
28391   BuildMI(FirstInsertedMBB, DL, TII->get(Opc2)).addMBB(SinkMBB);
28392 
28393   //  SinkMBB:
28394   //   %Result = phi [ %FalseValue, SecondInsertedMBB ], [ %TrueValue, ThisMBB ]
28395   unsigned DestReg = FirstCMOV.getOperand(0).getReg();
28396   unsigned Op1Reg = FirstCMOV.getOperand(1).getReg();
28397   unsigned Op2Reg = FirstCMOV.getOperand(2).getReg();
28398   MachineInstrBuilder MIB =
28399       BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII->get(X86::PHI), DestReg)
28400           .addReg(Op1Reg)
28401           .addMBB(SecondInsertedMBB)
28402           .addReg(Op2Reg)
28403           .addMBB(ThisMBB);
28404 
28405   // The second SecondInsertedMBB provides the same incoming value as the
28406   // FirstInsertedMBB (the True operand of the SELECT_CC/CMOV nodes).
28407   MIB.addReg(FirstCMOV.getOperand(2).getReg()).addMBB(FirstInsertedMBB);
28408   // Copy the PHI result to the register defined by the second CMOV.
28409   BuildMI(*SinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())), DL,
28410           TII->get(TargetOpcode::COPY),
28411           SecondCascadedCMOV.getOperand(0).getReg())
28412       .addReg(FirstCMOV.getOperand(0).getReg());
28413 
28414   // Now remove the CMOVs.
28415   FirstCMOV.eraseFromParent();
28416   SecondCascadedCMOV.eraseFromParent();
28417 
28418   return SinkMBB;
28419 }
28420 
28421 MachineBasicBlock *
EmitLoweredSelect(MachineInstr & MI,MachineBasicBlock * ThisMBB) const28422 X86TargetLowering::EmitLoweredSelect(MachineInstr &MI,
28423                                      MachineBasicBlock *ThisMBB) const {
28424   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
28425   DebugLoc DL = MI.getDebugLoc();
28426 
28427   // To "insert" a SELECT_CC instruction, we actually have to insert the
28428   // diamond control-flow pattern.  The incoming instruction knows the
28429   // destination vreg to set, the condition code register to branch on, the
28430   // true/false values to select between and a branch opcode to use.
28431 
28432   //  ThisMBB:
28433   //  ...
28434   //   TrueVal = ...
28435   //   cmpTY ccX, r1, r2
28436   //   bCC copy1MBB
28437   //   fallthrough --> FalseMBB
28438 
28439   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
28440   // as described above, by inserting a BB, and then making a PHI at the join
28441   // point to select the true and false operands of the CMOV in the PHI.
28442   //
28443   // The code also handles two different cases of multiple CMOV opcodes
28444   // in a row.
28445   //
28446   // Case 1:
28447   // In this case, there are multiple CMOVs in a row, all which are based on
28448   // the same condition setting (or the exact opposite condition setting).
28449   // In this case we can lower all the CMOVs using a single inserted BB, and
28450   // then make a number of PHIs at the join point to model the CMOVs. The only
28451   // trickiness here, is that in a case like:
28452   //
28453   // t2 = CMOV cond1 t1, f1
28454   // t3 = CMOV cond1 t2, f2
28455   //
28456   // when rewriting this into PHIs, we have to perform some renaming on the
28457   // temps since you cannot have a PHI operand refer to a PHI result earlier
28458   // in the same block.  The "simple" but wrong lowering would be:
28459   //
28460   // t2 = PHI t1(BB1), f1(BB2)
28461   // t3 = PHI t2(BB1), f2(BB2)
28462   //
28463   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
28464   // renaming is to note that on the path through BB1, t2 is really just a
28465   // copy of t1, and do that renaming, properly generating:
28466   //
28467   // t2 = PHI t1(BB1), f1(BB2)
28468   // t3 = PHI t1(BB1), f2(BB2)
28469   //
28470   // Case 2:
28471   // CMOV ((CMOV F, T, cc1), T, cc2) is checked here and handled by a separate
28472   // function - EmitLoweredCascadedSelect.
28473 
28474   X86::CondCode CC = X86::CondCode(MI.getOperand(3).getImm());
28475   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
28476   MachineInstr *LastCMOV = &MI;
28477   MachineBasicBlock::iterator NextMIIt =
28478       std::next(MachineBasicBlock::iterator(MI));
28479 
28480   // Check for case 1, where there are multiple CMOVs with the same condition
28481   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
28482   // number of jumps the most.
28483 
28484   if (isCMOVPseudo(MI)) {
28485     // See if we have a string of CMOVS with the same condition.
28486     while (NextMIIt != ThisMBB->end() && isCMOVPseudo(*NextMIIt) &&
28487            (NextMIIt->getOperand(3).getImm() == CC ||
28488             NextMIIt->getOperand(3).getImm() == OppCC)) {
28489       LastCMOV = &*NextMIIt;
28490       ++NextMIIt;
28491     }
28492   }
28493 
28494   // This checks for case 2, but only do this if we didn't already find
28495   // case 1, as indicated by LastCMOV == MI.
28496   if (LastCMOV == &MI && NextMIIt != ThisMBB->end() &&
28497       NextMIIt->getOpcode() == MI.getOpcode() &&
28498       NextMIIt->getOperand(2).getReg() == MI.getOperand(2).getReg() &&
28499       NextMIIt->getOperand(1).getReg() == MI.getOperand(0).getReg() &&
28500       NextMIIt->getOperand(1).isKill()) {
28501     return EmitLoweredCascadedSelect(MI, *NextMIIt, ThisMBB);
28502   }
28503 
28504   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
28505   MachineFunction *F = ThisMBB->getParent();
28506   MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
28507   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
28508 
28509   MachineFunction::iterator It = ++ThisMBB->getIterator();
28510   F->insert(It, FalseMBB);
28511   F->insert(It, SinkMBB);
28512 
28513   // If the EFLAGS register isn't dead in the terminator, then claim that it's
28514   // live into the sink and copy blocks.
28515   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
28516   if (!LastCMOV->killsRegister(X86::EFLAGS) &&
28517       !checkAndUpdateEFLAGSKill(LastCMOV, ThisMBB, TRI)) {
28518     FalseMBB->addLiveIn(X86::EFLAGS);
28519     SinkMBB->addLiveIn(X86::EFLAGS);
28520   }
28521 
28522   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
28523   SinkMBB->splice(SinkMBB->begin(), ThisMBB,
28524                   std::next(MachineBasicBlock::iterator(LastCMOV)),
28525                   ThisMBB->end());
28526   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
28527 
28528   // Fallthrough block for ThisMBB.
28529   ThisMBB->addSuccessor(FalseMBB);
28530   // The true block target of the first (or only) branch is always a SinkMBB.
28531   ThisMBB->addSuccessor(SinkMBB);
28532   // Fallthrough block for FalseMBB.
28533   FalseMBB->addSuccessor(SinkMBB);
28534 
28535   // Create the conditional branch instruction.
28536   unsigned Opc = X86::GetCondBranchFromCond(CC);
28537   BuildMI(ThisMBB, DL, TII->get(Opc)).addMBB(SinkMBB);
28538 
28539   //  SinkMBB:
28540   //   %Result = phi [ %FalseValue, FalseMBB ], [ %TrueValue, ThisMBB ]
28541   //  ...
28542   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
28543   MachineBasicBlock::iterator MIItEnd =
28544       std::next(MachineBasicBlock::iterator(LastCMOV));
28545   createPHIsForCMOVsInSinkBB(MIItBegin, MIItEnd, ThisMBB, FalseMBB, SinkMBB);
28546 
28547   // Now remove the CMOV(s).
28548   ThisMBB->erase(MIItBegin, MIItEnd);
28549 
28550   return SinkMBB;
28551 }
28552 
28553 MachineBasicBlock *
EmitLoweredAtomicFP(MachineInstr & MI,MachineBasicBlock * BB) const28554 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr &MI,
28555                                        MachineBasicBlock *BB) const {
28556   // Combine the following atomic floating-point modification pattern:
28557   //   a.store(reg OP a.load(acquire), release)
28558   // Transform them into:
28559   //   OPss (%gpr), %xmm
28560   //   movss %xmm, (%gpr)
28561   // Or sd equivalent for 64-bit operations.
28562   unsigned MOp, FOp;
28563   switch (MI.getOpcode()) {
28564   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
28565   case X86::RELEASE_FADD32mr:
28566     FOp = X86::ADDSSrm;
28567     MOp = X86::MOVSSmr;
28568     break;
28569   case X86::RELEASE_FADD64mr:
28570     FOp = X86::ADDSDrm;
28571     MOp = X86::MOVSDmr;
28572     break;
28573   }
28574   const X86InstrInfo *TII = Subtarget.getInstrInfo();
28575   DebugLoc DL = MI.getDebugLoc();
28576   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
28577   unsigned ValOpIdx = X86::AddrNumOperands;
28578   unsigned VSrc = MI.getOperand(ValOpIdx).getReg();
28579   MachineInstrBuilder MIB =
28580       BuildMI(*BB, MI, DL, TII->get(FOp),
28581               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
28582           .addReg(VSrc);
28583   for (int i = 0; i < X86::AddrNumOperands; ++i) {
28584     MachineOperand &Operand = MI.getOperand(i);
28585     // Clear any kill flags on register operands as we'll create a second
28586     // instruction using the same address operands.
28587     if (Operand.isReg())
28588       Operand.setIsKill(false);
28589     MIB.add(Operand);
28590   }
28591   MachineInstr *FOpMI = MIB;
28592   MIB = BuildMI(*BB, MI, DL, TII->get(MOp));
28593   for (int i = 0; i < X86::AddrNumOperands; ++i)
28594     MIB.add(MI.getOperand(i));
28595   MIB.addReg(FOpMI->getOperand(0).getReg(), RegState::Kill);
28596   MI.eraseFromParent(); // The pseudo instruction is gone now.
28597   return BB;
28598 }
28599 
28600 MachineBasicBlock *
EmitLoweredSegAlloca(MachineInstr & MI,MachineBasicBlock * BB) const28601 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr &MI,
28602                                         MachineBasicBlock *BB) const {
28603   MachineFunction *MF = BB->getParent();
28604   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
28605   DebugLoc DL = MI.getDebugLoc();
28606   const BasicBlock *LLVM_BB = BB->getBasicBlock();
28607 
28608   assert(MF->shouldSplitStack());
28609 
28610   const bool Is64Bit = Subtarget.is64Bit();
28611   const bool IsLP64 = Subtarget.isTarget64BitLP64();
28612 
28613   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
28614   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
28615 
28616   // BB:
28617   //  ... [Till the alloca]
28618   // If stacklet is not large enough, jump to mallocMBB
28619   //
28620   // bumpMBB:
28621   //  Allocate by subtracting from RSP
28622   //  Jump to continueMBB
28623   //
28624   // mallocMBB:
28625   //  Allocate by call to runtime
28626   //
28627   // continueMBB:
28628   //  ...
28629   //  [rest of original BB]
28630   //
28631 
28632   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
28633   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
28634   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
28635 
28636   MachineRegisterInfo &MRI = MF->getRegInfo();
28637   const TargetRegisterClass *AddrRegClass =
28638       getRegClassFor(getPointerTy(MF->getDataLayout()));
28639 
28640   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
28641            bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
28642            tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
28643            SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
28644            sizeVReg = MI.getOperand(1).getReg(),
28645            physSPReg =
28646                IsLP64 || Subtarget.isTargetNaCl64() ? X86::RSP : X86::ESP;
28647 
28648   MachineFunction::iterator MBBIter = ++BB->getIterator();
28649 
28650   MF->insert(MBBIter, bumpMBB);
28651   MF->insert(MBBIter, mallocMBB);
28652   MF->insert(MBBIter, continueMBB);
28653 
28654   continueMBB->splice(continueMBB->begin(), BB,
28655                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
28656   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
28657 
28658   // Add code to the main basic block to check if the stack limit has been hit,
28659   // and if so, jump to mallocMBB otherwise to bumpMBB.
28660   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
28661   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
28662     .addReg(tmpSPVReg).addReg(sizeVReg);
28663   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
28664     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
28665     .addReg(SPLimitVReg);
28666   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
28667 
28668   // bumpMBB simply decreases the stack pointer, since we know the current
28669   // stacklet has enough space.
28670   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
28671     .addReg(SPLimitVReg);
28672   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
28673     .addReg(SPLimitVReg);
28674   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
28675 
28676   // Calls into a routine in libgcc to allocate more space from the heap.
28677   const uint32_t *RegMask =
28678       Subtarget.getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
28679   if (IsLP64) {
28680     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
28681       .addReg(sizeVReg);
28682     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
28683       .addExternalSymbol("__morestack_allocate_stack_space")
28684       .addRegMask(RegMask)
28685       .addReg(X86::RDI, RegState::Implicit)
28686       .addReg(X86::RAX, RegState::ImplicitDefine);
28687   } else if (Is64Bit) {
28688     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
28689       .addReg(sizeVReg);
28690     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
28691       .addExternalSymbol("__morestack_allocate_stack_space")
28692       .addRegMask(RegMask)
28693       .addReg(X86::EDI, RegState::Implicit)
28694       .addReg(X86::EAX, RegState::ImplicitDefine);
28695   } else {
28696     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
28697       .addImm(12);
28698     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
28699     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
28700       .addExternalSymbol("__morestack_allocate_stack_space")
28701       .addRegMask(RegMask)
28702       .addReg(X86::EAX, RegState::ImplicitDefine);
28703   }
28704 
28705   if (!Is64Bit)
28706     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
28707       .addImm(16);
28708 
28709   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
28710     .addReg(IsLP64 ? X86::RAX : X86::EAX);
28711   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
28712 
28713   // Set up the CFG correctly.
28714   BB->addSuccessor(bumpMBB);
28715   BB->addSuccessor(mallocMBB);
28716   mallocMBB->addSuccessor(continueMBB);
28717   bumpMBB->addSuccessor(continueMBB);
28718 
28719   // Take care of the PHI nodes.
28720   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
28721           MI.getOperand(0).getReg())
28722       .addReg(mallocPtrVReg)
28723       .addMBB(mallocMBB)
28724       .addReg(bumpSPPtrVReg)
28725       .addMBB(bumpMBB);
28726 
28727   // Delete the original pseudo instruction.
28728   MI.eraseFromParent();
28729 
28730   // And we're done.
28731   return continueMBB;
28732 }
28733 
28734 MachineBasicBlock *
EmitLoweredCatchRet(MachineInstr & MI,MachineBasicBlock * BB) const28735 X86TargetLowering::EmitLoweredCatchRet(MachineInstr &MI,
28736                                        MachineBasicBlock *BB) const {
28737   MachineFunction *MF = BB->getParent();
28738   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
28739   MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
28740   DebugLoc DL = MI.getDebugLoc();
28741 
28742   assert(!isAsynchronousEHPersonality(
28743              classifyEHPersonality(MF->getFunction().getPersonalityFn())) &&
28744          "SEH does not use catchret!");
28745 
28746   // Only 32-bit EH needs to worry about manually restoring stack pointers.
28747   if (!Subtarget.is32Bit())
28748     return BB;
28749 
28750   // C++ EH creates a new target block to hold the restore code, and wires up
28751   // the new block to the return destination with a normal JMP_4.
28752   MachineBasicBlock *RestoreMBB =
28753       MF->CreateMachineBasicBlock(BB->getBasicBlock());
28754   assert(BB->succ_size() == 1);
28755   MF->insert(std::next(BB->getIterator()), RestoreMBB);
28756   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
28757   BB->addSuccessor(RestoreMBB);
28758   MI.getOperand(0).setMBB(RestoreMBB);
28759 
28760   auto RestoreMBBI = RestoreMBB->begin();
28761   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
28762   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
28763   return BB;
28764 }
28765 
28766 MachineBasicBlock *
EmitLoweredCatchPad(MachineInstr & MI,MachineBasicBlock * BB) const28767 X86TargetLowering::EmitLoweredCatchPad(MachineInstr &MI,
28768                                        MachineBasicBlock *BB) const {
28769   MachineFunction *MF = BB->getParent();
28770   const Constant *PerFn = MF->getFunction().getPersonalityFn();
28771   bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
28772   // Only 32-bit SEH requires special handling for catchpad.
28773   if (IsSEH && Subtarget.is32Bit()) {
28774     const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
28775     DebugLoc DL = MI.getDebugLoc();
28776     BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
28777   }
28778   MI.eraseFromParent();
28779   return BB;
28780 }
28781 
28782 MachineBasicBlock *
EmitLoweredTLSAddr(MachineInstr & MI,MachineBasicBlock * BB) const28783 X86TargetLowering::EmitLoweredTLSAddr(MachineInstr &MI,
28784                                       MachineBasicBlock *BB) const {
28785   // So, here we replace TLSADDR with the sequence:
28786   // adjust_stackdown -> TLSADDR -> adjust_stackup.
28787   // We need this because TLSADDR is lowered into calls
28788   // inside MC, therefore without the two markers shrink-wrapping
28789   // may push the prologue/epilogue pass them.
28790   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
28791   DebugLoc DL = MI.getDebugLoc();
28792   MachineFunction &MF = *BB->getParent();
28793 
28794   // Emit CALLSEQ_START right before the instruction.
28795   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
28796   MachineInstrBuilder CallseqStart =
28797     BuildMI(MF, DL, TII.get(AdjStackDown)).addImm(0).addImm(0).addImm(0);
28798   BB->insert(MachineBasicBlock::iterator(MI), CallseqStart);
28799 
28800   // Emit CALLSEQ_END right after the instruction.
28801   // We don't call erase from parent because we want to keep the
28802   // original instruction around.
28803   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
28804   MachineInstrBuilder CallseqEnd =
28805     BuildMI(MF, DL, TII.get(AdjStackUp)).addImm(0).addImm(0);
28806   BB->insertAfter(MachineBasicBlock::iterator(MI), CallseqEnd);
28807 
28808   return BB;
28809 }
28810 
28811 MachineBasicBlock *
EmitLoweredTLSCall(MachineInstr & MI,MachineBasicBlock * BB) const28812 X86TargetLowering::EmitLoweredTLSCall(MachineInstr &MI,
28813                                       MachineBasicBlock *BB) const {
28814   // This is pretty easy.  We're taking the value that we received from
28815   // our load from the relocation, sticking it in either RDI (x86-64)
28816   // or EAX and doing an indirect call.  The return value will then
28817   // be in the normal return register.
28818   MachineFunction *F = BB->getParent();
28819   const X86InstrInfo *TII = Subtarget.getInstrInfo();
28820   DebugLoc DL = MI.getDebugLoc();
28821 
28822   assert(Subtarget.isTargetDarwin() && "Darwin only instr emitted?");
28823   assert(MI.getOperand(3).isGlobal() && "This should be a global");
28824 
28825   // Get a register mask for the lowered call.
28826   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
28827   // proper register mask.
28828   const uint32_t *RegMask =
28829       Subtarget.is64Bit() ?
28830       Subtarget.getRegisterInfo()->getDarwinTLSCallPreservedMask() :
28831       Subtarget.getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
28832   if (Subtarget.is64Bit()) {
28833     MachineInstrBuilder MIB =
28834         BuildMI(*BB, MI, DL, TII->get(X86::MOV64rm), X86::RDI)
28835             .addReg(X86::RIP)
28836             .addImm(0)
28837             .addReg(0)
28838             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
28839                               MI.getOperand(3).getTargetFlags())
28840             .addReg(0);
28841     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
28842     addDirectMem(MIB, X86::RDI);
28843     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
28844   } else if (!isPositionIndependent()) {
28845     MachineInstrBuilder MIB =
28846         BuildMI(*BB, MI, DL, TII->get(X86::MOV32rm), X86::EAX)
28847             .addReg(0)
28848             .addImm(0)
28849             .addReg(0)
28850             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
28851                               MI.getOperand(3).getTargetFlags())
28852             .addReg(0);
28853     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
28854     addDirectMem(MIB, X86::EAX);
28855     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
28856   } else {
28857     MachineInstrBuilder MIB =
28858         BuildMI(*BB, MI, DL, TII->get(X86::MOV32rm), X86::EAX)
28859             .addReg(TII->getGlobalBaseReg(F))
28860             .addImm(0)
28861             .addReg(0)
28862             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
28863                               MI.getOperand(3).getTargetFlags())
28864             .addReg(0);
28865     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
28866     addDirectMem(MIB, X86::EAX);
28867     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
28868   }
28869 
28870   MI.eraseFromParent(); // The pseudo instruction is gone now.
28871   return BB;
28872 }
28873 
getOpcodeForRetpoline(unsigned RPOpc)28874 static unsigned getOpcodeForRetpoline(unsigned RPOpc) {
28875   switch (RPOpc) {
28876   case X86::RETPOLINE_CALL32:
28877     return X86::CALLpcrel32;
28878   case X86::RETPOLINE_CALL64:
28879     return X86::CALL64pcrel32;
28880   case X86::RETPOLINE_TCRETURN32:
28881     return X86::TCRETURNdi;
28882   case X86::RETPOLINE_TCRETURN64:
28883     return X86::TCRETURNdi64;
28884   }
28885   llvm_unreachable("not retpoline opcode");
28886 }
28887 
getRetpolineSymbol(const X86Subtarget & Subtarget,unsigned Reg)28888 static const char *getRetpolineSymbol(const X86Subtarget &Subtarget,
28889                                       unsigned Reg) {
28890   if (Subtarget.useRetpolineExternalThunk()) {
28891     // When using an external thunk for retpolines, we pick names that match the
28892     // names GCC happens to use as well. This helps simplify the implementation
28893     // of the thunks for kernels where they have no easy ability to create
28894     // aliases and are doing non-trivial configuration of the thunk's body. For
28895     // example, the Linux kernel will do boot-time hot patching of the thunk
28896     // bodies and cannot easily export aliases of these to loaded modules.
28897     //
28898     // Note that at any point in the future, we may need to change the semantics
28899     // of how we implement retpolines and at that time will likely change the
28900     // name of the called thunk. Essentially, there is no hard guarantee that
28901     // LLVM will generate calls to specific thunks, we merely make a best-effort
28902     // attempt to help out kernels and other systems where duplicating the
28903     // thunks is costly.
28904     switch (Reg) {
28905     case X86::EAX:
28906       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
28907       return "__x86_indirect_thunk_eax";
28908     case X86::ECX:
28909       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
28910       return "__x86_indirect_thunk_ecx";
28911     case X86::EDX:
28912       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
28913       return "__x86_indirect_thunk_edx";
28914     case X86::EDI:
28915       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
28916       return "__x86_indirect_thunk_edi";
28917     case X86::R11:
28918       assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
28919       return "__x86_indirect_thunk_r11";
28920     }
28921     llvm_unreachable("unexpected reg for retpoline");
28922   }
28923 
28924   // When targeting an internal COMDAT thunk use an LLVM-specific name.
28925   switch (Reg) {
28926   case X86::EAX:
28927     assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
28928     return "__llvm_retpoline_eax";
28929   case X86::ECX:
28930     assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
28931     return "__llvm_retpoline_ecx";
28932   case X86::EDX:
28933     assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
28934     return "__llvm_retpoline_edx";
28935   case X86::EDI:
28936     assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
28937     return "__llvm_retpoline_edi";
28938   case X86::R11:
28939     assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
28940     return "__llvm_retpoline_r11";
28941   }
28942   llvm_unreachable("unexpected reg for retpoline");
28943 }
28944 
28945 MachineBasicBlock *
EmitLoweredRetpoline(MachineInstr & MI,MachineBasicBlock * BB) const28946 X86TargetLowering::EmitLoweredRetpoline(MachineInstr &MI,
28947                                         MachineBasicBlock *BB) const {
28948   // Copy the virtual register into the R11 physical register and
28949   // call the retpoline thunk.
28950   DebugLoc DL = MI.getDebugLoc();
28951   const X86InstrInfo *TII = Subtarget.getInstrInfo();
28952   unsigned CalleeVReg = MI.getOperand(0).getReg();
28953   unsigned Opc = getOpcodeForRetpoline(MI.getOpcode());
28954 
28955   // Find an available scratch register to hold the callee. On 64-bit, we can
28956   // just use R11, but we scan for uses anyway to ensure we don't generate
28957   // incorrect code. On 32-bit, we use one of EAX, ECX, or EDX that isn't
28958   // already a register use operand to the call to hold the callee. If none
28959   // are available, use EDI instead. EDI is chosen because EBX is the PIC base
28960   // register and ESI is the base pointer to realigned stack frames with VLAs.
28961   SmallVector<unsigned, 3> AvailableRegs;
28962   if (Subtarget.is64Bit())
28963     AvailableRegs.push_back(X86::R11);
28964   else
28965     AvailableRegs.append({X86::EAX, X86::ECX, X86::EDX, X86::EDI});
28966 
28967   // Zero out any registers that are already used.
28968   for (const auto &MO : MI.operands()) {
28969     if (MO.isReg() && MO.isUse())
28970       for (unsigned &Reg : AvailableRegs)
28971         if (Reg == MO.getReg())
28972           Reg = 0;
28973   }
28974 
28975   // Choose the first remaining non-zero available register.
28976   unsigned AvailableReg = 0;
28977   for (unsigned MaybeReg : AvailableRegs) {
28978     if (MaybeReg) {
28979       AvailableReg = MaybeReg;
28980       break;
28981     }
28982   }
28983   if (!AvailableReg)
28984     report_fatal_error("calling convention incompatible with retpoline, no "
28985                        "available registers");
28986 
28987   const char *Symbol = getRetpolineSymbol(Subtarget, AvailableReg);
28988 
28989   BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), AvailableReg)
28990       .addReg(CalleeVReg);
28991   MI.getOperand(0).ChangeToES(Symbol);
28992   MI.setDesc(TII->get(Opc));
28993   MachineInstrBuilder(*BB->getParent(), &MI)
28994       .addReg(AvailableReg, RegState::Implicit | RegState::Kill);
28995   return BB;
28996 }
28997 
28998 /// SetJmp implies future control flow change upon calling the corresponding
28999 /// LongJmp.
29000 /// Instead of using the 'return' instruction, the long jump fixes the stack and
29001 /// performs an indirect branch. To do so it uses the registers that were stored
29002 /// in the jump buffer (when calling SetJmp).
29003 /// In case the shadow stack is enabled we need to fix it as well, because some
29004 /// return addresses will be skipped.
29005 /// The function will save the SSP for future fixing in the function
29006 /// emitLongJmpShadowStackFix.
29007 /// \sa emitLongJmpShadowStackFix
29008 /// \param [in] MI The temporary Machine Instruction for the builtin.
29009 /// \param [in] MBB The Machine Basic Block that will be modified.
emitSetJmpShadowStackFix(MachineInstr & MI,MachineBasicBlock * MBB) const29010 void X86TargetLowering::emitSetJmpShadowStackFix(MachineInstr &MI,
29011                                                  MachineBasicBlock *MBB) const {
29012   DebugLoc DL = MI.getDebugLoc();
29013   MachineFunction *MF = MBB->getParent();
29014   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
29015   MachineRegisterInfo &MRI = MF->getRegInfo();
29016   MachineInstrBuilder MIB;
29017 
29018   // Memory Reference.
29019   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
29020                                            MI.memoperands_end());
29021 
29022   // Initialize a register with zero.
29023   MVT PVT = getPointerTy(MF->getDataLayout());
29024   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
29025   unsigned ZReg = MRI.createVirtualRegister(PtrRC);
29026   unsigned XorRROpc = (PVT == MVT::i64) ? X86::XOR64rr : X86::XOR32rr;
29027   BuildMI(*MBB, MI, DL, TII->get(XorRROpc))
29028       .addDef(ZReg)
29029       .addReg(ZReg, RegState::Undef)
29030       .addReg(ZReg, RegState::Undef);
29031 
29032   // Read the current SSP Register value to the zeroed register.
29033   unsigned SSPCopyReg = MRI.createVirtualRegister(PtrRC);
29034   unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
29035   BuildMI(*MBB, MI, DL, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
29036 
29037   // Write the SSP register value to offset 3 in input memory buffer.
29038   unsigned PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
29039   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrStoreOpc));
29040   const int64_t SSPOffset = 3 * PVT.getStoreSize();
29041   const unsigned MemOpndSlot = 1;
29042   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
29043     if (i == X86::AddrDisp)
29044       MIB.addDisp(MI.getOperand(MemOpndSlot + i), SSPOffset);
29045     else
29046       MIB.add(MI.getOperand(MemOpndSlot + i));
29047   }
29048   MIB.addReg(SSPCopyReg);
29049   MIB.setMemRefs(MMOs);
29050 }
29051 
29052 MachineBasicBlock *
emitEHSjLjSetJmp(MachineInstr & MI,MachineBasicBlock * MBB) const29053 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
29054                                     MachineBasicBlock *MBB) const {
29055   DebugLoc DL = MI.getDebugLoc();
29056   MachineFunction *MF = MBB->getParent();
29057   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
29058   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
29059   MachineRegisterInfo &MRI = MF->getRegInfo();
29060 
29061   const BasicBlock *BB = MBB->getBasicBlock();
29062   MachineFunction::iterator I = ++MBB->getIterator();
29063 
29064   // Memory Reference
29065   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
29066                                            MI.memoperands_end());
29067 
29068   unsigned DstReg;
29069   unsigned MemOpndSlot = 0;
29070 
29071   unsigned CurOp = 0;
29072 
29073   DstReg = MI.getOperand(CurOp++).getReg();
29074   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
29075   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
29076   (void)TRI;
29077   unsigned mainDstReg = MRI.createVirtualRegister(RC);
29078   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
29079 
29080   MemOpndSlot = CurOp;
29081 
29082   MVT PVT = getPointerTy(MF->getDataLayout());
29083   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
29084          "Invalid Pointer Size!");
29085 
29086   // For v = setjmp(buf), we generate
29087   //
29088   // thisMBB:
29089   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
29090   //  SjLjSetup restoreMBB
29091   //
29092   // mainMBB:
29093   //  v_main = 0
29094   //
29095   // sinkMBB:
29096   //  v = phi(main, restore)
29097   //
29098   // restoreMBB:
29099   //  if base pointer being used, load it from frame
29100   //  v_restore = 1
29101 
29102   MachineBasicBlock *thisMBB = MBB;
29103   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
29104   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
29105   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
29106   MF->insert(I, mainMBB);
29107   MF->insert(I, sinkMBB);
29108   MF->push_back(restoreMBB);
29109   restoreMBB->setHasAddressTaken();
29110 
29111   MachineInstrBuilder MIB;
29112 
29113   // Transfer the remainder of BB and its successor edges to sinkMBB.
29114   sinkMBB->splice(sinkMBB->begin(), MBB,
29115                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
29116   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
29117 
29118   // thisMBB:
29119   unsigned PtrStoreOpc = 0;
29120   unsigned LabelReg = 0;
29121   const int64_t LabelOffset = 1 * PVT.getStoreSize();
29122   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
29123                      !isPositionIndependent();
29124 
29125   // Prepare IP either in reg or imm.
29126   if (!UseImmLabel) {
29127     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
29128     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
29129     LabelReg = MRI.createVirtualRegister(PtrRC);
29130     if (Subtarget.is64Bit()) {
29131       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
29132               .addReg(X86::RIP)
29133               .addImm(0)
29134               .addReg(0)
29135               .addMBB(restoreMBB)
29136               .addReg(0);
29137     } else {
29138       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
29139       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
29140               .addReg(XII->getGlobalBaseReg(MF))
29141               .addImm(0)
29142               .addReg(0)
29143               .addMBB(restoreMBB, Subtarget.classifyBlockAddressReference())
29144               .addReg(0);
29145     }
29146   } else
29147     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
29148   // Store IP
29149   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
29150   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
29151     if (i == X86::AddrDisp)
29152       MIB.addDisp(MI.getOperand(MemOpndSlot + i), LabelOffset);
29153     else
29154       MIB.add(MI.getOperand(MemOpndSlot + i));
29155   }
29156   if (!UseImmLabel)
29157     MIB.addReg(LabelReg);
29158   else
29159     MIB.addMBB(restoreMBB);
29160   MIB.setMemRefs(MMOs);
29161 
29162   if (MF->getMMI().getModule()->getModuleFlag("cf-protection-return")) {
29163     emitSetJmpShadowStackFix(MI, thisMBB);
29164   }
29165 
29166   // Setup
29167   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
29168           .addMBB(restoreMBB);
29169 
29170   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
29171   MIB.addRegMask(RegInfo->getNoPreservedMask());
29172   thisMBB->addSuccessor(mainMBB);
29173   thisMBB->addSuccessor(restoreMBB);
29174 
29175   // mainMBB:
29176   //  EAX = 0
29177   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
29178   mainMBB->addSuccessor(sinkMBB);
29179 
29180   // sinkMBB:
29181   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
29182           TII->get(X86::PHI), DstReg)
29183     .addReg(mainDstReg).addMBB(mainMBB)
29184     .addReg(restoreDstReg).addMBB(restoreMBB);
29185 
29186   // restoreMBB:
29187   if (RegInfo->hasBasePointer(*MF)) {
29188     const bool Uses64BitFramePtr =
29189         Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
29190     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
29191     X86FI->setRestoreBasePointer(MF);
29192     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
29193     unsigned BasePtr = RegInfo->getBaseRegister();
29194     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
29195     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
29196                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
29197       .setMIFlag(MachineInstr::FrameSetup);
29198   }
29199   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
29200   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
29201   restoreMBB->addSuccessor(sinkMBB);
29202 
29203   MI.eraseFromParent();
29204   return sinkMBB;
29205 }
29206 
29207 /// Fix the shadow stack using the previously saved SSP pointer.
29208 /// \sa emitSetJmpShadowStackFix
29209 /// \param [in] MI The temporary Machine Instruction for the builtin.
29210 /// \param [in] MBB The Machine Basic Block that will be modified.
29211 /// \return The sink MBB that will perform the future indirect branch.
29212 MachineBasicBlock *
emitLongJmpShadowStackFix(MachineInstr & MI,MachineBasicBlock * MBB) const29213 X86TargetLowering::emitLongJmpShadowStackFix(MachineInstr &MI,
29214                                              MachineBasicBlock *MBB) const {
29215   DebugLoc DL = MI.getDebugLoc();
29216   MachineFunction *MF = MBB->getParent();
29217   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
29218   MachineRegisterInfo &MRI = MF->getRegInfo();
29219 
29220   // Memory Reference
29221   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
29222                                            MI.memoperands_end());
29223 
29224   MVT PVT = getPointerTy(MF->getDataLayout());
29225   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
29226 
29227   // checkSspMBB:
29228   //         xor vreg1, vreg1
29229   //         rdssp vreg1
29230   //         test vreg1, vreg1
29231   //         je sinkMBB   # Jump if Shadow Stack is not supported
29232   // fallMBB:
29233   //         mov buf+24/12(%rip), vreg2
29234   //         sub vreg1, vreg2
29235   //         jbe sinkMBB  # No need to fix the Shadow Stack
29236   // fixShadowMBB:
29237   //         shr 3/2, vreg2
29238   //         incssp vreg2  # fix the SSP according to the lower 8 bits
29239   //         shr 8, vreg2
29240   //         je sinkMBB
29241   // fixShadowLoopPrepareMBB:
29242   //         shl vreg2
29243   //         mov 128, vreg3
29244   // fixShadowLoopMBB:
29245   //         incssp vreg3
29246   //         dec vreg2
29247   //         jne fixShadowLoopMBB # Iterate until you finish fixing
29248   //                              # the Shadow Stack
29249   // sinkMBB:
29250 
29251   MachineFunction::iterator I = ++MBB->getIterator();
29252   const BasicBlock *BB = MBB->getBasicBlock();
29253 
29254   MachineBasicBlock *checkSspMBB = MF->CreateMachineBasicBlock(BB);
29255   MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
29256   MachineBasicBlock *fixShadowMBB = MF->CreateMachineBasicBlock(BB);
29257   MachineBasicBlock *fixShadowLoopPrepareMBB = MF->CreateMachineBasicBlock(BB);
29258   MachineBasicBlock *fixShadowLoopMBB = MF->CreateMachineBasicBlock(BB);
29259   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
29260   MF->insert(I, checkSspMBB);
29261   MF->insert(I, fallMBB);
29262   MF->insert(I, fixShadowMBB);
29263   MF->insert(I, fixShadowLoopPrepareMBB);
29264   MF->insert(I, fixShadowLoopMBB);
29265   MF->insert(I, sinkMBB);
29266 
29267   // Transfer the remainder of BB and its successor edges to sinkMBB.
29268   sinkMBB->splice(sinkMBB->begin(), MBB, MachineBasicBlock::iterator(MI),
29269                   MBB->end());
29270   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
29271 
29272   MBB->addSuccessor(checkSspMBB);
29273 
29274   // Initialize a register with zero.
29275   unsigned ZReg = MRI.createVirtualRegister(PtrRC);
29276   unsigned XorRROpc = (PVT == MVT::i64) ? X86::XOR64rr : X86::XOR32rr;
29277   BuildMI(checkSspMBB, DL, TII->get(XorRROpc))
29278       .addDef(ZReg)
29279       .addReg(ZReg, RegState::Undef)
29280       .addReg(ZReg, RegState::Undef);
29281 
29282   // Read the current SSP Register value to the zeroed register.
29283   unsigned SSPCopyReg = MRI.createVirtualRegister(PtrRC);
29284   unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
29285   BuildMI(checkSspMBB, DL, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
29286 
29287   // Check whether the result of the SSP register is zero and jump directly
29288   // to the sink.
29289   unsigned TestRROpc = (PVT == MVT::i64) ? X86::TEST64rr : X86::TEST32rr;
29290   BuildMI(checkSspMBB, DL, TII->get(TestRROpc))
29291       .addReg(SSPCopyReg)
29292       .addReg(SSPCopyReg);
29293   BuildMI(checkSspMBB, DL, TII->get(X86::JE_1)).addMBB(sinkMBB);
29294   checkSspMBB->addSuccessor(sinkMBB);
29295   checkSspMBB->addSuccessor(fallMBB);
29296 
29297   // Reload the previously saved SSP register value.
29298   unsigned PrevSSPReg = MRI.createVirtualRegister(PtrRC);
29299   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
29300   const int64_t SPPOffset = 3 * PVT.getStoreSize();
29301   MachineInstrBuilder MIB =
29302       BuildMI(fallMBB, DL, TII->get(PtrLoadOpc), PrevSSPReg);
29303   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
29304     const MachineOperand &MO = MI.getOperand(i);
29305     if (i == X86::AddrDisp)
29306       MIB.addDisp(MO, SPPOffset);
29307     else if (MO.isReg()) // Don't add the whole operand, we don't want to
29308                          // preserve kill flags.
29309       MIB.addReg(MO.getReg());
29310     else
29311       MIB.add(MO);
29312   }
29313   MIB.setMemRefs(MMOs);
29314 
29315   // Subtract the current SSP from the previous SSP.
29316   unsigned SspSubReg = MRI.createVirtualRegister(PtrRC);
29317   unsigned SubRROpc = (PVT == MVT::i64) ? X86::SUB64rr : X86::SUB32rr;
29318   BuildMI(fallMBB, DL, TII->get(SubRROpc), SspSubReg)
29319       .addReg(PrevSSPReg)
29320       .addReg(SSPCopyReg);
29321 
29322   // Jump to sink in case PrevSSPReg <= SSPCopyReg.
29323   BuildMI(fallMBB, DL, TII->get(X86::JBE_1)).addMBB(sinkMBB);
29324   fallMBB->addSuccessor(sinkMBB);
29325   fallMBB->addSuccessor(fixShadowMBB);
29326 
29327   // Shift right by 2/3 for 32/64 because incssp multiplies the argument by 4/8.
29328   unsigned ShrRIOpc = (PVT == MVT::i64) ? X86::SHR64ri : X86::SHR32ri;
29329   unsigned Offset = (PVT == MVT::i64) ? 3 : 2;
29330   unsigned SspFirstShrReg = MRI.createVirtualRegister(PtrRC);
29331   BuildMI(fixShadowMBB, DL, TII->get(ShrRIOpc), SspFirstShrReg)
29332       .addReg(SspSubReg)
29333       .addImm(Offset);
29334 
29335   // Increase SSP when looking only on the lower 8 bits of the delta.
29336   unsigned IncsspOpc = (PVT == MVT::i64) ? X86::INCSSPQ : X86::INCSSPD;
29337   BuildMI(fixShadowMBB, DL, TII->get(IncsspOpc)).addReg(SspFirstShrReg);
29338 
29339   // Reset the lower 8 bits.
29340   unsigned SspSecondShrReg = MRI.createVirtualRegister(PtrRC);
29341   BuildMI(fixShadowMBB, DL, TII->get(ShrRIOpc), SspSecondShrReg)
29342       .addReg(SspFirstShrReg)
29343       .addImm(8);
29344 
29345   // Jump if the result of the shift is zero.
29346   BuildMI(fixShadowMBB, DL, TII->get(X86::JE_1)).addMBB(sinkMBB);
29347   fixShadowMBB->addSuccessor(sinkMBB);
29348   fixShadowMBB->addSuccessor(fixShadowLoopPrepareMBB);
29349 
29350   // Do a single shift left.
29351   unsigned ShlR1Opc = (PVT == MVT::i64) ? X86::SHL64r1 : X86::SHL32r1;
29352   unsigned SspAfterShlReg = MRI.createVirtualRegister(PtrRC);
29353   BuildMI(fixShadowLoopPrepareMBB, DL, TII->get(ShlR1Opc), SspAfterShlReg)
29354       .addReg(SspSecondShrReg);
29355 
29356   // Save the value 128 to a register (will be used next with incssp).
29357   unsigned Value128InReg = MRI.createVirtualRegister(PtrRC);
29358   unsigned MovRIOpc = (PVT == MVT::i64) ? X86::MOV64ri32 : X86::MOV32ri;
29359   BuildMI(fixShadowLoopPrepareMBB, DL, TII->get(MovRIOpc), Value128InReg)
29360       .addImm(128);
29361   fixShadowLoopPrepareMBB->addSuccessor(fixShadowLoopMBB);
29362 
29363   // Since incssp only looks at the lower 8 bits, we might need to do several
29364   // iterations of incssp until we finish fixing the shadow stack.
29365   unsigned DecReg = MRI.createVirtualRegister(PtrRC);
29366   unsigned CounterReg = MRI.createVirtualRegister(PtrRC);
29367   BuildMI(fixShadowLoopMBB, DL, TII->get(X86::PHI), CounterReg)
29368       .addReg(SspAfterShlReg)
29369       .addMBB(fixShadowLoopPrepareMBB)
29370       .addReg(DecReg)
29371       .addMBB(fixShadowLoopMBB);
29372 
29373   // Every iteration we increase the SSP by 128.
29374   BuildMI(fixShadowLoopMBB, DL, TII->get(IncsspOpc)).addReg(Value128InReg);
29375 
29376   // Every iteration we decrement the counter by 1.
29377   unsigned DecROpc = (PVT == MVT::i64) ? X86::DEC64r : X86::DEC32r;
29378   BuildMI(fixShadowLoopMBB, DL, TII->get(DecROpc), DecReg).addReg(CounterReg);
29379 
29380   // Jump if the counter is not zero yet.
29381   BuildMI(fixShadowLoopMBB, DL, TII->get(X86::JNE_1)).addMBB(fixShadowLoopMBB);
29382   fixShadowLoopMBB->addSuccessor(sinkMBB);
29383   fixShadowLoopMBB->addSuccessor(fixShadowLoopMBB);
29384 
29385   return sinkMBB;
29386 }
29387 
29388 MachineBasicBlock *
emitEHSjLjLongJmp(MachineInstr & MI,MachineBasicBlock * MBB) const29389 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
29390                                      MachineBasicBlock *MBB) const {
29391   DebugLoc DL = MI.getDebugLoc();
29392   MachineFunction *MF = MBB->getParent();
29393   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
29394   MachineRegisterInfo &MRI = MF->getRegInfo();
29395 
29396   // Memory Reference
29397   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
29398                                            MI.memoperands_end());
29399 
29400   MVT PVT = getPointerTy(MF->getDataLayout());
29401   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
29402          "Invalid Pointer Size!");
29403 
29404   const TargetRegisterClass *RC =
29405     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
29406   unsigned Tmp = MRI.createVirtualRegister(RC);
29407   // Since FP is only updated here but NOT referenced, it's treated as GPR.
29408   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
29409   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
29410   unsigned SP = RegInfo->getStackRegister();
29411 
29412   MachineInstrBuilder MIB;
29413 
29414   const int64_t LabelOffset = 1 * PVT.getStoreSize();
29415   const int64_t SPOffset = 2 * PVT.getStoreSize();
29416 
29417   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
29418   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
29419 
29420   MachineBasicBlock *thisMBB = MBB;
29421 
29422   // When CET and shadow stack is enabled, we need to fix the Shadow Stack.
29423   if (MF->getMMI().getModule()->getModuleFlag("cf-protection-return")) {
29424     thisMBB = emitLongJmpShadowStackFix(MI, thisMBB);
29425   }
29426 
29427   // Reload FP
29428   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), FP);
29429   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
29430     const MachineOperand &MO = MI.getOperand(i);
29431     if (MO.isReg()) // Don't add the whole operand, we don't want to
29432                     // preserve kill flags.
29433       MIB.addReg(MO.getReg());
29434     else
29435       MIB.add(MO);
29436   }
29437   MIB.setMemRefs(MMOs);
29438 
29439   // Reload IP
29440   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
29441   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
29442     const MachineOperand &MO = MI.getOperand(i);
29443     if (i == X86::AddrDisp)
29444       MIB.addDisp(MO, LabelOffset);
29445     else if (MO.isReg()) // Don't add the whole operand, we don't want to
29446                          // preserve kill flags.
29447       MIB.addReg(MO.getReg());
29448     else
29449       MIB.add(MO);
29450   }
29451   MIB.setMemRefs(MMOs);
29452 
29453   // Reload SP
29454   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), SP);
29455   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
29456     if (i == X86::AddrDisp)
29457       MIB.addDisp(MI.getOperand(i), SPOffset);
29458     else
29459       MIB.add(MI.getOperand(i)); // We can preserve the kill flags here, it's
29460                                  // the last instruction of the expansion.
29461   }
29462   MIB.setMemRefs(MMOs);
29463 
29464   // Jump
29465   BuildMI(*thisMBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
29466 
29467   MI.eraseFromParent();
29468   return thisMBB;
29469 }
29470 
SetupEntryBlockForSjLj(MachineInstr & MI,MachineBasicBlock * MBB,MachineBasicBlock * DispatchBB,int FI) const29471 void X86TargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
29472                                                MachineBasicBlock *MBB,
29473                                                MachineBasicBlock *DispatchBB,
29474                                                int FI) const {
29475   DebugLoc DL = MI.getDebugLoc();
29476   MachineFunction *MF = MBB->getParent();
29477   MachineRegisterInfo *MRI = &MF->getRegInfo();
29478   const X86InstrInfo *TII = Subtarget.getInstrInfo();
29479 
29480   MVT PVT = getPointerTy(MF->getDataLayout());
29481   assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
29482 
29483   unsigned Op = 0;
29484   unsigned VR = 0;
29485 
29486   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
29487                      !isPositionIndependent();
29488 
29489   if (UseImmLabel) {
29490     Op = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
29491   } else {
29492     const TargetRegisterClass *TRC =
29493         (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
29494     VR = MRI->createVirtualRegister(TRC);
29495     Op = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
29496 
29497     if (Subtarget.is64Bit())
29498       BuildMI(*MBB, MI, DL, TII->get(X86::LEA64r), VR)
29499           .addReg(X86::RIP)
29500           .addImm(1)
29501           .addReg(0)
29502           .addMBB(DispatchBB)
29503           .addReg(0);
29504     else
29505       BuildMI(*MBB, MI, DL, TII->get(X86::LEA32r), VR)
29506           .addReg(0) /* TII->getGlobalBaseReg(MF) */
29507           .addImm(1)
29508           .addReg(0)
29509           .addMBB(DispatchBB, Subtarget.classifyBlockAddressReference())
29510           .addReg(0);
29511   }
29512 
29513   MachineInstrBuilder MIB = BuildMI(*MBB, MI, DL, TII->get(Op));
29514   addFrameReference(MIB, FI, Subtarget.is64Bit() ? 56 : 36);
29515   if (UseImmLabel)
29516     MIB.addMBB(DispatchBB);
29517   else
29518     MIB.addReg(VR);
29519 }
29520 
29521 MachineBasicBlock *
EmitSjLjDispatchBlock(MachineInstr & MI,MachineBasicBlock * BB) const29522 X86TargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
29523                                          MachineBasicBlock *BB) const {
29524   DebugLoc DL = MI.getDebugLoc();
29525   MachineFunction *MF = BB->getParent();
29526   MachineFrameInfo &MFI = MF->getFrameInfo();
29527   MachineRegisterInfo *MRI = &MF->getRegInfo();
29528   const X86InstrInfo *TII = Subtarget.getInstrInfo();
29529   int FI = MFI.getFunctionContextIndex();
29530 
29531   // Get a mapping of the call site numbers to all of the landing pads they're
29532   // associated with.
29533   DenseMap<unsigned, SmallVector<MachineBasicBlock *, 2>> CallSiteNumToLPad;
29534   unsigned MaxCSNum = 0;
29535   for (auto &MBB : *MF) {
29536     if (!MBB.isEHPad())
29537       continue;
29538 
29539     MCSymbol *Sym = nullptr;
29540     for (const auto &MI : MBB) {
29541       if (MI.isDebugInstr())
29542         continue;
29543 
29544       assert(MI.isEHLabel() && "expected EH_LABEL");
29545       Sym = MI.getOperand(0).getMCSymbol();
29546       break;
29547     }
29548 
29549     if (!MF->hasCallSiteLandingPad(Sym))
29550       continue;
29551 
29552     for (unsigned CSI : MF->getCallSiteLandingPad(Sym)) {
29553       CallSiteNumToLPad[CSI].push_back(&MBB);
29554       MaxCSNum = std::max(MaxCSNum, CSI);
29555     }
29556   }
29557 
29558   // Get an ordered list of the machine basic blocks for the jump table.
29559   std::vector<MachineBasicBlock *> LPadList;
29560   SmallPtrSet<MachineBasicBlock *, 32> InvokeBBs;
29561   LPadList.reserve(CallSiteNumToLPad.size());
29562 
29563   for (unsigned CSI = 1; CSI <= MaxCSNum; ++CSI) {
29564     for (auto &LP : CallSiteNumToLPad[CSI]) {
29565       LPadList.push_back(LP);
29566       InvokeBBs.insert(LP->pred_begin(), LP->pred_end());
29567     }
29568   }
29569 
29570   assert(!LPadList.empty() &&
29571          "No landing pad destinations for the dispatch jump table!");
29572 
29573   // Create the MBBs for the dispatch code.
29574 
29575   // Shove the dispatch's address into the return slot in the function context.
29576   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
29577   DispatchBB->setIsEHPad(true);
29578 
29579   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
29580   BuildMI(TrapBB, DL, TII->get(X86::TRAP));
29581   DispatchBB->addSuccessor(TrapBB);
29582 
29583   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
29584   DispatchBB->addSuccessor(DispContBB);
29585 
29586   // Insert MBBs.
29587   MF->push_back(DispatchBB);
29588   MF->push_back(DispContBB);
29589   MF->push_back(TrapBB);
29590 
29591   // Insert code into the entry block that creates and registers the function
29592   // context.
29593   SetupEntryBlockForSjLj(MI, BB, DispatchBB, FI);
29594 
29595   // Create the jump table and associated information
29596   unsigned JTE = getJumpTableEncoding();
29597   MachineJumpTableInfo *JTI = MF->getOrCreateJumpTableInfo(JTE);
29598   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
29599 
29600   const X86RegisterInfo &RI = TII->getRegisterInfo();
29601   // Add a register mask with no preserved registers.  This results in all
29602   // registers being marked as clobbered.
29603   if (RI.hasBasePointer(*MF)) {
29604     const bool FPIs64Bit =
29605         Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
29606     X86MachineFunctionInfo *MFI = MF->getInfo<X86MachineFunctionInfo>();
29607     MFI->setRestoreBasePointer(MF);
29608 
29609     unsigned FP = RI.getFrameRegister(*MF);
29610     unsigned BP = RI.getBaseRegister();
29611     unsigned Op = FPIs64Bit ? X86::MOV64rm : X86::MOV32rm;
29612     addRegOffset(BuildMI(DispatchBB, DL, TII->get(Op), BP), FP, true,
29613                  MFI->getRestoreBasePointerOffset())
29614         .addRegMask(RI.getNoPreservedMask());
29615   } else {
29616     BuildMI(DispatchBB, DL, TII->get(X86::NOOP))
29617         .addRegMask(RI.getNoPreservedMask());
29618   }
29619 
29620   // IReg is used as an index in a memory operand and therefore can't be SP
29621   unsigned IReg = MRI->createVirtualRegister(&X86::GR32_NOSPRegClass);
29622   addFrameReference(BuildMI(DispatchBB, DL, TII->get(X86::MOV32rm), IReg), FI,
29623                     Subtarget.is64Bit() ? 8 : 4);
29624   BuildMI(DispatchBB, DL, TII->get(X86::CMP32ri))
29625       .addReg(IReg)
29626       .addImm(LPadList.size());
29627   BuildMI(DispatchBB, DL, TII->get(X86::JAE_1)).addMBB(TrapBB);
29628 
29629   if (Subtarget.is64Bit()) {
29630     unsigned BReg = MRI->createVirtualRegister(&X86::GR64RegClass);
29631     unsigned IReg64 = MRI->createVirtualRegister(&X86::GR64_NOSPRegClass);
29632 
29633     // leaq .LJTI0_0(%rip), BReg
29634     BuildMI(DispContBB, DL, TII->get(X86::LEA64r), BReg)
29635         .addReg(X86::RIP)
29636         .addImm(1)
29637         .addReg(0)
29638         .addJumpTableIndex(MJTI)
29639         .addReg(0);
29640     // movzx IReg64, IReg
29641     BuildMI(DispContBB, DL, TII->get(TargetOpcode::SUBREG_TO_REG), IReg64)
29642         .addImm(0)
29643         .addReg(IReg)
29644         .addImm(X86::sub_32bit);
29645 
29646     switch (JTE) {
29647     case MachineJumpTableInfo::EK_BlockAddress:
29648       // jmpq *(BReg,IReg64,8)
29649       BuildMI(DispContBB, DL, TII->get(X86::JMP64m))
29650           .addReg(BReg)
29651           .addImm(8)
29652           .addReg(IReg64)
29653           .addImm(0)
29654           .addReg(0);
29655       break;
29656     case MachineJumpTableInfo::EK_LabelDifference32: {
29657       unsigned OReg = MRI->createVirtualRegister(&X86::GR32RegClass);
29658       unsigned OReg64 = MRI->createVirtualRegister(&X86::GR64RegClass);
29659       unsigned TReg = MRI->createVirtualRegister(&X86::GR64RegClass);
29660 
29661       // movl (BReg,IReg64,4), OReg
29662       BuildMI(DispContBB, DL, TII->get(X86::MOV32rm), OReg)
29663           .addReg(BReg)
29664           .addImm(4)
29665           .addReg(IReg64)
29666           .addImm(0)
29667           .addReg(0);
29668       // movsx OReg64, OReg
29669       BuildMI(DispContBB, DL, TII->get(X86::MOVSX64rr32), OReg64).addReg(OReg);
29670       // addq BReg, OReg64, TReg
29671       BuildMI(DispContBB, DL, TII->get(X86::ADD64rr), TReg)
29672           .addReg(OReg64)
29673           .addReg(BReg);
29674       // jmpq *TReg
29675       BuildMI(DispContBB, DL, TII->get(X86::JMP64r)).addReg(TReg);
29676       break;
29677     }
29678     default:
29679       llvm_unreachable("Unexpected jump table encoding");
29680     }
29681   } else {
29682     // jmpl *.LJTI0_0(,IReg,4)
29683     BuildMI(DispContBB, DL, TII->get(X86::JMP32m))
29684         .addReg(0)
29685         .addImm(4)
29686         .addReg(IReg)
29687         .addJumpTableIndex(MJTI)
29688         .addReg(0);
29689   }
29690 
29691   // Add the jump table entries as successors to the MBB.
29692   SmallPtrSet<MachineBasicBlock *, 8> SeenMBBs;
29693   for (auto &LP : LPadList)
29694     if (SeenMBBs.insert(LP).second)
29695       DispContBB->addSuccessor(LP);
29696 
29697   // N.B. the order the invoke BBs are processed in doesn't matter here.
29698   SmallVector<MachineBasicBlock *, 64> MBBLPads;
29699   const MCPhysReg *SavedRegs = MF->getRegInfo().getCalleeSavedRegs();
29700   for (MachineBasicBlock *MBB : InvokeBBs) {
29701     // Remove the landing pad successor from the invoke block and replace it
29702     // with the new dispatch block.
29703     // Keep a copy of Successors since it's modified inside the loop.
29704     SmallVector<MachineBasicBlock *, 8> Successors(MBB->succ_rbegin(),
29705                                                    MBB->succ_rend());
29706     // FIXME: Avoid quadratic complexity.
29707     for (auto MBBS : Successors) {
29708       if (MBBS->isEHPad()) {
29709         MBB->removeSuccessor(MBBS);
29710         MBBLPads.push_back(MBBS);
29711       }
29712     }
29713 
29714     MBB->addSuccessor(DispatchBB);
29715 
29716     // Find the invoke call and mark all of the callee-saved registers as
29717     // 'implicit defined' so that they're spilled.  This prevents code from
29718     // moving instructions to before the EH block, where they will never be
29719     // executed.
29720     for (auto &II : reverse(*MBB)) {
29721       if (!II.isCall())
29722         continue;
29723 
29724       DenseMap<unsigned, bool> DefRegs;
29725       for (auto &MOp : II.operands())
29726         if (MOp.isReg())
29727           DefRegs[MOp.getReg()] = true;
29728 
29729       MachineInstrBuilder MIB(*MF, &II);
29730       for (unsigned RI = 0; SavedRegs[RI]; ++RI) {
29731         unsigned Reg = SavedRegs[RI];
29732         if (!DefRegs[Reg])
29733           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
29734       }
29735 
29736       break;
29737     }
29738   }
29739 
29740   // Mark all former landing pads as non-landing pads.  The dispatch is the only
29741   // landing pad now.
29742   for (auto &LP : MBBLPads)
29743     LP->setIsEHPad(false);
29744 
29745   // The instruction is gone now.
29746   MI.eraseFromParent();
29747   return BB;
29748 }
29749 
29750 MachineBasicBlock *
EmitInstrWithCustomInserter(MachineInstr & MI,MachineBasicBlock * BB) const29751 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
29752                                                MachineBasicBlock *BB) const {
29753   MachineFunction *MF = BB->getParent();
29754   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
29755   DebugLoc DL = MI.getDebugLoc();
29756 
29757   switch (MI.getOpcode()) {
29758   default: llvm_unreachable("Unexpected instr type to insert");
29759   case X86::TLS_addr32:
29760   case X86::TLS_addr64:
29761   case X86::TLS_base_addr32:
29762   case X86::TLS_base_addr64:
29763     return EmitLoweredTLSAddr(MI, BB);
29764   case X86::RETPOLINE_CALL32:
29765   case X86::RETPOLINE_CALL64:
29766   case X86::RETPOLINE_TCRETURN32:
29767   case X86::RETPOLINE_TCRETURN64:
29768     return EmitLoweredRetpoline(MI, BB);
29769   case X86::CATCHRET:
29770     return EmitLoweredCatchRet(MI, BB);
29771   case X86::CATCHPAD:
29772     return EmitLoweredCatchPad(MI, BB);
29773   case X86::SEG_ALLOCA_32:
29774   case X86::SEG_ALLOCA_64:
29775     return EmitLoweredSegAlloca(MI, BB);
29776   case X86::TLSCall_32:
29777   case X86::TLSCall_64:
29778     return EmitLoweredTLSCall(MI, BB);
29779   case X86::CMOV_FR32:
29780   case X86::CMOV_FR64:
29781   case X86::CMOV_GR8:
29782   case X86::CMOV_GR16:
29783   case X86::CMOV_GR32:
29784   case X86::CMOV_RFP32:
29785   case X86::CMOV_RFP64:
29786   case X86::CMOV_RFP80:
29787   case X86::CMOV_VR128:
29788   case X86::CMOV_VR128X:
29789   case X86::CMOV_VR256:
29790   case X86::CMOV_VR256X:
29791   case X86::CMOV_VR512:
29792   case X86::CMOV_VK2:
29793   case X86::CMOV_VK4:
29794   case X86::CMOV_VK8:
29795   case X86::CMOV_VK16:
29796   case X86::CMOV_VK32:
29797   case X86::CMOV_VK64:
29798     return EmitLoweredSelect(MI, BB);
29799 
29800   case X86::RDFLAGS32:
29801   case X86::RDFLAGS64: {
29802     unsigned PushF =
29803         MI.getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
29804     unsigned Pop = MI.getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
29805     MachineInstr *Push = BuildMI(*BB, MI, DL, TII->get(PushF));
29806     // Permit reads of the EFLAGS and DF registers without them being defined.
29807     // This intrinsic exists to read external processor state in flags, such as
29808     // the trap flag, interrupt flag, and direction flag, none of which are
29809     // modeled by the backend.
29810     assert(Push->getOperand(2).getReg() == X86::EFLAGS &&
29811            "Unexpected register in operand!");
29812     Push->getOperand(2).setIsUndef();
29813     assert(Push->getOperand(3).getReg() == X86::DF &&
29814            "Unexpected register in operand!");
29815     Push->getOperand(3).setIsUndef();
29816     BuildMI(*BB, MI, DL, TII->get(Pop), MI.getOperand(0).getReg());
29817 
29818     MI.eraseFromParent(); // The pseudo is gone now.
29819     return BB;
29820   }
29821 
29822   case X86::WRFLAGS32:
29823   case X86::WRFLAGS64: {
29824     unsigned Push =
29825         MI.getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
29826     unsigned PopF =
29827         MI.getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
29828     BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI.getOperand(0).getReg());
29829     BuildMI(*BB, MI, DL, TII->get(PopF));
29830 
29831     MI.eraseFromParent(); // The pseudo is gone now.
29832     return BB;
29833   }
29834 
29835   case X86::RELEASE_FADD32mr:
29836   case X86::RELEASE_FADD64mr:
29837     return EmitLoweredAtomicFP(MI, BB);
29838 
29839   case X86::FP32_TO_INT16_IN_MEM:
29840   case X86::FP32_TO_INT32_IN_MEM:
29841   case X86::FP32_TO_INT64_IN_MEM:
29842   case X86::FP64_TO_INT16_IN_MEM:
29843   case X86::FP64_TO_INT32_IN_MEM:
29844   case X86::FP64_TO_INT64_IN_MEM:
29845   case X86::FP80_TO_INT16_IN_MEM:
29846   case X86::FP80_TO_INT32_IN_MEM:
29847   case X86::FP80_TO_INT64_IN_MEM: {
29848     // Change the floating point control register to use "round towards zero"
29849     // mode when truncating to an integer value.
29850     int CWFrameIdx = MF->getFrameInfo().CreateStackObject(2, 2, false);
29851     addFrameReference(BuildMI(*BB, MI, DL,
29852                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
29853 
29854     // Load the old value of the high byte of the control word...
29855     unsigned OldCW =
29856       MF->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
29857     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
29858                       CWFrameIdx);
29859 
29860     // Set the high part to be round to zero...
29861     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
29862       .addImm(0xC7F);
29863 
29864     // Reload the modified control word now...
29865     addFrameReference(BuildMI(*BB, MI, DL,
29866                               TII->get(X86::FLDCW16m)), CWFrameIdx);
29867 
29868     // Restore the memory image of control word to original value
29869     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
29870       .addReg(OldCW);
29871 
29872     // Get the X86 opcode to use.
29873     unsigned Opc;
29874     switch (MI.getOpcode()) {
29875     default: llvm_unreachable("illegal opcode!");
29876     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
29877     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
29878     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
29879     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
29880     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
29881     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
29882     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
29883     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
29884     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
29885     }
29886 
29887     X86AddressMode AM = getAddressFromInstr(&MI, 0);
29888     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
29889         .addReg(MI.getOperand(X86::AddrNumOperands).getReg());
29890 
29891     // Reload the original control word now.
29892     addFrameReference(BuildMI(*BB, MI, DL,
29893                               TII->get(X86::FLDCW16m)), CWFrameIdx);
29894 
29895     MI.eraseFromParent(); // The pseudo instruction is gone now.
29896     return BB;
29897   }
29898   // Thread synchronization.
29899   case X86::MONITOR:
29900     return emitMonitor(MI, BB, Subtarget, X86::MONITORrrr);
29901   case X86::MONITORX:
29902     return emitMonitor(MI, BB, Subtarget, X86::MONITORXrrr);
29903 
29904   // Cache line zero
29905   case X86::CLZERO:
29906     return emitClzero(&MI, BB, Subtarget);
29907 
29908   // PKU feature
29909   case X86::WRPKRU:
29910     return emitWRPKRU(MI, BB, Subtarget);
29911   case X86::RDPKRU:
29912     return emitRDPKRU(MI, BB, Subtarget);
29913   // xbegin
29914   case X86::XBEGIN:
29915     return emitXBegin(MI, BB, Subtarget.getInstrInfo());
29916 
29917   case X86::VASTART_SAVE_XMM_REGS:
29918     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
29919 
29920   case X86::VAARG_64:
29921     return EmitVAARG64WithCustomInserter(MI, BB);
29922 
29923   case X86::EH_SjLj_SetJmp32:
29924   case X86::EH_SjLj_SetJmp64:
29925     return emitEHSjLjSetJmp(MI, BB);
29926 
29927   case X86::EH_SjLj_LongJmp32:
29928   case X86::EH_SjLj_LongJmp64:
29929     return emitEHSjLjLongJmp(MI, BB);
29930 
29931   case X86::Int_eh_sjlj_setup_dispatch:
29932     return EmitSjLjDispatchBlock(MI, BB);
29933 
29934   case TargetOpcode::STATEPOINT:
29935     // As an implementation detail, STATEPOINT shares the STACKMAP format at
29936     // this point in the process.  We diverge later.
29937     return emitPatchPoint(MI, BB);
29938 
29939   case TargetOpcode::STACKMAP:
29940   case TargetOpcode::PATCHPOINT:
29941     return emitPatchPoint(MI, BB);
29942 
29943   case TargetOpcode::PATCHABLE_EVENT_CALL:
29944     return emitXRayCustomEvent(MI, BB);
29945 
29946   case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
29947     return emitXRayTypedEvent(MI, BB);
29948 
29949   case X86::LCMPXCHG8B: {
29950     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
29951     // In addition to 4 E[ABCD] registers implied by encoding, CMPXCHG8B
29952     // requires a memory operand. If it happens that current architecture is
29953     // i686 and for current function we need a base pointer
29954     // - which is ESI for i686 - register allocator would not be able to
29955     // allocate registers for an address in form of X(%reg, %reg, Y)
29956     // - there never would be enough unreserved registers during regalloc
29957     // (without the need for base ptr the only option would be X(%edi, %esi, Y).
29958     // We are giving a hand to register allocator by precomputing the address in
29959     // a new vreg using LEA.
29960 
29961     // If it is not i686 or there is no base pointer - nothing to do here.
29962     if (!Subtarget.is32Bit() || !TRI->hasBasePointer(*MF))
29963       return BB;
29964 
29965     // Even though this code does not necessarily needs the base pointer to
29966     // be ESI, we check for that. The reason: if this assert fails, there are
29967     // some changes happened in the compiler base pointer handling, which most
29968     // probably have to be addressed somehow here.
29969     assert(TRI->getBaseRegister() == X86::ESI &&
29970            "LCMPXCHG8B custom insertion for i686 is written with X86::ESI as a "
29971            "base pointer in mind");
29972 
29973     MachineRegisterInfo &MRI = MF->getRegInfo();
29974     MVT SPTy = getPointerTy(MF->getDataLayout());
29975     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
29976     unsigned computedAddrVReg = MRI.createVirtualRegister(AddrRegClass);
29977 
29978     X86AddressMode AM = getAddressFromInstr(&MI, 0);
29979     // Regalloc does not need any help when the memory operand of CMPXCHG8B
29980     // does not use index register.
29981     if (AM.IndexReg == X86::NoRegister)
29982       return BB;
29983 
29984     // After X86TargetLowering::ReplaceNodeResults CMPXCHG8B is glued to its
29985     // four operand definitions that are E[ABCD] registers. We skip them and
29986     // then insert the LEA.
29987     MachineBasicBlock::iterator MBBI(MI);
29988     while (MBBI->definesRegister(X86::EAX) || MBBI->definesRegister(X86::EBX) ||
29989            MBBI->definesRegister(X86::ECX) || MBBI->definesRegister(X86::EDX))
29990       --MBBI;
29991     addFullAddress(
29992         BuildMI(*BB, *MBBI, DL, TII->get(X86::LEA32r), computedAddrVReg), AM);
29993 
29994     setDirectAddressInInstr(&MI, 0, computedAddrVReg);
29995 
29996     return BB;
29997   }
29998   case X86::LCMPXCHG16B:
29999     return BB;
30000   case X86::LCMPXCHG8B_SAVE_EBX:
30001   case X86::LCMPXCHG16B_SAVE_RBX: {
30002     unsigned BasePtr =
30003         MI.getOpcode() == X86::LCMPXCHG8B_SAVE_EBX ? X86::EBX : X86::RBX;
30004     if (!BB->isLiveIn(BasePtr))
30005       BB->addLiveIn(BasePtr);
30006     return BB;
30007   }
30008   }
30009 }
30010 
30011 //===----------------------------------------------------------------------===//
30012 //                           X86 Optimization Hooks
30013 //===----------------------------------------------------------------------===//
30014 
30015 bool
targetShrinkDemandedConstant(SDValue Op,const APInt & Demanded,TargetLoweringOpt & TLO) const30016 X86TargetLowering::targetShrinkDemandedConstant(SDValue Op,
30017                                                 const APInt &Demanded,
30018                                                 TargetLoweringOpt &TLO) const {
30019   // Only optimize Ands to prevent shrinking a constant that could be
30020   // matched by movzx.
30021   if (Op.getOpcode() != ISD::AND)
30022     return false;
30023 
30024   EVT VT = Op.getValueType();
30025 
30026   // Ignore vectors.
30027   if (VT.isVector())
30028     return false;
30029 
30030   unsigned Size = VT.getSizeInBits();
30031 
30032   // Make sure the RHS really is a constant.
30033   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
30034   if (!C)
30035     return false;
30036 
30037   const APInt &Mask = C->getAPIntValue();
30038 
30039   // Clear all non-demanded bits initially.
30040   APInt ShrunkMask = Mask & Demanded;
30041 
30042   // Find the width of the shrunk mask.
30043   unsigned Width = ShrunkMask.getActiveBits();
30044 
30045   // If the mask is all 0s there's nothing to do here.
30046   if (Width == 0)
30047     return false;
30048 
30049   // Find the next power of 2 width, rounding up to a byte.
30050   Width = PowerOf2Ceil(std::max(Width, 8U));
30051   // Truncate the width to size to handle illegal types.
30052   Width = std::min(Width, Size);
30053 
30054   // Calculate a possible zero extend mask for this constant.
30055   APInt ZeroExtendMask = APInt::getLowBitsSet(Size, Width);
30056 
30057   // If we aren't changing the mask, just return true to keep it and prevent
30058   // the caller from optimizing.
30059   if (ZeroExtendMask == Mask)
30060     return true;
30061 
30062   // Make sure the new mask can be represented by a combination of mask bits
30063   // and non-demanded bits.
30064   if (!ZeroExtendMask.isSubsetOf(Mask | ~Demanded))
30065     return false;
30066 
30067   // Replace the constant with the zero extend mask.
30068   SDLoc DL(Op);
30069   SDValue NewC = TLO.DAG.getConstant(ZeroExtendMask, DL, VT);
30070   SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
30071   return TLO.CombineTo(Op, NewOp);
30072 }
30073 
computeKnownBitsForTargetNode(const SDValue Op,KnownBits & Known,const APInt & DemandedElts,const SelectionDAG & DAG,unsigned Depth) const30074 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
30075                                                       KnownBits &Known,
30076                                                       const APInt &DemandedElts,
30077                                                       const SelectionDAG &DAG,
30078                                                       unsigned Depth) const {
30079   unsigned BitWidth = Known.getBitWidth();
30080   unsigned Opc = Op.getOpcode();
30081   EVT VT = Op.getValueType();
30082   assert((Opc >= ISD::BUILTIN_OP_END ||
30083           Opc == ISD::INTRINSIC_WO_CHAIN ||
30084           Opc == ISD::INTRINSIC_W_CHAIN ||
30085           Opc == ISD::INTRINSIC_VOID) &&
30086          "Should use MaskedValueIsZero if you don't know whether Op"
30087          " is a target node!");
30088 
30089   Known.resetAll();
30090   switch (Opc) {
30091   default: break;
30092   case X86ISD::SETCC:
30093     Known.Zero.setBitsFrom(1);
30094     break;
30095   case X86ISD::MOVMSK: {
30096     unsigned NumLoBits = Op.getOperand(0).getValueType().getVectorNumElements();
30097     Known.Zero.setBitsFrom(NumLoBits);
30098     break;
30099   }
30100   case X86ISD::PEXTRB:
30101   case X86ISD::PEXTRW: {
30102     SDValue Src = Op.getOperand(0);
30103     EVT SrcVT = Src.getValueType();
30104     APInt DemandedElt = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
30105                                             Op.getConstantOperandVal(1));
30106     Known = DAG.computeKnownBits(Src, DemandedElt, Depth + 1);
30107     Known = Known.zextOrTrunc(BitWidth);
30108     Known.Zero.setBitsFrom(SrcVT.getScalarSizeInBits());
30109     break;
30110   }
30111   case X86ISD::VSRAI:
30112   case X86ISD::VSHLI:
30113   case X86ISD::VSRLI: {
30114     if (auto *ShiftImm = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
30115       if (ShiftImm->getAPIntValue().uge(VT.getScalarSizeInBits())) {
30116         Known.setAllZero();
30117         break;
30118       }
30119 
30120       Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
30121       unsigned ShAmt = ShiftImm->getZExtValue();
30122       if (Opc == X86ISD::VSHLI) {
30123         Known.Zero <<= ShAmt;
30124         Known.One <<= ShAmt;
30125         // Low bits are known zero.
30126         Known.Zero.setLowBits(ShAmt);
30127       } else if (Opc == X86ISD::VSRLI) {
30128         Known.Zero.lshrInPlace(ShAmt);
30129         Known.One.lshrInPlace(ShAmt);
30130         // High bits are known zero.
30131         Known.Zero.setHighBits(ShAmt);
30132       } else {
30133         Known.Zero.ashrInPlace(ShAmt);
30134         Known.One.ashrInPlace(ShAmt);
30135       }
30136     }
30137     break;
30138   }
30139   case X86ISD::PACKUS: {
30140     // PACKUS is just a truncation if the upper half is zero.
30141     APInt DemandedLHS, DemandedRHS;
30142     getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
30143 
30144     Known.One = APInt::getAllOnesValue(BitWidth * 2);
30145     Known.Zero = APInt::getAllOnesValue(BitWidth * 2);
30146 
30147     KnownBits Known2;
30148     if (!!DemandedLHS) {
30149       Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedLHS, Depth + 1);
30150       Known.One &= Known2.One;
30151       Known.Zero &= Known2.Zero;
30152     }
30153     if (!!DemandedRHS) {
30154       Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedRHS, Depth + 1);
30155       Known.One &= Known2.One;
30156       Known.Zero &= Known2.Zero;
30157     }
30158 
30159     if (Known.countMinLeadingZeros() < BitWidth)
30160       Known.resetAll();
30161     Known = Known.trunc(BitWidth);
30162     break;
30163   }
30164   case X86ISD::CMOV: {
30165     Known = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
30166     // If we don't know any bits, early out.
30167     if (Known.isUnknown())
30168       break;
30169     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
30170 
30171     // Only known if known in both the LHS and RHS.
30172     Known.One &= Known2.One;
30173     Known.Zero &= Known2.Zero;
30174     break;
30175   }
30176   }
30177 
30178   // Handle target shuffles.
30179   // TODO - use resolveTargetShuffleInputs once we can limit recursive depth.
30180   if (isTargetShuffle(Opc)) {
30181     bool IsUnary;
30182     SmallVector<int, 64> Mask;
30183     SmallVector<SDValue, 2> Ops;
30184     if (getTargetShuffleMask(Op.getNode(), VT.getSimpleVT(), true, Ops, Mask,
30185                              IsUnary)) {
30186       unsigned NumOps = Ops.size();
30187       unsigned NumElts = VT.getVectorNumElements();
30188       if (Mask.size() == NumElts) {
30189         SmallVector<APInt, 2> DemandedOps(NumOps, APInt(NumElts, 0));
30190         Known.Zero.setAllBits(); Known.One.setAllBits();
30191         for (unsigned i = 0; i != NumElts; ++i) {
30192           if (!DemandedElts[i])
30193             continue;
30194           int M = Mask[i];
30195           if (M == SM_SentinelUndef) {
30196             // For UNDEF elements, we don't know anything about the common state
30197             // of the shuffle result.
30198             Known.resetAll();
30199             break;
30200           } else if (M == SM_SentinelZero) {
30201             Known.One.clearAllBits();
30202             continue;
30203           }
30204           assert(0 <= M && (unsigned)M < (NumOps * NumElts) &&
30205                  "Shuffle index out of range");
30206 
30207           unsigned OpIdx = (unsigned)M / NumElts;
30208           unsigned EltIdx = (unsigned)M % NumElts;
30209           if (Ops[OpIdx].getValueType() != VT) {
30210             // TODO - handle target shuffle ops with different value types.
30211             Known.resetAll();
30212             break;
30213           }
30214           DemandedOps[OpIdx].setBit(EltIdx);
30215         }
30216         // Known bits are the values that are shared by every demanded element.
30217         for (unsigned i = 0; i != NumOps && !Known.isUnknown(); ++i) {
30218           if (!DemandedOps[i])
30219             continue;
30220           KnownBits Known2 =
30221               DAG.computeKnownBits(Ops[i], DemandedOps[i], Depth + 1);
30222           Known.One &= Known2.One;
30223           Known.Zero &= Known2.Zero;
30224         }
30225       }
30226     }
30227   }
30228 }
30229 
ComputeNumSignBitsForTargetNode(SDValue Op,const APInt & DemandedElts,const SelectionDAG & DAG,unsigned Depth) const30230 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
30231     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
30232     unsigned Depth) const {
30233   unsigned VTBits = Op.getScalarValueSizeInBits();
30234   unsigned Opcode = Op.getOpcode();
30235   switch (Opcode) {
30236   case X86ISD::SETCC_CARRY:
30237     // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
30238     return VTBits;
30239 
30240   case X86ISD::VTRUNC: {
30241     // TODO: Add DemandedElts support.
30242     SDValue Src = Op.getOperand(0);
30243     unsigned NumSrcBits = Src.getScalarValueSizeInBits();
30244     assert(VTBits < NumSrcBits && "Illegal truncation input type");
30245     unsigned Tmp = DAG.ComputeNumSignBits(Src, Depth + 1);
30246     if (Tmp > (NumSrcBits - VTBits))
30247       return Tmp - (NumSrcBits - VTBits);
30248     return 1;
30249   }
30250 
30251   case X86ISD::PACKSS: {
30252     // PACKSS is just a truncation if the sign bits extend to the packed size.
30253     APInt DemandedLHS, DemandedRHS;
30254     getPackDemandedElts(Op.getValueType(), DemandedElts, DemandedLHS,
30255                         DemandedRHS);
30256 
30257     unsigned SrcBits = Op.getOperand(0).getScalarValueSizeInBits();
30258     unsigned Tmp0 = SrcBits, Tmp1 = SrcBits;
30259     if (!!DemandedLHS)
30260       Tmp0 = DAG.ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
30261     if (!!DemandedRHS)
30262       Tmp1 = DAG.ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
30263     unsigned Tmp = std::min(Tmp0, Tmp1);
30264     if (Tmp > (SrcBits - VTBits))
30265       return Tmp - (SrcBits - VTBits);
30266     return 1;
30267   }
30268 
30269   case X86ISD::VSHLI: {
30270     SDValue Src = Op.getOperand(0);
30271     APInt ShiftVal = cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue();
30272     if (ShiftVal.uge(VTBits))
30273       return VTBits; // Shifted all bits out --> zero.
30274     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
30275     if (ShiftVal.uge(Tmp))
30276       return 1; // Shifted all sign bits out --> unknown.
30277     return Tmp - ShiftVal.getZExtValue();
30278   }
30279 
30280   case X86ISD::VSRAI: {
30281     SDValue Src = Op.getOperand(0);
30282     APInt ShiftVal = cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue();
30283     if (ShiftVal.uge(VTBits - 1))
30284       return VTBits; // Sign splat.
30285     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
30286     ShiftVal += Tmp;
30287     return ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
30288   }
30289 
30290   case X86ISD::PCMPGT:
30291   case X86ISD::PCMPEQ:
30292   case X86ISD::CMPP:
30293   case X86ISD::VPCOM:
30294   case X86ISD::VPCOMU:
30295     // Vector compares return zero/all-bits result values.
30296     return VTBits;
30297 
30298   case X86ISD::CMOV: {
30299     unsigned Tmp0 = DAG.ComputeNumSignBits(Op.getOperand(0), Depth+1);
30300     if (Tmp0 == 1) return 1;  // Early out.
30301     unsigned Tmp1 = DAG.ComputeNumSignBits(Op.getOperand(1), Depth+1);
30302     return std::min(Tmp0, Tmp1);
30303   }
30304   }
30305 
30306   // Fallback case.
30307   return 1;
30308 }
30309 
unwrapAddress(SDValue N) const30310 SDValue X86TargetLowering::unwrapAddress(SDValue N) const {
30311   if (N->getOpcode() == X86ISD::Wrapper || N->getOpcode() == X86ISD::WrapperRIP)
30312     return N->getOperand(0);
30313   return N;
30314 }
30315 
30316 // Attempt to match a combined shuffle mask against supported unary shuffle
30317 // instructions.
30318 // TODO: Investigate sharing more of this with shuffle lowering.
matchUnaryVectorShuffle(MVT MaskVT,ArrayRef<int> Mask,bool AllowFloatDomain,bool AllowIntDomain,SDValue & V1,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget,unsigned & Shuffle,MVT & SrcVT,MVT & DstVT)30319 static bool matchUnaryVectorShuffle(MVT MaskVT, ArrayRef<int> Mask,
30320                                     bool AllowFloatDomain, bool AllowIntDomain,
30321                                     SDValue &V1, const SDLoc &DL,
30322                                     SelectionDAG &DAG,
30323                                     const X86Subtarget &Subtarget,
30324                                     unsigned &Shuffle, MVT &SrcVT, MVT &DstVT) {
30325   unsigned NumMaskElts = Mask.size();
30326   unsigned MaskEltSize = MaskVT.getScalarSizeInBits();
30327 
30328   // Match against a VZEXT_MOVL vXi32 zero-extending instruction.
30329   if (MaskEltSize == 32 && isUndefOrEqual(Mask[0], 0) &&
30330       isUndefOrZero(Mask[1]) && isUndefInRange(Mask, 2, NumMaskElts - 2)) {
30331     Shuffle = X86ISD::VZEXT_MOVL;
30332     SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
30333     return true;
30334   }
30335 
30336   // Match against a ZERO_EXTEND_VECTOR_INREG/VZEXT instruction.
30337   // TODO: Add 512-bit vector support (split AVX512F and AVX512BW).
30338   if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSE41()) ||
30339                          (MaskVT.is256BitVector() && Subtarget.hasInt256()))) {
30340     unsigned MaxScale = 64 / MaskEltSize;
30341     for (unsigned Scale = 2; Scale <= MaxScale; Scale *= 2) {
30342       bool Match = true;
30343       unsigned NumDstElts = NumMaskElts / Scale;
30344       for (unsigned i = 0; i != NumDstElts && Match; ++i) {
30345         Match &= isUndefOrEqual(Mask[i * Scale], (int)i);
30346         Match &= isUndefOrZeroInRange(Mask, (i * Scale) + 1, Scale - 1);
30347       }
30348       if (Match) {
30349         unsigned SrcSize = std::max(128u, NumDstElts * MaskEltSize);
30350         MVT ScalarTy = MaskVT.isInteger() ? MaskVT.getScalarType() :
30351                                             MVT::getIntegerVT(MaskEltSize);
30352         SrcVT = MVT::getVectorVT(ScalarTy, SrcSize / MaskEltSize);
30353 
30354         if (SrcVT.getSizeInBits() != MaskVT.getSizeInBits())
30355           V1 = extractSubVector(V1, 0, DAG, DL, SrcSize);
30356 
30357         if (SrcVT.getVectorNumElements() == NumDstElts)
30358           Shuffle = unsigned(ISD::ZERO_EXTEND);
30359         else
30360           Shuffle = unsigned(ISD::ZERO_EXTEND_VECTOR_INREG);
30361 
30362         DstVT = MVT::getIntegerVT(Scale * MaskEltSize);
30363         DstVT = MVT::getVectorVT(DstVT, NumDstElts);
30364         return true;
30365       }
30366     }
30367   }
30368 
30369   // Match against a VZEXT_MOVL instruction, SSE1 only supports 32-bits (MOVSS).
30370   if (((MaskEltSize == 32) || (MaskEltSize == 64 && Subtarget.hasSSE2())) &&
30371       isUndefOrEqual(Mask[0], 0) &&
30372       isUndefOrZeroInRange(Mask, 1, NumMaskElts - 1)) {
30373     Shuffle = X86ISD::VZEXT_MOVL;
30374     SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
30375     return true;
30376   }
30377 
30378   // Check if we have SSE3 which will let us use MOVDDUP etc. The
30379   // instructions are no slower than UNPCKLPD but has the option to
30380   // fold the input operand into even an unaligned memory load.
30381   if (MaskVT.is128BitVector() && Subtarget.hasSSE3() && AllowFloatDomain) {
30382     if (!Subtarget.hasAVX2() && isTargetShuffleEquivalent(Mask, {0, 0})) {
30383       Shuffle = X86ISD::MOVDDUP;
30384       SrcVT = DstVT = MVT::v2f64;
30385       return true;
30386     }
30387     if (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2})) {
30388       Shuffle = X86ISD::MOVSLDUP;
30389       SrcVT = DstVT = MVT::v4f32;
30390       return true;
30391     }
30392     if (isTargetShuffleEquivalent(Mask, {1, 1, 3, 3})) {
30393       Shuffle = X86ISD::MOVSHDUP;
30394       SrcVT = DstVT = MVT::v4f32;
30395       return true;
30396     }
30397   }
30398 
30399   if (MaskVT.is256BitVector() && AllowFloatDomain) {
30400     assert(Subtarget.hasAVX() && "AVX required for 256-bit vector shuffles");
30401     if (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2})) {
30402       Shuffle = X86ISD::MOVDDUP;
30403       SrcVT = DstVT = MVT::v4f64;
30404       return true;
30405     }
30406     if (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2, 4, 4, 6, 6})) {
30407       Shuffle = X86ISD::MOVSLDUP;
30408       SrcVT = DstVT = MVT::v8f32;
30409       return true;
30410     }
30411     if (isTargetShuffleEquivalent(Mask, {1, 1, 3, 3, 5, 5, 7, 7})) {
30412       Shuffle = X86ISD::MOVSHDUP;
30413       SrcVT = DstVT = MVT::v8f32;
30414       return true;
30415     }
30416   }
30417 
30418   if (MaskVT.is512BitVector() && AllowFloatDomain) {
30419     assert(Subtarget.hasAVX512() &&
30420            "AVX512 required for 512-bit vector shuffles");
30421     if (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2, 4, 4, 6, 6})) {
30422       Shuffle = X86ISD::MOVDDUP;
30423       SrcVT = DstVT = MVT::v8f64;
30424       return true;
30425     }
30426     if (isTargetShuffleEquivalent(
30427             Mask, {0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14})) {
30428       Shuffle = X86ISD::MOVSLDUP;
30429       SrcVT = DstVT = MVT::v16f32;
30430       return true;
30431     }
30432     if (isTargetShuffleEquivalent(
30433             Mask, {1, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11, 11, 13, 13, 15, 15})) {
30434       Shuffle = X86ISD::MOVSHDUP;
30435       SrcVT = DstVT = MVT::v16f32;
30436       return true;
30437     }
30438   }
30439 
30440   // Attempt to match against broadcast-from-vector.
30441   if (Subtarget.hasAVX2()) {
30442     SmallVector<int, 64> BroadcastMask(NumMaskElts, 0);
30443     if (isTargetShuffleEquivalent(Mask, BroadcastMask)) {
30444       SrcVT = DstVT = MaskVT;
30445       Shuffle = X86ISD::VBROADCAST;
30446       return true;
30447     }
30448   }
30449 
30450   return false;
30451 }
30452 
30453 // Attempt to match a combined shuffle mask against supported unary immediate
30454 // permute instructions.
30455 // TODO: Investigate sharing more of this with shuffle lowering.
matchUnaryPermuteVectorShuffle(MVT MaskVT,ArrayRef<int> Mask,const APInt & Zeroable,bool AllowFloatDomain,bool AllowIntDomain,const X86Subtarget & Subtarget,unsigned & Shuffle,MVT & ShuffleVT,unsigned & PermuteImm)30456 static bool matchUnaryPermuteVectorShuffle(MVT MaskVT, ArrayRef<int> Mask,
30457                                            const APInt &Zeroable,
30458                                            bool AllowFloatDomain,
30459                                            bool AllowIntDomain,
30460                                            const X86Subtarget &Subtarget,
30461                                            unsigned &Shuffle, MVT &ShuffleVT,
30462                                            unsigned &PermuteImm) {
30463   unsigned NumMaskElts = Mask.size();
30464   unsigned InputSizeInBits = MaskVT.getSizeInBits();
30465   unsigned MaskScalarSizeInBits = InputSizeInBits / NumMaskElts;
30466   MVT MaskEltVT = MVT::getIntegerVT(MaskScalarSizeInBits);
30467 
30468   bool ContainsZeros =
30469       llvm::any_of(Mask, [](int M) { return M == SM_SentinelZero; });
30470 
30471   // Handle VPERMI/VPERMILPD vXi64/vXi64 patterns.
30472   if (!ContainsZeros && MaskScalarSizeInBits == 64) {
30473     // Check for lane crossing permutes.
30474     if (is128BitLaneCrossingShuffleMask(MaskEltVT, Mask)) {
30475       // PERMPD/PERMQ permutes within a 256-bit vector (AVX2+).
30476       if (Subtarget.hasAVX2() && MaskVT.is256BitVector()) {
30477         Shuffle = X86ISD::VPERMI;
30478         ShuffleVT = (AllowFloatDomain ? MVT::v4f64 : MVT::v4i64);
30479         PermuteImm = getV4X86ShuffleImm(Mask);
30480         return true;
30481       }
30482       if (Subtarget.hasAVX512() && MaskVT.is512BitVector()) {
30483         SmallVector<int, 4> RepeatedMask;
30484         if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask)) {
30485           Shuffle = X86ISD::VPERMI;
30486           ShuffleVT = (AllowFloatDomain ? MVT::v8f64 : MVT::v8i64);
30487           PermuteImm = getV4X86ShuffleImm(RepeatedMask);
30488           return true;
30489         }
30490       }
30491     } else if (AllowFloatDomain && Subtarget.hasAVX()) {
30492       // VPERMILPD can permute with a non-repeating shuffle.
30493       Shuffle = X86ISD::VPERMILPI;
30494       ShuffleVT = MVT::getVectorVT(MVT::f64, Mask.size());
30495       PermuteImm = 0;
30496       for (int i = 0, e = Mask.size(); i != e; ++i) {
30497         int M = Mask[i];
30498         if (M == SM_SentinelUndef)
30499           continue;
30500         assert(((M / 2) == (i / 2)) && "Out of range shuffle mask index");
30501         PermuteImm |= (M & 1) << i;
30502       }
30503       return true;
30504     }
30505   }
30506 
30507   // Handle PSHUFD/VPERMILPI vXi32/vXf32 repeated patterns.
30508   // AVX introduced the VPERMILPD/VPERMILPS float permutes, before then we
30509   // had to use 2-input SHUFPD/SHUFPS shuffles (not handled here).
30510   if ((MaskScalarSizeInBits == 64 || MaskScalarSizeInBits == 32) &&
30511       !ContainsZeros && (AllowIntDomain || Subtarget.hasAVX())) {
30512     SmallVector<int, 4> RepeatedMask;
30513     if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
30514       // Narrow the repeated mask to create 32-bit element permutes.
30515       SmallVector<int, 4> WordMask = RepeatedMask;
30516       if (MaskScalarSizeInBits == 64)
30517         scaleShuffleMask<int>(2, RepeatedMask, WordMask);
30518 
30519       Shuffle = (AllowIntDomain ? X86ISD::PSHUFD : X86ISD::VPERMILPI);
30520       ShuffleVT = (AllowIntDomain ? MVT::i32 : MVT::f32);
30521       ShuffleVT = MVT::getVectorVT(ShuffleVT, InputSizeInBits / 32);
30522       PermuteImm = getV4X86ShuffleImm(WordMask);
30523       return true;
30524     }
30525   }
30526 
30527   // Handle PSHUFLW/PSHUFHW vXi16 repeated patterns.
30528   if (!ContainsZeros && AllowIntDomain && MaskScalarSizeInBits == 16) {
30529     SmallVector<int, 4> RepeatedMask;
30530     if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
30531       ArrayRef<int> LoMask(Mask.data() + 0, 4);
30532       ArrayRef<int> HiMask(Mask.data() + 4, 4);
30533 
30534       // PSHUFLW: permute lower 4 elements only.
30535       if (isUndefOrInRange(LoMask, 0, 4) &&
30536           isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
30537         Shuffle = X86ISD::PSHUFLW;
30538         ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
30539         PermuteImm = getV4X86ShuffleImm(LoMask);
30540         return true;
30541       }
30542 
30543       // PSHUFHW: permute upper 4 elements only.
30544       if (isUndefOrInRange(HiMask, 4, 8) &&
30545           isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
30546         // Offset the HiMask so that we can create the shuffle immediate.
30547         int OffsetHiMask[4];
30548         for (int i = 0; i != 4; ++i)
30549           OffsetHiMask[i] = (HiMask[i] < 0 ? HiMask[i] : HiMask[i] - 4);
30550 
30551         Shuffle = X86ISD::PSHUFHW;
30552         ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
30553         PermuteImm = getV4X86ShuffleImm(OffsetHiMask);
30554         return true;
30555       }
30556     }
30557   }
30558 
30559   // Attempt to match against byte/bit shifts.
30560   // FIXME: Add 512-bit support.
30561   if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
30562                          (MaskVT.is256BitVector() && Subtarget.hasAVX2()))) {
30563     int ShiftAmt = matchVectorShuffleAsShift(ShuffleVT, Shuffle,
30564                                              MaskScalarSizeInBits, Mask,
30565                                              0, Zeroable, Subtarget);
30566     if (0 < ShiftAmt) {
30567       PermuteImm = (unsigned)ShiftAmt;
30568       return true;
30569     }
30570   }
30571 
30572   return false;
30573 }
30574 
30575 // Attempt to match a combined unary shuffle mask against supported binary
30576 // shuffle instructions.
30577 // TODO: Investigate sharing more of this with shuffle lowering.
matchBinaryVectorShuffle(MVT MaskVT,ArrayRef<int> Mask,bool AllowFloatDomain,bool AllowIntDomain,SDValue & V1,SDValue & V2,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget,unsigned & Shuffle,MVT & SrcVT,MVT & DstVT,bool IsUnary)30578 static bool matchBinaryVectorShuffle(MVT MaskVT, ArrayRef<int> Mask,
30579                                      bool AllowFloatDomain, bool AllowIntDomain,
30580                                      SDValue &V1, SDValue &V2, const SDLoc &DL,
30581                                      SelectionDAG &DAG,
30582                                      const X86Subtarget &Subtarget,
30583                                      unsigned &Shuffle, MVT &SrcVT, MVT &DstVT,
30584                                      bool IsUnary) {
30585   unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
30586 
30587   if (MaskVT.is128BitVector()) {
30588     if (isTargetShuffleEquivalent(Mask, {0, 0}) && AllowFloatDomain) {
30589       V2 = V1;
30590       V1 = (SM_SentinelUndef == Mask[0] ? DAG.getUNDEF(MVT::v4f32) : V1);
30591       Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKL : X86ISD::MOVLHPS;
30592       SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
30593       return true;
30594     }
30595     if (isTargetShuffleEquivalent(Mask, {1, 1}) && AllowFloatDomain) {
30596       V2 = V1;
30597       Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKH : X86ISD::MOVHLPS;
30598       SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
30599       return true;
30600     }
30601     if (isTargetShuffleEquivalent(Mask, {0, 3}) && Subtarget.hasSSE2() &&
30602         (AllowFloatDomain || !Subtarget.hasSSE41())) {
30603       std::swap(V1, V2);
30604       Shuffle = X86ISD::MOVSD;
30605       SrcVT = DstVT = MVT::v2f64;
30606       return true;
30607     }
30608     if (isTargetShuffleEquivalent(Mask, {4, 1, 2, 3}) &&
30609         (AllowFloatDomain || !Subtarget.hasSSE41())) {
30610       Shuffle = X86ISD::MOVSS;
30611       SrcVT = DstVT = MVT::v4f32;
30612       return true;
30613     }
30614   }
30615 
30616   // Attempt to match against either an unary or binary PACKSS/PACKUS shuffle.
30617   if (((MaskVT == MVT::v8i16 || MaskVT == MVT::v16i8) && Subtarget.hasSSE2()) ||
30618       ((MaskVT == MVT::v16i16 || MaskVT == MVT::v32i8) && Subtarget.hasInt256()) ||
30619       ((MaskVT == MVT::v32i16 || MaskVT == MVT::v64i8) && Subtarget.hasBWI())) {
30620     if (matchVectorShuffleWithPACK(MaskVT, SrcVT, V1, V2, Shuffle, Mask, DAG,
30621                                    Subtarget)) {
30622       DstVT = MaskVT;
30623       return true;
30624     }
30625   }
30626 
30627   // Attempt to match against either a unary or binary UNPCKL/UNPCKH shuffle.
30628   if ((MaskVT == MVT::v4f32 && Subtarget.hasSSE1()) ||
30629       (MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
30630       (MaskVT.is256BitVector() && 32 <= EltSizeInBits && Subtarget.hasAVX()) ||
30631       (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
30632       (MaskVT.is512BitVector() && Subtarget.hasAVX512())) {
30633     if (matchVectorShuffleWithUNPCK(MaskVT, V1, V2, Shuffle, IsUnary, Mask, DL,
30634                                     DAG, Subtarget)) {
30635       SrcVT = DstVT = MaskVT;
30636       if (MaskVT.is256BitVector() && !Subtarget.hasAVX2())
30637         SrcVT = DstVT = (32 == EltSizeInBits ? MVT::v8f32 : MVT::v4f64);
30638       return true;
30639     }
30640   }
30641 
30642   return false;
30643 }
30644 
matchBinaryPermuteVectorShuffle(MVT MaskVT,ArrayRef<int> Mask,const APInt & Zeroable,bool AllowFloatDomain,bool AllowIntDomain,SDValue & V1,SDValue & V2,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget,unsigned & Shuffle,MVT & ShuffleVT,unsigned & PermuteImm)30645 static bool matchBinaryPermuteVectorShuffle(
30646     MVT MaskVT, ArrayRef<int> Mask, const APInt &Zeroable,
30647     bool AllowFloatDomain, bool AllowIntDomain, SDValue &V1, SDValue &V2,
30648     const SDLoc &DL, SelectionDAG &DAG, const X86Subtarget &Subtarget,
30649     unsigned &Shuffle, MVT &ShuffleVT, unsigned &PermuteImm) {
30650   unsigned NumMaskElts = Mask.size();
30651   unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
30652 
30653   // Attempt to match against PALIGNR byte rotate.
30654   if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSSE3()) ||
30655                          (MaskVT.is256BitVector() && Subtarget.hasAVX2()))) {
30656     int ByteRotation = matchVectorShuffleAsByteRotate(MaskVT, V1, V2, Mask);
30657     if (0 < ByteRotation) {
30658       Shuffle = X86ISD::PALIGNR;
30659       ShuffleVT = MVT::getVectorVT(MVT::i8, MaskVT.getSizeInBits() / 8);
30660       PermuteImm = ByteRotation;
30661       return true;
30662     }
30663   }
30664 
30665   // Attempt to combine to X86ISD::BLENDI.
30666   if ((NumMaskElts <= 8 && ((Subtarget.hasSSE41() && MaskVT.is128BitVector()) ||
30667                             (Subtarget.hasAVX() && MaskVT.is256BitVector()))) ||
30668       (MaskVT == MVT::v16i16 && Subtarget.hasAVX2())) {
30669     uint64_t BlendMask = 0;
30670     bool ForceV1Zero = false, ForceV2Zero = false;
30671     SmallVector<int, 8> TargetMask(Mask.begin(), Mask.end());
30672     if (matchVectorShuffleAsBlend(V1, V2, TargetMask, ForceV1Zero, ForceV2Zero,
30673                                   BlendMask)) {
30674       if (MaskVT == MVT::v16i16) {
30675         // We can only use v16i16 PBLENDW if the lanes are repeated.
30676         SmallVector<int, 8> RepeatedMask;
30677         if (isRepeatedTargetShuffleMask(128, MaskVT, TargetMask,
30678                                         RepeatedMask)) {
30679           assert(RepeatedMask.size() == 8 &&
30680                  "Repeated mask size doesn't match!");
30681           PermuteImm = 0;
30682           for (int i = 0; i < 8; ++i)
30683             if (RepeatedMask[i] >= 8)
30684               PermuteImm |= 1 << i;
30685           V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
30686           V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
30687           Shuffle = X86ISD::BLENDI;
30688           ShuffleVT = MaskVT;
30689           return true;
30690         }
30691       } else {
30692         // Determine a type compatible with X86ISD::BLENDI.
30693         ShuffleVT = MaskVT;
30694         if (Subtarget.hasAVX2()) {
30695           if (ShuffleVT == MVT::v4i64)
30696             ShuffleVT = MVT::v8i32;
30697           else if (ShuffleVT == MVT::v2i64)
30698             ShuffleVT = MVT::v4i32;
30699         } else {
30700           if (ShuffleVT == MVT::v2i64 || ShuffleVT == MVT::v4i32)
30701             ShuffleVT = MVT::v8i16;
30702           else if (ShuffleVT == MVT::v4i64)
30703             ShuffleVT = MVT::v4f64;
30704           else if (ShuffleVT == MVT::v8i32)
30705             ShuffleVT = MVT::v8f32;
30706         }
30707 
30708         if (!ShuffleVT.isFloatingPoint()) {
30709           int Scale = EltSizeInBits / ShuffleVT.getScalarSizeInBits();
30710           BlendMask =
30711               scaleVectorShuffleBlendMask(BlendMask, NumMaskElts, Scale);
30712           ShuffleVT = MVT::getIntegerVT(EltSizeInBits / Scale);
30713           ShuffleVT = MVT::getVectorVT(ShuffleVT, NumMaskElts * Scale);
30714         }
30715 
30716         V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
30717         V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
30718         PermuteImm = (unsigned)BlendMask;
30719         Shuffle = X86ISD::BLENDI;
30720         return true;
30721       }
30722     }
30723   }
30724 
30725   // Attempt to combine to INSERTPS.
30726   if (AllowFloatDomain && EltSizeInBits == 32 && Subtarget.hasSSE41() &&
30727       MaskVT.is128BitVector()) {
30728     if (Zeroable.getBoolValue() &&
30729         matchVectorShuffleAsInsertPS(V1, V2, PermuteImm, Zeroable, Mask, DAG)) {
30730       Shuffle = X86ISD::INSERTPS;
30731       ShuffleVT = MVT::v4f32;
30732       return true;
30733     }
30734   }
30735 
30736   // Attempt to combine to SHUFPD.
30737   if (AllowFloatDomain && EltSizeInBits == 64 &&
30738       ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
30739        (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
30740        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
30741     if (matchVectorShuffleWithSHUFPD(MaskVT, V1, V2, PermuteImm, Mask)) {
30742       Shuffle = X86ISD::SHUFP;
30743       ShuffleVT = MVT::getVectorVT(MVT::f64, MaskVT.getSizeInBits() / 64);
30744       return true;
30745     }
30746   }
30747 
30748   // Attempt to combine to SHUFPS.
30749   if (AllowFloatDomain && EltSizeInBits == 32 &&
30750       ((MaskVT.is128BitVector() && Subtarget.hasSSE1()) ||
30751        (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
30752        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
30753     SmallVector<int, 4> RepeatedMask;
30754     if (isRepeatedTargetShuffleMask(128, MaskVT, Mask, RepeatedMask)) {
30755       // Match each half of the repeated mask, to determine if its just
30756       // referencing one of the vectors, is zeroable or entirely undef.
30757       auto MatchHalf = [&](unsigned Offset, int &S0, int &S1) {
30758         int M0 = RepeatedMask[Offset];
30759         int M1 = RepeatedMask[Offset + 1];
30760 
30761         if (isUndefInRange(RepeatedMask, Offset, 2)) {
30762           return DAG.getUNDEF(MaskVT);
30763         } else if (isUndefOrZeroInRange(RepeatedMask, Offset, 2)) {
30764           S0 = (SM_SentinelUndef == M0 ? -1 : 0);
30765           S1 = (SM_SentinelUndef == M1 ? -1 : 1);
30766           return getZeroVector(MaskVT, Subtarget, DAG, DL);
30767         } else if (isUndefOrInRange(M0, 0, 4) && isUndefOrInRange(M1, 0, 4)) {
30768           S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
30769           S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
30770           return V1;
30771         } else if (isUndefOrInRange(M0, 4, 8) && isUndefOrInRange(M1, 4, 8)) {
30772           S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
30773           S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
30774           return V2;
30775         }
30776 
30777         return SDValue();
30778       };
30779 
30780       int ShufMask[4] = {-1, -1, -1, -1};
30781       SDValue Lo = MatchHalf(0, ShufMask[0], ShufMask[1]);
30782       SDValue Hi = MatchHalf(2, ShufMask[2], ShufMask[3]);
30783 
30784       if (Lo && Hi) {
30785         V1 = Lo;
30786         V2 = Hi;
30787         Shuffle = X86ISD::SHUFP;
30788         ShuffleVT = MVT::getVectorVT(MVT::f32, MaskVT.getSizeInBits() / 32);
30789         PermuteImm = getV4X86ShuffleImm(ShufMask);
30790         return true;
30791       }
30792     }
30793   }
30794 
30795   return false;
30796 }
30797 
30798 /// Combine an arbitrary chain of shuffles into a single instruction if
30799 /// possible.
30800 ///
30801 /// This is the leaf of the recursive combine below. When we have found some
30802 /// chain of single-use x86 shuffle instructions and accumulated the combined
30803 /// shuffle mask represented by them, this will try to pattern match that mask
30804 /// into either a single instruction if there is a special purpose instruction
30805 /// for this operation, or into a PSHUFB instruction which is a fully general
30806 /// instruction but should only be used to replace chains over a certain depth.
combineX86ShuffleChain(ArrayRef<SDValue> Inputs,SDValue Root,ArrayRef<int> BaseMask,int Depth,bool HasVariableMask,bool AllowVariableMask,SelectionDAG & DAG,const X86Subtarget & Subtarget)30807 static SDValue combineX86ShuffleChain(ArrayRef<SDValue> Inputs, SDValue Root,
30808                                       ArrayRef<int> BaseMask, int Depth,
30809                                       bool HasVariableMask,
30810                                       bool AllowVariableMask, SelectionDAG &DAG,
30811                                       const X86Subtarget &Subtarget) {
30812   assert(!BaseMask.empty() && "Cannot combine an empty shuffle mask!");
30813   assert((Inputs.size() == 1 || Inputs.size() == 2) &&
30814          "Unexpected number of shuffle inputs!");
30815 
30816   // Find the inputs that enter the chain. Note that multiple uses are OK
30817   // here, we're not going to remove the operands we find.
30818   bool UnaryShuffle = (Inputs.size() == 1);
30819   SDValue V1 = peekThroughBitcasts(Inputs[0]);
30820   SDValue V2 = (UnaryShuffle ? DAG.getUNDEF(V1.getValueType())
30821                              : peekThroughBitcasts(Inputs[1]));
30822 
30823   MVT VT1 = V1.getSimpleValueType();
30824   MVT VT2 = V2.getSimpleValueType();
30825   MVT RootVT = Root.getSimpleValueType();
30826   assert(VT1.getSizeInBits() == RootVT.getSizeInBits() &&
30827          VT2.getSizeInBits() == RootVT.getSizeInBits() &&
30828          "Vector size mismatch");
30829 
30830   SDLoc DL(Root);
30831   SDValue Res;
30832 
30833   unsigned NumBaseMaskElts = BaseMask.size();
30834   if (NumBaseMaskElts == 1) {
30835     assert(BaseMask[0] == 0 && "Invalid shuffle index found!");
30836     return DAG.getBitcast(RootVT, V1);
30837   }
30838 
30839   unsigned RootSizeInBits = RootVT.getSizeInBits();
30840   unsigned NumRootElts = RootVT.getVectorNumElements();
30841   unsigned BaseMaskEltSizeInBits = RootSizeInBits / NumBaseMaskElts;
30842   bool FloatDomain = VT1.isFloatingPoint() || VT2.isFloatingPoint() ||
30843                      (RootVT.isFloatingPoint() && Depth >= 2) ||
30844                      (RootVT.is256BitVector() && !Subtarget.hasAVX2());
30845 
30846   // Don't combine if we are a AVX512/EVEX target and the mask element size
30847   // is different from the root element size - this would prevent writemasks
30848   // from being reused.
30849   // TODO - this currently prevents all lane shuffles from occurring.
30850   // TODO - check for writemasks usage instead of always preventing combining.
30851   // TODO - attempt to narrow Mask back to writemask size.
30852   bool IsEVEXShuffle =
30853       RootSizeInBits == 512 || (Subtarget.hasVLX() && RootSizeInBits >= 128);
30854 
30855   // TODO - handle 128/256-bit lane shuffles of 512-bit vectors.
30856 
30857   // Handle 128-bit lane shuffles of 256-bit vectors.
30858   // If we have AVX2, prefer to use VPERMQ/VPERMPD for unary shuffles unless
30859   // we need to use the zeroing feature.
30860   // TODO - this should support binary shuffles.
30861   if (UnaryShuffle && RootVT.is256BitVector() && NumBaseMaskElts == 2 &&
30862       !(Subtarget.hasAVX2() && BaseMask[0] >= -1 && BaseMask[1] >= -1) &&
30863       !isSequentialOrUndefOrZeroInRange(BaseMask, 0, 2, 0)) {
30864     if (Depth == 1 && Root.getOpcode() == X86ISD::VPERM2X128)
30865       return SDValue(); // Nothing to do!
30866     MVT ShuffleVT = (FloatDomain ? MVT::v4f64 : MVT::v4i64);
30867     unsigned PermMask = 0;
30868     PermMask |= ((BaseMask[0] < 0 ? 0x8 : (BaseMask[0] & 1)) << 0);
30869     PermMask |= ((BaseMask[1] < 0 ? 0x8 : (BaseMask[1] & 1)) << 4);
30870 
30871     Res = DAG.getBitcast(ShuffleVT, V1);
30872     Res = DAG.getNode(X86ISD::VPERM2X128, DL, ShuffleVT, Res,
30873                       DAG.getUNDEF(ShuffleVT),
30874                       DAG.getConstant(PermMask, DL, MVT::i8));
30875     return DAG.getBitcast(RootVT, Res);
30876   }
30877 
30878   // For masks that have been widened to 128-bit elements or more,
30879   // narrow back down to 64-bit elements.
30880   SmallVector<int, 64> Mask;
30881   if (BaseMaskEltSizeInBits > 64) {
30882     assert((BaseMaskEltSizeInBits % 64) == 0 && "Illegal mask size");
30883     int MaskScale = BaseMaskEltSizeInBits / 64;
30884     scaleShuffleMask<int>(MaskScale, BaseMask, Mask);
30885   } else {
30886     Mask = SmallVector<int, 64>(BaseMask.begin(), BaseMask.end());
30887   }
30888 
30889   unsigned NumMaskElts = Mask.size();
30890   unsigned MaskEltSizeInBits = RootSizeInBits / NumMaskElts;
30891 
30892   // Determine the effective mask value type.
30893   FloatDomain &= (32 <= MaskEltSizeInBits);
30894   MVT MaskVT = FloatDomain ? MVT::getFloatingPointVT(MaskEltSizeInBits)
30895                            : MVT::getIntegerVT(MaskEltSizeInBits);
30896   MaskVT = MVT::getVectorVT(MaskVT, NumMaskElts);
30897 
30898   // Only allow legal mask types.
30899   if (!DAG.getTargetLoweringInfo().isTypeLegal(MaskVT))
30900     return SDValue();
30901 
30902   // Attempt to match the mask against known shuffle patterns.
30903   MVT ShuffleSrcVT, ShuffleVT;
30904   unsigned Shuffle, PermuteImm;
30905 
30906   // Which shuffle domains are permitted?
30907   // Permit domain crossing at higher combine depths.
30908   bool AllowFloatDomain = FloatDomain || (Depth > 3);
30909   bool AllowIntDomain = (!FloatDomain || (Depth > 3)) && Subtarget.hasSSE2() &&
30910                         (!MaskVT.is256BitVector() || Subtarget.hasAVX2());
30911 
30912   // Determine zeroable mask elements.
30913   APInt Zeroable(NumMaskElts, 0);
30914   for (unsigned i = 0; i != NumMaskElts; ++i)
30915     if (isUndefOrZero(Mask[i]))
30916       Zeroable.setBit(i);
30917 
30918   if (UnaryShuffle) {
30919     // If we are shuffling a X86ISD::VZEXT_LOAD then we can use the load
30920     // directly if we don't shuffle the lower element and we shuffle the upper
30921     // (zero) elements within themselves.
30922     if (V1.getOpcode() == X86ISD::VZEXT_LOAD &&
30923         (V1.getScalarValueSizeInBits() % MaskEltSizeInBits) == 0) {
30924       unsigned Scale = V1.getScalarValueSizeInBits() / MaskEltSizeInBits;
30925       ArrayRef<int> HiMask(Mask.data() + Scale, NumMaskElts - Scale);
30926       if (isSequentialOrUndefInRange(Mask, 0, Scale, 0) &&
30927           isUndefOrZeroOrInRange(HiMask, Scale, NumMaskElts)) {
30928         return DAG.getBitcast(RootVT, V1);
30929       }
30930     }
30931 
30932     SDValue NewV1 = V1; // Save operand in case early exit happens.
30933     if (matchUnaryVectorShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain,
30934                                 NewV1, DL, DAG, Subtarget, Shuffle,
30935                                 ShuffleSrcVT, ShuffleVT) &&
30936         (!IsEVEXShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
30937       if (Depth == 1 && Root.getOpcode() == Shuffle)
30938         return SDValue(); // Nothing to do!
30939       Res = DAG.getBitcast(ShuffleSrcVT, NewV1);
30940       Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res);
30941       return DAG.getBitcast(RootVT, Res);
30942     }
30943 
30944     if (matchUnaryPermuteVectorShuffle(MaskVT, Mask, Zeroable, AllowFloatDomain,
30945                                        AllowIntDomain, Subtarget, Shuffle,
30946                                        ShuffleVT, PermuteImm) &&
30947         (!IsEVEXShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
30948       if (Depth == 1 && Root.getOpcode() == Shuffle)
30949         return SDValue(); // Nothing to do!
30950       Res = DAG.getBitcast(ShuffleVT, V1);
30951       Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res,
30952                         DAG.getConstant(PermuteImm, DL, MVT::i8));
30953       return DAG.getBitcast(RootVT, Res);
30954     }
30955   }
30956 
30957   SDValue NewV1 = V1; // Save operands in case early exit happens.
30958   SDValue NewV2 = V2;
30959   if (matchBinaryVectorShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain,
30960                                NewV1, NewV2, DL, DAG, Subtarget, Shuffle,
30961                                ShuffleSrcVT, ShuffleVT, UnaryShuffle) &&
30962       (!IsEVEXShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
30963     if (Depth == 1 && Root.getOpcode() == Shuffle)
30964       return SDValue(); // Nothing to do!
30965     NewV1 = DAG.getBitcast(ShuffleSrcVT, NewV1);
30966     NewV2 = DAG.getBitcast(ShuffleSrcVT, NewV2);
30967     Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2);
30968     return DAG.getBitcast(RootVT, Res);
30969   }
30970 
30971   NewV1 = V1; // Save operands in case early exit happens.
30972   NewV2 = V2;
30973   if (matchBinaryPermuteVectorShuffle(
30974           MaskVT, Mask, Zeroable, AllowFloatDomain, AllowIntDomain, NewV1,
30975           NewV2, DL, DAG, Subtarget, Shuffle, ShuffleVT, PermuteImm) &&
30976       (!IsEVEXShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
30977     if (Depth == 1 && Root.getOpcode() == Shuffle)
30978       return SDValue(); // Nothing to do!
30979     NewV1 = DAG.getBitcast(ShuffleVT, NewV1);
30980     NewV2 = DAG.getBitcast(ShuffleVT, NewV2);
30981     Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2,
30982                       DAG.getConstant(PermuteImm, DL, MVT::i8));
30983     return DAG.getBitcast(RootVT, Res);
30984   }
30985 
30986   // Typically from here on, we need an integer version of MaskVT.
30987   MVT IntMaskVT = MVT::getIntegerVT(MaskEltSizeInBits);
30988   IntMaskVT = MVT::getVectorVT(IntMaskVT, NumMaskElts);
30989 
30990   // Annoyingly, SSE4A instructions don't map into the above match helpers.
30991   if (Subtarget.hasSSE4A() && AllowIntDomain && RootSizeInBits == 128) {
30992     uint64_t BitLen, BitIdx;
30993     if (matchVectorShuffleAsEXTRQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx,
30994                                   Zeroable)) {
30995       if (Depth == 1 && Root.getOpcode() == X86ISD::EXTRQI)
30996         return SDValue(); // Nothing to do!
30997       V1 = DAG.getBitcast(IntMaskVT, V1);
30998       Res = DAG.getNode(X86ISD::EXTRQI, DL, IntMaskVT, V1,
30999                         DAG.getConstant(BitLen, DL, MVT::i8),
31000                         DAG.getConstant(BitIdx, DL, MVT::i8));
31001       return DAG.getBitcast(RootVT, Res);
31002     }
31003 
31004     if (matchVectorShuffleAsINSERTQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx)) {
31005       if (Depth == 1 && Root.getOpcode() == X86ISD::INSERTQI)
31006         return SDValue(); // Nothing to do!
31007       V1 = DAG.getBitcast(IntMaskVT, V1);
31008       V2 = DAG.getBitcast(IntMaskVT, V2);
31009       Res = DAG.getNode(X86ISD::INSERTQI, DL, IntMaskVT, V1, V2,
31010                         DAG.getConstant(BitLen, DL, MVT::i8),
31011                         DAG.getConstant(BitIdx, DL, MVT::i8));
31012       return DAG.getBitcast(RootVT, Res);
31013     }
31014   }
31015 
31016   // Don't try to re-form single instruction chains under any circumstances now
31017   // that we've done encoding canonicalization for them.
31018   if (Depth < 2)
31019     return SDValue();
31020 
31021   // Depth threshold above which we can efficiently use variable mask shuffles.
31022   int VariableShuffleDepth = Subtarget.hasFastVariableShuffle() ? 2 : 3;
31023   AllowVariableMask &= (Depth >= VariableShuffleDepth) || HasVariableMask;
31024 
31025   bool MaskContainsZeros =
31026       any_of(Mask, [](int M) { return M == SM_SentinelZero; });
31027 
31028   if (is128BitLaneCrossingShuffleMask(MaskVT, Mask)) {
31029     // If we have a single input lane-crossing shuffle then lower to VPERMV.
31030     if (UnaryShuffle && AllowVariableMask && !MaskContainsZeros &&
31031         ((Subtarget.hasAVX2() &&
31032           (MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
31033          (Subtarget.hasAVX512() &&
31034           (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
31035            MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
31036          (Subtarget.hasBWI() && MaskVT == MVT::v32i16) ||
31037          (Subtarget.hasBWI() && Subtarget.hasVLX() && MaskVT == MVT::v16i16) ||
31038          (Subtarget.hasVBMI() && MaskVT == MVT::v64i8) ||
31039          (Subtarget.hasVBMI() && Subtarget.hasVLX() && MaskVT == MVT::v32i8))) {
31040       SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
31041       Res = DAG.getBitcast(MaskVT, V1);
31042       Res = DAG.getNode(X86ISD::VPERMV, DL, MaskVT, VPermMask, Res);
31043       return DAG.getBitcast(RootVT, Res);
31044     }
31045 
31046     // Lower a unary+zero lane-crossing shuffle as VPERMV3 with a zero
31047     // vector as the second source.
31048     if (UnaryShuffle && AllowVariableMask &&
31049         ((Subtarget.hasAVX512() &&
31050           (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
31051            MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
31052          (Subtarget.hasVLX() &&
31053           (MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
31054            MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
31055          (Subtarget.hasBWI() && MaskVT == MVT::v32i16) ||
31056          (Subtarget.hasBWI() && Subtarget.hasVLX() && MaskVT == MVT::v16i16) ||
31057          (Subtarget.hasVBMI() && MaskVT == MVT::v64i8) ||
31058          (Subtarget.hasVBMI() && Subtarget.hasVLX() && MaskVT == MVT::v32i8))) {
31059       // Adjust shuffle mask - replace SM_SentinelZero with second source index.
31060       for (unsigned i = 0; i != NumMaskElts; ++i)
31061         if (Mask[i] == SM_SentinelZero)
31062           Mask[i] = NumMaskElts + i;
31063 
31064       SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
31065       Res = DAG.getBitcast(MaskVT, V1);
31066       SDValue Zero = getZeroVector(MaskVT, Subtarget, DAG, DL);
31067       Res = DAG.getNode(X86ISD::VPERMV3, DL, MaskVT, Res, VPermMask, Zero);
31068       return DAG.getBitcast(RootVT, Res);
31069     }
31070 
31071     // If we have a dual input lane-crossing shuffle then lower to VPERMV3.
31072     if (AllowVariableMask && !MaskContainsZeros &&
31073         ((Subtarget.hasAVX512() &&
31074           (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
31075            MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
31076          (Subtarget.hasVLX() &&
31077           (MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
31078            MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
31079          (Subtarget.hasBWI() && MaskVT == MVT::v32i16) ||
31080          (Subtarget.hasBWI() && Subtarget.hasVLX() && MaskVT == MVT::v16i16) ||
31081          (Subtarget.hasVBMI() && MaskVT == MVT::v64i8) ||
31082          (Subtarget.hasVBMI() && Subtarget.hasVLX() && MaskVT == MVT::v32i8))) {
31083       SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
31084       V1 = DAG.getBitcast(MaskVT, V1);
31085       V2 = DAG.getBitcast(MaskVT, V2);
31086       Res = DAG.getNode(X86ISD::VPERMV3, DL, MaskVT, V1, VPermMask, V2);
31087       return DAG.getBitcast(RootVT, Res);
31088     }
31089     return SDValue();
31090   }
31091 
31092   // See if we can combine a single input shuffle with zeros to a bit-mask,
31093   // which is much simpler than any shuffle.
31094   if (UnaryShuffle && MaskContainsZeros && AllowVariableMask &&
31095       isSequentialOrUndefOrZeroInRange(Mask, 0, NumMaskElts, 0) &&
31096       DAG.getTargetLoweringInfo().isTypeLegal(MaskVT)) {
31097     APInt Zero = APInt::getNullValue(MaskEltSizeInBits);
31098     APInt AllOnes = APInt::getAllOnesValue(MaskEltSizeInBits);
31099     APInt UndefElts(NumMaskElts, 0);
31100     SmallVector<APInt, 64> EltBits(NumMaskElts, Zero);
31101     for (unsigned i = 0; i != NumMaskElts; ++i) {
31102       int M = Mask[i];
31103       if (M == SM_SentinelUndef) {
31104         UndefElts.setBit(i);
31105         continue;
31106       }
31107       if (M == SM_SentinelZero)
31108         continue;
31109       EltBits[i] = AllOnes;
31110     }
31111     SDValue BitMask = getConstVector(EltBits, UndefElts, MaskVT, DAG, DL);
31112     Res = DAG.getBitcast(MaskVT, V1);
31113     unsigned AndOpcode =
31114         FloatDomain ? unsigned(X86ISD::FAND) : unsigned(ISD::AND);
31115     Res = DAG.getNode(AndOpcode, DL, MaskVT, Res, BitMask);
31116     return DAG.getBitcast(RootVT, Res);
31117   }
31118 
31119   // If we have a single input shuffle with different shuffle patterns in the
31120   // the 128-bit lanes use the variable mask to VPERMILPS.
31121   // TODO Combine other mask types at higher depths.
31122   if (UnaryShuffle && AllowVariableMask && !MaskContainsZeros &&
31123       ((MaskVT == MVT::v8f32 && Subtarget.hasAVX()) ||
31124        (MaskVT == MVT::v16f32 && Subtarget.hasAVX512()))) {
31125     SmallVector<SDValue, 16> VPermIdx;
31126     for (int M : Mask) {
31127       SDValue Idx =
31128           M < 0 ? DAG.getUNDEF(MVT::i32) : DAG.getConstant(M % 4, DL, MVT::i32);
31129       VPermIdx.push_back(Idx);
31130     }
31131     SDValue VPermMask = DAG.getBuildVector(IntMaskVT, DL, VPermIdx);
31132     Res = DAG.getBitcast(MaskVT, V1);
31133     Res = DAG.getNode(X86ISD::VPERMILPV, DL, MaskVT, Res, VPermMask);
31134     return DAG.getBitcast(RootVT, Res);
31135   }
31136 
31137   // With XOP, binary shuffles of 128/256-bit floating point vectors can combine
31138   // to VPERMIL2PD/VPERMIL2PS.
31139   if (AllowVariableMask && Subtarget.hasXOP() &&
31140       (MaskVT == MVT::v2f64 || MaskVT == MVT::v4f64 || MaskVT == MVT::v4f32 ||
31141        MaskVT == MVT::v8f32)) {
31142     // VPERMIL2 Operation.
31143     // Bits[3] - Match Bit.
31144     // Bits[2:1] - (Per Lane) PD Shuffle Mask.
31145     // Bits[2:0] - (Per Lane) PS Shuffle Mask.
31146     unsigned NumLanes = MaskVT.getSizeInBits() / 128;
31147     unsigned NumEltsPerLane = NumMaskElts / NumLanes;
31148     SmallVector<int, 8> VPerm2Idx;
31149     unsigned M2ZImm = 0;
31150     for (int M : Mask) {
31151       if (M == SM_SentinelUndef) {
31152         VPerm2Idx.push_back(-1);
31153         continue;
31154       }
31155       if (M == SM_SentinelZero) {
31156         M2ZImm = 2;
31157         VPerm2Idx.push_back(8);
31158         continue;
31159       }
31160       int Index = (M % NumEltsPerLane) + ((M / NumMaskElts) * NumEltsPerLane);
31161       Index = (MaskVT.getScalarSizeInBits() == 64 ? Index << 1 : Index);
31162       VPerm2Idx.push_back(Index);
31163     }
31164     V1 = DAG.getBitcast(MaskVT, V1);
31165     V2 = DAG.getBitcast(MaskVT, V2);
31166     SDValue VPerm2MaskOp = getConstVector(VPerm2Idx, IntMaskVT, DAG, DL, true);
31167     Res = DAG.getNode(X86ISD::VPERMIL2, DL, MaskVT, V1, V2, VPerm2MaskOp,
31168                       DAG.getConstant(M2ZImm, DL, MVT::i8));
31169     return DAG.getBitcast(RootVT, Res);
31170   }
31171 
31172   // If we have 3 or more shuffle instructions or a chain involving a variable
31173   // mask, we can replace them with a single PSHUFB instruction profitably.
31174   // Intel's manuals suggest only using PSHUFB if doing so replacing 5
31175   // instructions, but in practice PSHUFB tends to be *very* fast so we're
31176   // more aggressive.
31177   if (UnaryShuffle && AllowVariableMask &&
31178       ((RootVT.is128BitVector() && Subtarget.hasSSSE3()) ||
31179        (RootVT.is256BitVector() && Subtarget.hasAVX2()) ||
31180        (RootVT.is512BitVector() && Subtarget.hasBWI()))) {
31181     SmallVector<SDValue, 16> PSHUFBMask;
31182     int NumBytes = RootVT.getSizeInBits() / 8;
31183     int Ratio = NumBytes / NumMaskElts;
31184     for (int i = 0; i < NumBytes; ++i) {
31185       int M = Mask[i / Ratio];
31186       if (M == SM_SentinelUndef) {
31187         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
31188         continue;
31189       }
31190       if (M == SM_SentinelZero) {
31191         PSHUFBMask.push_back(DAG.getConstant(255, DL, MVT::i8));
31192         continue;
31193       }
31194       M = Ratio * M + i % Ratio;
31195       assert((M / 16) == (i / 16) && "Lane crossing detected");
31196       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
31197     }
31198     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
31199     Res = DAG.getBitcast(ByteVT, V1);
31200     SDValue PSHUFBMaskOp = DAG.getBuildVector(ByteVT, DL, PSHUFBMask);
31201     Res = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Res, PSHUFBMaskOp);
31202     return DAG.getBitcast(RootVT, Res);
31203   }
31204 
31205   // With XOP, if we have a 128-bit binary input shuffle we can always combine
31206   // to VPPERM. We match the depth requirement of PSHUFB - VPPERM is never
31207   // slower than PSHUFB on targets that support both.
31208   if (AllowVariableMask && RootVT.is128BitVector() && Subtarget.hasXOP()) {
31209     // VPPERM Mask Operation
31210     // Bits[4:0] - Byte Index (0 - 31)
31211     // Bits[7:5] - Permute Operation (0 - Source byte, 4 - ZERO)
31212     SmallVector<SDValue, 16> VPPERMMask;
31213     int NumBytes = 16;
31214     int Ratio = NumBytes / NumMaskElts;
31215     for (int i = 0; i < NumBytes; ++i) {
31216       int M = Mask[i / Ratio];
31217       if (M == SM_SentinelUndef) {
31218         VPPERMMask.push_back(DAG.getUNDEF(MVT::i8));
31219         continue;
31220       }
31221       if (M == SM_SentinelZero) {
31222         VPPERMMask.push_back(DAG.getConstant(128, DL, MVT::i8));
31223         continue;
31224       }
31225       M = Ratio * M + i % Ratio;
31226       VPPERMMask.push_back(DAG.getConstant(M, DL, MVT::i8));
31227     }
31228     MVT ByteVT = MVT::v16i8;
31229     V1 = DAG.getBitcast(ByteVT, V1);
31230     V2 = DAG.getBitcast(ByteVT, V2);
31231     SDValue VPPERMMaskOp = DAG.getBuildVector(ByteVT, DL, VPPERMMask);
31232     Res = DAG.getNode(X86ISD::VPPERM, DL, ByteVT, V1, V2, VPPERMMaskOp);
31233     return DAG.getBitcast(RootVT, Res);
31234   }
31235 
31236   // Failed to find any combines.
31237   return SDValue();
31238 }
31239 
31240 // Attempt to constant fold all of the constant source ops.
31241 // Returns true if the entire shuffle is folded to a constant.
31242 // TODO: Extend this to merge multiple constant Ops and update the mask.
combineX86ShufflesConstants(ArrayRef<SDValue> Ops,ArrayRef<int> Mask,SDValue Root,bool HasVariableMask,SelectionDAG & DAG,const X86Subtarget & Subtarget)31243 static SDValue combineX86ShufflesConstants(ArrayRef<SDValue> Ops,
31244                                            ArrayRef<int> Mask, SDValue Root,
31245                                            bool HasVariableMask,
31246                                            SelectionDAG &DAG,
31247                                            const X86Subtarget &Subtarget) {
31248   MVT VT = Root.getSimpleValueType();
31249 
31250   unsigned SizeInBits = VT.getSizeInBits();
31251   unsigned NumMaskElts = Mask.size();
31252   unsigned MaskSizeInBits = SizeInBits / NumMaskElts;
31253   unsigned NumOps = Ops.size();
31254 
31255   // Extract constant bits from each source op.
31256   bool OneUseConstantOp = false;
31257   SmallVector<APInt, 16> UndefEltsOps(NumOps);
31258   SmallVector<SmallVector<APInt, 16>, 16> RawBitsOps(NumOps);
31259   for (unsigned i = 0; i != NumOps; ++i) {
31260     SDValue SrcOp = Ops[i];
31261     OneUseConstantOp |= SrcOp.hasOneUse();
31262     if (!getTargetConstantBitsFromNode(SrcOp, MaskSizeInBits, UndefEltsOps[i],
31263                                        RawBitsOps[i]))
31264       return SDValue();
31265   }
31266 
31267   // Only fold if at least one of the constants is only used once or
31268   // the combined shuffle has included a variable mask shuffle, this
31269   // is to avoid constant pool bloat.
31270   if (!OneUseConstantOp && !HasVariableMask)
31271     return SDValue();
31272 
31273   // Shuffle the constant bits according to the mask.
31274   APInt UndefElts(NumMaskElts, 0);
31275   APInt ZeroElts(NumMaskElts, 0);
31276   APInt ConstantElts(NumMaskElts, 0);
31277   SmallVector<APInt, 8> ConstantBitData(NumMaskElts,
31278                                         APInt::getNullValue(MaskSizeInBits));
31279   for (unsigned i = 0; i != NumMaskElts; ++i) {
31280     int M = Mask[i];
31281     if (M == SM_SentinelUndef) {
31282       UndefElts.setBit(i);
31283       continue;
31284     } else if (M == SM_SentinelZero) {
31285       ZeroElts.setBit(i);
31286       continue;
31287     }
31288     assert(0 <= M && M < (int)(NumMaskElts * NumOps));
31289 
31290     unsigned SrcOpIdx = (unsigned)M / NumMaskElts;
31291     unsigned SrcMaskIdx = (unsigned)M % NumMaskElts;
31292 
31293     auto &SrcUndefElts = UndefEltsOps[SrcOpIdx];
31294     if (SrcUndefElts[SrcMaskIdx]) {
31295       UndefElts.setBit(i);
31296       continue;
31297     }
31298 
31299     auto &SrcEltBits = RawBitsOps[SrcOpIdx];
31300     APInt &Bits = SrcEltBits[SrcMaskIdx];
31301     if (!Bits) {
31302       ZeroElts.setBit(i);
31303       continue;
31304     }
31305 
31306     ConstantElts.setBit(i);
31307     ConstantBitData[i] = Bits;
31308   }
31309   assert((UndefElts | ZeroElts | ConstantElts).isAllOnesValue());
31310 
31311   // Create the constant data.
31312   MVT MaskSVT;
31313   if (VT.isFloatingPoint() && (MaskSizeInBits == 32 || MaskSizeInBits == 64))
31314     MaskSVT = MVT::getFloatingPointVT(MaskSizeInBits);
31315   else
31316     MaskSVT = MVT::getIntegerVT(MaskSizeInBits);
31317 
31318   MVT MaskVT = MVT::getVectorVT(MaskSVT, NumMaskElts);
31319 
31320   SDLoc DL(Root);
31321   SDValue CstOp = getConstVector(ConstantBitData, UndefElts, MaskVT, DAG, DL);
31322   return DAG.getBitcast(VT, CstOp);
31323 }
31324 
31325 /// Fully generic combining of x86 shuffle instructions.
31326 ///
31327 /// This should be the last combine run over the x86 shuffle instructions. Once
31328 /// they have been fully optimized, this will recursively consider all chains
31329 /// of single-use shuffle instructions, build a generic model of the cumulative
31330 /// shuffle operation, and check for simpler instructions which implement this
31331 /// operation. We use this primarily for two purposes:
31332 ///
31333 /// 1) Collapse generic shuffles to specialized single instructions when
31334 ///    equivalent. In most cases, this is just an encoding size win, but
31335 ///    sometimes we will collapse multiple generic shuffles into a single
31336 ///    special-purpose shuffle.
31337 /// 2) Look for sequences of shuffle instructions with 3 or more total
31338 ///    instructions, and replace them with the slightly more expensive SSSE3
31339 ///    PSHUFB instruction if available. We do this as the last combining step
31340 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
31341 ///    a suitable short sequence of other instructions. The PSHUFB will either
31342 ///    use a register or have to read from memory and so is slightly (but only
31343 ///    slightly) more expensive than the other shuffle instructions.
31344 ///
31345 /// Because this is inherently a quadratic operation (for each shuffle in
31346 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
31347 /// This should never be an issue in practice as the shuffle lowering doesn't
31348 /// produce sequences of more than 8 instructions.
31349 ///
31350 /// FIXME: We will currently miss some cases where the redundant shuffling
31351 /// would simplify under the threshold for PSHUFB formation because of
31352 /// combine-ordering. To fix this, we should do the redundant instruction
31353 /// combining in this recursive walk.
combineX86ShufflesRecursively(ArrayRef<SDValue> SrcOps,int SrcOpIndex,SDValue Root,ArrayRef<int> RootMask,ArrayRef<const SDNode * > SrcNodes,unsigned Depth,bool HasVariableMask,bool AllowVariableMask,SelectionDAG & DAG,const X86Subtarget & Subtarget)31354 static SDValue combineX86ShufflesRecursively(
31355     ArrayRef<SDValue> SrcOps, int SrcOpIndex, SDValue Root,
31356     ArrayRef<int> RootMask, ArrayRef<const SDNode *> SrcNodes, unsigned Depth,
31357     bool HasVariableMask, bool AllowVariableMask, SelectionDAG &DAG,
31358     const X86Subtarget &Subtarget) {
31359   // Bound the depth of our recursive combine because this is ultimately
31360   // quadratic in nature.
31361   const unsigned MaxRecursionDepth = 8;
31362   if (Depth > MaxRecursionDepth)
31363     return SDValue();
31364 
31365   // Directly rip through bitcasts to find the underlying operand.
31366   SDValue Op = SrcOps[SrcOpIndex];
31367   Op = peekThroughOneUseBitcasts(Op);
31368 
31369   MVT VT = Op.getSimpleValueType();
31370   if (!VT.isVector())
31371     return SDValue(); // Bail if we hit a non-vector.
31372 
31373   assert(Root.getSimpleValueType().isVector() &&
31374          "Shuffles operate on vector types!");
31375   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
31376          "Can only combine shuffles of the same vector register size.");
31377 
31378   // Extract target shuffle mask and resolve sentinels and inputs.
31379   SmallVector<int, 64> OpMask;
31380   SmallVector<SDValue, 2> OpInputs;
31381   if (!resolveTargetShuffleInputs(Op, OpInputs, OpMask, DAG))
31382     return SDValue();
31383 
31384   // TODO - Add support for more than 2 inputs.
31385   if (2 < OpInputs.size())
31386     return SDValue();
31387 
31388   SDValue Input0 = (OpInputs.size() > 0 ? OpInputs[0] : SDValue());
31389   SDValue Input1 = (OpInputs.size() > 1 ? OpInputs[1] : SDValue());
31390 
31391   // Add the inputs to the Ops list, avoiding duplicates.
31392   SmallVector<SDValue, 16> Ops(SrcOps.begin(), SrcOps.end());
31393 
31394   auto AddOp = [&Ops](SDValue Input, int InsertionPoint) -> int {
31395     if (!Input)
31396       return -1;
31397     // Attempt to find an existing match.
31398     SDValue InputBC = peekThroughBitcasts(Input);
31399     for (int i = 0, e = Ops.size(); i < e; ++i)
31400       if (InputBC == peekThroughBitcasts(Ops[i]))
31401         return i;
31402     // Match failed - should we replace an existing Op?
31403     if (InsertionPoint >= 0) {
31404       Ops[InsertionPoint] = Input;
31405       return InsertionPoint;
31406     }
31407     // Add to the end of the Ops list.
31408     Ops.push_back(Input);
31409     return Ops.size() - 1;
31410   };
31411 
31412   int InputIdx0 = AddOp(Input0, SrcOpIndex);
31413   int InputIdx1 = AddOp(Input1, -1);
31414 
31415   assert(((RootMask.size() > OpMask.size() &&
31416            RootMask.size() % OpMask.size() == 0) ||
31417           (OpMask.size() > RootMask.size() &&
31418            OpMask.size() % RootMask.size() == 0) ||
31419           OpMask.size() == RootMask.size()) &&
31420          "The smaller number of elements must divide the larger.");
31421 
31422   // This function can be performance-critical, so we rely on the power-of-2
31423   // knowledge that we have about the mask sizes to replace div/rem ops with
31424   // bit-masks and shifts.
31425   assert(isPowerOf2_32(RootMask.size()) && "Non-power-of-2 shuffle mask sizes");
31426   assert(isPowerOf2_32(OpMask.size()) && "Non-power-of-2 shuffle mask sizes");
31427   unsigned RootMaskSizeLog2 = countTrailingZeros(RootMask.size());
31428   unsigned OpMaskSizeLog2 = countTrailingZeros(OpMask.size());
31429 
31430   unsigned MaskWidth = std::max<unsigned>(OpMask.size(), RootMask.size());
31431   unsigned RootRatio = std::max<unsigned>(1, OpMask.size() >> RootMaskSizeLog2);
31432   unsigned OpRatio = std::max<unsigned>(1, RootMask.size() >> OpMaskSizeLog2);
31433   assert((RootRatio == 1 || OpRatio == 1) &&
31434          "Must not have a ratio for both incoming and op masks!");
31435 
31436   assert(isPowerOf2_32(MaskWidth) && "Non-power-of-2 shuffle mask sizes");
31437   assert(isPowerOf2_32(RootRatio) && "Non-power-of-2 shuffle mask sizes");
31438   assert(isPowerOf2_32(OpRatio) && "Non-power-of-2 shuffle mask sizes");
31439   unsigned RootRatioLog2 = countTrailingZeros(RootRatio);
31440   unsigned OpRatioLog2 = countTrailingZeros(OpRatio);
31441 
31442   SmallVector<int, 64> Mask(MaskWidth, SM_SentinelUndef);
31443 
31444   // Merge this shuffle operation's mask into our accumulated mask. Note that
31445   // this shuffle's mask will be the first applied to the input, followed by the
31446   // root mask to get us all the way to the root value arrangement. The reason
31447   // for this order is that we are recursing up the operation chain.
31448   for (unsigned i = 0; i < MaskWidth; ++i) {
31449     unsigned RootIdx = i >> RootRatioLog2;
31450     if (RootMask[RootIdx] < 0) {
31451       // This is a zero or undef lane, we're done.
31452       Mask[i] = RootMask[RootIdx];
31453       continue;
31454     }
31455 
31456     unsigned RootMaskedIdx =
31457         RootRatio == 1
31458             ? RootMask[RootIdx]
31459             : (RootMask[RootIdx] << RootRatioLog2) + (i & (RootRatio - 1));
31460 
31461     // Just insert the scaled root mask value if it references an input other
31462     // than the SrcOp we're currently inserting.
31463     if ((RootMaskedIdx < (SrcOpIndex * MaskWidth)) ||
31464         (((SrcOpIndex + 1) * MaskWidth) <= RootMaskedIdx)) {
31465       Mask[i] = RootMaskedIdx;
31466       continue;
31467     }
31468 
31469     RootMaskedIdx = RootMaskedIdx & (MaskWidth - 1);
31470     unsigned OpIdx = RootMaskedIdx >> OpRatioLog2;
31471     if (OpMask[OpIdx] < 0) {
31472       // The incoming lanes are zero or undef, it doesn't matter which ones we
31473       // are using.
31474       Mask[i] = OpMask[OpIdx];
31475       continue;
31476     }
31477 
31478     // Ok, we have non-zero lanes, map them through to one of the Op's inputs.
31479     unsigned OpMaskedIdx =
31480         OpRatio == 1
31481             ? OpMask[OpIdx]
31482             : (OpMask[OpIdx] << OpRatioLog2) + (RootMaskedIdx & (OpRatio - 1));
31483 
31484     OpMaskedIdx = OpMaskedIdx & (MaskWidth - 1);
31485     if (OpMask[OpIdx] < (int)OpMask.size()) {
31486       assert(0 <= InputIdx0 && "Unknown target shuffle input");
31487       OpMaskedIdx += InputIdx0 * MaskWidth;
31488     } else {
31489       assert(0 <= InputIdx1 && "Unknown target shuffle input");
31490       OpMaskedIdx += InputIdx1 * MaskWidth;
31491     }
31492 
31493     Mask[i] = OpMaskedIdx;
31494   }
31495 
31496   // Handle the all undef/zero cases early.
31497   if (all_of(Mask, [](int Idx) { return Idx == SM_SentinelUndef; }))
31498     return DAG.getUNDEF(Root.getValueType());
31499 
31500   // TODO - should we handle the mixed zero/undef case as well? Just returning
31501   // a zero mask will lose information on undef elements possibly reducing
31502   // future combine possibilities.
31503   if (all_of(Mask, [](int Idx) { return Idx < 0; }))
31504     return getZeroVector(Root.getSimpleValueType(), Subtarget, DAG,
31505                          SDLoc(Root));
31506 
31507   // Remove unused shuffle source ops.
31508   resolveTargetShuffleInputsAndMask(Ops, Mask);
31509   assert(!Ops.empty() && "Shuffle with no inputs detected");
31510 
31511   HasVariableMask |= isTargetShuffleVariableMask(Op.getOpcode());
31512 
31513   // Update the list of shuffle nodes that have been combined so far.
31514   SmallVector<const SDNode *, 16> CombinedNodes(SrcNodes.begin(),
31515                                                 SrcNodes.end());
31516   CombinedNodes.push_back(Op.getNode());
31517 
31518   // See if we can recurse into each shuffle source op (if it's a target
31519   // shuffle). The source op should only be generally combined if it either has
31520   // a single use (i.e. current Op) or all its users have already been combined,
31521   // if not then we can still combine but should prevent generation of variable
31522   // shuffles to avoid constant pool bloat.
31523   // Don't recurse if we already have more source ops than we can combine in
31524   // the remaining recursion depth.
31525   if (Ops.size() < (MaxRecursionDepth - Depth)) {
31526     for (int i = 0, e = Ops.size(); i < e; ++i) {
31527       bool AllowVar = false;
31528       if (Ops[i].getNode()->hasOneUse() ||
31529           SDNode::areOnlyUsersOf(CombinedNodes, Ops[i].getNode()))
31530         AllowVar = AllowVariableMask;
31531       if (SDValue Res = combineX86ShufflesRecursively(
31532               Ops, i, Root, Mask, CombinedNodes, Depth + 1, HasVariableMask,
31533               AllowVar, DAG, Subtarget))
31534         return Res;
31535     }
31536   }
31537 
31538   // Attempt to constant fold all of the constant source ops.
31539   if (SDValue Cst = combineX86ShufflesConstants(
31540           Ops, Mask, Root, HasVariableMask, DAG, Subtarget))
31541     return Cst;
31542 
31543   // We can only combine unary and binary shuffle mask cases.
31544   if (Ops.size() > 2)
31545     return SDValue();
31546 
31547   // Minor canonicalization of the accumulated shuffle mask to make it easier
31548   // to match below. All this does is detect masks with sequential pairs of
31549   // elements, and shrink them to the half-width mask. It does this in a loop
31550   // so it will reduce the size of the mask to the minimal width mask which
31551   // performs an equivalent shuffle.
31552   SmallVector<int, 64> WidenedMask;
31553   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
31554     Mask = std::move(WidenedMask);
31555   }
31556 
31557   // Canonicalization of binary shuffle masks to improve pattern matching by
31558   // commuting the inputs.
31559   if (Ops.size() == 2 && canonicalizeShuffleMaskWithCommute(Mask)) {
31560     ShuffleVectorSDNode::commuteMask(Mask);
31561     std::swap(Ops[0], Ops[1]);
31562   }
31563 
31564   // Finally, try to combine into a single shuffle instruction.
31565   return combineX86ShuffleChain(Ops, Root, Mask, Depth, HasVariableMask,
31566                                 AllowVariableMask, DAG, Subtarget);
31567 }
31568 
31569 /// Get the PSHUF-style mask from PSHUF node.
31570 ///
31571 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
31572 /// PSHUF-style masks that can be reused with such instructions.
getPSHUFShuffleMask(SDValue N)31573 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
31574   MVT VT = N.getSimpleValueType();
31575   SmallVector<int, 4> Mask;
31576   SmallVector<SDValue, 2> Ops;
31577   bool IsUnary;
31578   bool HaveMask =
31579       getTargetShuffleMask(N.getNode(), VT, false, Ops, Mask, IsUnary);
31580   (void)HaveMask;
31581   assert(HaveMask);
31582 
31583   // If we have more than 128-bits, only the low 128-bits of shuffle mask
31584   // matter. Check that the upper masks are repeats and remove them.
31585   if (VT.getSizeInBits() > 128) {
31586     int LaneElts = 128 / VT.getScalarSizeInBits();
31587 #ifndef NDEBUG
31588     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
31589       for (int j = 0; j < LaneElts; ++j)
31590         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
31591                "Mask doesn't repeat in high 128-bit lanes!");
31592 #endif
31593     Mask.resize(LaneElts);
31594   }
31595 
31596   switch (N.getOpcode()) {
31597   case X86ISD::PSHUFD:
31598     return Mask;
31599   case X86ISD::PSHUFLW:
31600     Mask.resize(4);
31601     return Mask;
31602   case X86ISD::PSHUFHW:
31603     Mask.erase(Mask.begin(), Mask.begin() + 4);
31604     for (int &M : Mask)
31605       M -= 4;
31606     return Mask;
31607   default:
31608     llvm_unreachable("No valid shuffle instruction found!");
31609   }
31610 }
31611 
31612 /// Search for a combinable shuffle across a chain ending in pshufd.
31613 ///
31614 /// We walk up the chain and look for a combinable shuffle, skipping over
31615 /// shuffles that we could hoist this shuffle's transformation past without
31616 /// altering anything.
31617 static SDValue
combineRedundantDWordShuffle(SDValue N,MutableArrayRef<int> Mask,SelectionDAG & DAG)31618 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
31619                              SelectionDAG &DAG) {
31620   assert(N.getOpcode() == X86ISD::PSHUFD &&
31621          "Called with something other than an x86 128-bit half shuffle!");
31622   SDLoc DL(N);
31623 
31624   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
31625   // of the shuffles in the chain so that we can form a fresh chain to replace
31626   // this one.
31627   SmallVector<SDValue, 8> Chain;
31628   SDValue V = N.getOperand(0);
31629   for (; V.hasOneUse(); V = V.getOperand(0)) {
31630     switch (V.getOpcode()) {
31631     default:
31632       return SDValue(); // Nothing combined!
31633 
31634     case ISD::BITCAST:
31635       // Skip bitcasts as we always know the type for the target specific
31636       // instructions.
31637       continue;
31638 
31639     case X86ISD::PSHUFD:
31640       // Found another dword shuffle.
31641       break;
31642 
31643     case X86ISD::PSHUFLW:
31644       // Check that the low words (being shuffled) are the identity in the
31645       // dword shuffle, and the high words are self-contained.
31646       if (Mask[0] != 0 || Mask[1] != 1 ||
31647           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
31648         return SDValue();
31649 
31650       Chain.push_back(V);
31651       continue;
31652 
31653     case X86ISD::PSHUFHW:
31654       // Check that the high words (being shuffled) are the identity in the
31655       // dword shuffle, and the low words are self-contained.
31656       if (Mask[2] != 2 || Mask[3] != 3 ||
31657           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
31658         return SDValue();
31659 
31660       Chain.push_back(V);
31661       continue;
31662 
31663     case X86ISD::UNPCKL:
31664     case X86ISD::UNPCKH:
31665       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
31666       // shuffle into a preceding word shuffle.
31667       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
31668           V.getSimpleValueType().getVectorElementType() != MVT::i16)
31669         return SDValue();
31670 
31671       // Search for a half-shuffle which we can combine with.
31672       unsigned CombineOp =
31673           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
31674       if (V.getOperand(0) != V.getOperand(1) ||
31675           !V->isOnlyUserOf(V.getOperand(0).getNode()))
31676         return SDValue();
31677       Chain.push_back(V);
31678       V = V.getOperand(0);
31679       do {
31680         switch (V.getOpcode()) {
31681         default:
31682           return SDValue(); // Nothing to combine.
31683 
31684         case X86ISD::PSHUFLW:
31685         case X86ISD::PSHUFHW:
31686           if (V.getOpcode() == CombineOp)
31687             break;
31688 
31689           Chain.push_back(V);
31690 
31691           LLVM_FALLTHROUGH;
31692         case ISD::BITCAST:
31693           V = V.getOperand(0);
31694           continue;
31695         }
31696         break;
31697       } while (V.hasOneUse());
31698       break;
31699     }
31700     // Break out of the loop if we break out of the switch.
31701     break;
31702   }
31703 
31704   if (!V.hasOneUse())
31705     // We fell out of the loop without finding a viable combining instruction.
31706     return SDValue();
31707 
31708   // Merge this node's mask and our incoming mask.
31709   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
31710   for (int &M : Mask)
31711     M = VMask[M];
31712   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
31713                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
31714 
31715   // Rebuild the chain around this new shuffle.
31716   while (!Chain.empty()) {
31717     SDValue W = Chain.pop_back_val();
31718 
31719     if (V.getValueType() != W.getOperand(0).getValueType())
31720       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
31721 
31722     switch (W.getOpcode()) {
31723     default:
31724       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
31725 
31726     case X86ISD::UNPCKL:
31727     case X86ISD::UNPCKH:
31728       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
31729       break;
31730 
31731     case X86ISD::PSHUFD:
31732     case X86ISD::PSHUFLW:
31733     case X86ISD::PSHUFHW:
31734       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
31735       break;
31736     }
31737   }
31738   if (V.getValueType() != N.getValueType())
31739     V = DAG.getBitcast(N.getValueType(), V);
31740 
31741   // Return the new chain to replace N.
31742   return V;
31743 }
31744 
31745 /// Try to combine x86 target specific shuffles.
combineTargetShuffle(SDValue N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)31746 static SDValue combineTargetShuffle(SDValue N, SelectionDAG &DAG,
31747                                     TargetLowering::DAGCombinerInfo &DCI,
31748                                     const X86Subtarget &Subtarget) {
31749   SDLoc DL(N);
31750   MVT VT = N.getSimpleValueType();
31751   SmallVector<int, 4> Mask;
31752   unsigned Opcode = N.getOpcode();
31753 
31754   // Combine binary shuffle of 2 similar 'Horizontal' instructions into a
31755   // single instruction.
31756   if (VT.getScalarSizeInBits() == 64 &&
31757       (Opcode == X86ISD::MOVSD || Opcode == X86ISD::UNPCKH ||
31758        Opcode == X86ISD::UNPCKL)) {
31759     auto BC0 = peekThroughBitcasts(N.getOperand(0));
31760     auto BC1 = peekThroughBitcasts(N.getOperand(1));
31761     EVT VT0 = BC0.getValueType();
31762     EVT VT1 = BC1.getValueType();
31763     unsigned Opcode0 = BC0.getOpcode();
31764     unsigned Opcode1 = BC1.getOpcode();
31765     if (Opcode0 == Opcode1 && VT0 == VT1 &&
31766         (Opcode0 == X86ISD::FHADD || Opcode0 == X86ISD::HADD ||
31767          Opcode0 == X86ISD::FHSUB || Opcode0 == X86ISD::HSUB ||
31768          Opcode0 == X86ISD::PACKSS || Opcode0 == X86ISD::PACKUS)) {
31769       SDValue Lo, Hi;
31770       if (Opcode == X86ISD::MOVSD) {
31771         Lo = BC1.getOperand(0);
31772         Hi = BC0.getOperand(1);
31773       } else {
31774         Lo = BC0.getOperand(Opcode == X86ISD::UNPCKH ? 1 : 0);
31775         Hi = BC1.getOperand(Opcode == X86ISD::UNPCKH ? 1 : 0);
31776       }
31777       SDValue Horiz = DAG.getNode(Opcode0, DL, VT0, Lo, Hi);
31778       return DAG.getBitcast(VT, Horiz);
31779     }
31780   }
31781 
31782   switch (Opcode) {
31783   case X86ISD::VBROADCAST: {
31784     // If broadcasting from another shuffle, attempt to simplify it.
31785     // TODO - we really need a general SimplifyDemandedVectorElts mechanism.
31786     SDValue Src = N.getOperand(0);
31787     SDValue BC = peekThroughBitcasts(Src);
31788     EVT SrcVT = Src.getValueType();
31789     EVT BCVT = BC.getValueType();
31790     if (isTargetShuffle(BC.getOpcode()) &&
31791         VT.getScalarSizeInBits() % BCVT.getScalarSizeInBits() == 0) {
31792       unsigned Scale = VT.getScalarSizeInBits() / BCVT.getScalarSizeInBits();
31793       SmallVector<int, 16> DemandedMask(BCVT.getVectorNumElements(),
31794                                         SM_SentinelUndef);
31795       for (unsigned i = 0; i != Scale; ++i)
31796         DemandedMask[i] = i;
31797       if (SDValue Res = combineX86ShufflesRecursively(
31798               {BC}, 0, BC, DemandedMask, {}, /*Depth*/ 1,
31799               /*HasVarMask*/ false, /*AllowVarMask*/ true, DAG, Subtarget))
31800         return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
31801                            DAG.getBitcast(SrcVT, Res));
31802     }
31803     return SDValue();
31804   }
31805   case X86ISD::PSHUFD:
31806   case X86ISD::PSHUFLW:
31807   case X86ISD::PSHUFHW:
31808     Mask = getPSHUFShuffleMask(N);
31809     assert(Mask.size() == 4);
31810     break;
31811   case X86ISD::MOVSD:
31812   case X86ISD::MOVSS: {
31813     SDValue N0 = N.getOperand(0);
31814     SDValue N1 = N.getOperand(1);
31815 
31816     // Canonicalize scalar FPOps:
31817     // MOVS*(N0, OP(N0, N1)) --> MOVS*(N0, SCALAR_TO_VECTOR(OP(N0[0], N1[0])))
31818     // If commutable, allow OP(N1[0], N0[0]).
31819     unsigned Opcode1 = N1.getOpcode();
31820     if (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL || Opcode1 == ISD::FSUB ||
31821         Opcode1 == ISD::FDIV) {
31822       SDValue N10 = N1.getOperand(0);
31823       SDValue N11 = N1.getOperand(1);
31824       if (N10 == N0 ||
31825           (N11 == N0 && (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL))) {
31826         if (N10 != N0)
31827           std::swap(N10, N11);
31828         MVT SVT = VT.getVectorElementType();
31829         SDValue ZeroIdx = DAG.getIntPtrConstant(0, DL);
31830         N10 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N10, ZeroIdx);
31831         N11 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N11, ZeroIdx);
31832         SDValue Scl = DAG.getNode(Opcode1, DL, SVT, N10, N11);
31833         SDValue SclVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
31834         return DAG.getNode(Opcode, DL, VT, N0, SclVec);
31835       }
31836     }
31837 
31838     return SDValue();
31839   }
31840   case X86ISD::INSERTPS: {
31841     assert(VT == MVT::v4f32 && "INSERTPS ValueType must be MVT::v4f32");
31842     SDValue Op0 = N.getOperand(0);
31843     SDValue Op1 = N.getOperand(1);
31844     SDValue Op2 = N.getOperand(2);
31845     unsigned InsertPSMask = cast<ConstantSDNode>(Op2)->getZExtValue();
31846     unsigned SrcIdx = (InsertPSMask >> 6) & 0x3;
31847     unsigned DstIdx = (InsertPSMask >> 4) & 0x3;
31848     unsigned ZeroMask = InsertPSMask & 0xF;
31849 
31850     // If we zero out all elements from Op0 then we don't need to reference it.
31851     if (((ZeroMask | (1u << DstIdx)) == 0xF) && !Op0.isUndef())
31852       return DAG.getNode(X86ISD::INSERTPS, DL, VT, DAG.getUNDEF(VT), Op1,
31853                          DAG.getConstant(InsertPSMask, DL, MVT::i8));
31854 
31855     // If we zero out the element from Op1 then we don't need to reference it.
31856     if ((ZeroMask & (1u << DstIdx)) && !Op1.isUndef())
31857       return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
31858                          DAG.getConstant(InsertPSMask, DL, MVT::i8));
31859 
31860     // Attempt to merge insertps Op1 with an inner target shuffle node.
31861     SmallVector<int, 8> TargetMask1;
31862     SmallVector<SDValue, 2> Ops1;
31863     if (setTargetShuffleZeroElements(Op1, TargetMask1, Ops1)) {
31864       int M = TargetMask1[SrcIdx];
31865       if (isUndefOrZero(M)) {
31866         // Zero/UNDEF insertion - zero out element and remove dependency.
31867         InsertPSMask |= (1u << DstIdx);
31868         return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
31869                            DAG.getConstant(InsertPSMask, DL, MVT::i8));
31870       }
31871       // Update insertps mask srcidx and reference the source input directly.
31872       assert(0 <= M && M < 8 && "Shuffle index out of range");
31873       InsertPSMask = (InsertPSMask & 0x3f) | ((M & 0x3) << 6);
31874       Op1 = Ops1[M < 4 ? 0 : 1];
31875       return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
31876                          DAG.getConstant(InsertPSMask, DL, MVT::i8));
31877     }
31878 
31879     // Attempt to merge insertps Op0 with an inner target shuffle node.
31880     SmallVector<int, 8> TargetMask0;
31881     SmallVector<SDValue, 2> Ops0;
31882     if (!setTargetShuffleZeroElements(Op0, TargetMask0, Ops0))
31883       return SDValue();
31884 
31885     bool Updated = false;
31886     bool UseInput00 = false;
31887     bool UseInput01 = false;
31888     for (int i = 0; i != 4; ++i) {
31889       int M = TargetMask0[i];
31890       if ((InsertPSMask & (1u << i)) || (i == (int)DstIdx)) {
31891         // No change if element is already zero or the inserted element.
31892         continue;
31893       } else if (isUndefOrZero(M)) {
31894         // If the target mask is undef/zero then we must zero the element.
31895         InsertPSMask |= (1u << i);
31896         Updated = true;
31897         continue;
31898       }
31899 
31900       // The input vector element must be inline.
31901       if (M != i && M != (i + 4))
31902         return SDValue();
31903 
31904       // Determine which inputs of the target shuffle we're using.
31905       UseInput00 |= (0 <= M && M < 4);
31906       UseInput01 |= (4 <= M);
31907     }
31908 
31909     // If we're not using both inputs of the target shuffle then use the
31910     // referenced input directly.
31911     if (UseInput00 && !UseInput01) {
31912       Updated = true;
31913       Op0 = Ops0[0];
31914     } else if (!UseInput00 && UseInput01) {
31915       Updated = true;
31916       Op0 = Ops0[1];
31917     }
31918 
31919     if (Updated)
31920       return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
31921                          DAG.getConstant(InsertPSMask, DL, MVT::i8));
31922 
31923     return SDValue();
31924   }
31925   default:
31926     return SDValue();
31927   }
31928 
31929   // Nuke no-op shuffles that show up after combining.
31930   if (isNoopShuffleMask(Mask))
31931     return N.getOperand(0);
31932 
31933   // Look for simplifications involving one or two shuffle instructions.
31934   SDValue V = N.getOperand(0);
31935   switch (N.getOpcode()) {
31936   default:
31937     break;
31938   case X86ISD::PSHUFLW:
31939   case X86ISD::PSHUFHW:
31940     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
31941 
31942     // See if this reduces to a PSHUFD which is no more expensive and can
31943     // combine with more operations. Note that it has to at least flip the
31944     // dwords as otherwise it would have been removed as a no-op.
31945     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
31946       int DMask[] = {0, 1, 2, 3};
31947       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
31948       DMask[DOffset + 0] = DOffset + 1;
31949       DMask[DOffset + 1] = DOffset + 0;
31950       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
31951       V = DAG.getBitcast(DVT, V);
31952       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
31953                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
31954       return DAG.getBitcast(VT, V);
31955     }
31956 
31957     // Look for shuffle patterns which can be implemented as a single unpack.
31958     // FIXME: This doesn't handle the location of the PSHUFD generically, and
31959     // only works when we have a PSHUFD followed by two half-shuffles.
31960     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
31961         (V.getOpcode() == X86ISD::PSHUFLW ||
31962          V.getOpcode() == X86ISD::PSHUFHW) &&
31963         V.getOpcode() != N.getOpcode() &&
31964         V.hasOneUse()) {
31965       SDValue D = peekThroughOneUseBitcasts(V.getOperand(0));
31966       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
31967         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
31968         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
31969         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
31970         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
31971         int WordMask[8];
31972         for (int i = 0; i < 4; ++i) {
31973           WordMask[i + NOffset] = Mask[i] + NOffset;
31974           WordMask[i + VOffset] = VMask[i] + VOffset;
31975         }
31976         // Map the word mask through the DWord mask.
31977         int MappedMask[8];
31978         for (int i = 0; i < 8; ++i)
31979           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
31980         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
31981             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
31982           // We can replace all three shuffles with an unpack.
31983           V = DAG.getBitcast(VT, D.getOperand(0));
31984           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
31985                                                 : X86ISD::UNPCKH,
31986                              DL, VT, V, V);
31987         }
31988       }
31989     }
31990 
31991     break;
31992 
31993   case X86ISD::PSHUFD:
31994     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG))
31995       return NewN;
31996 
31997     break;
31998   }
31999 
32000   return SDValue();
32001 }
32002 
32003 /// Checks if the shuffle mask takes subsequent elements
32004 /// alternately from two vectors.
32005 /// For example <0, 5, 2, 7> or <8, 1, 10, 3, 12, 5, 14, 7> are both correct.
isAddSubOrSubAddMask(ArrayRef<int> Mask,bool & Op0Even)32006 static bool isAddSubOrSubAddMask(ArrayRef<int> Mask, bool &Op0Even) {
32007 
32008   int ParitySrc[2] = {-1, -1};
32009   unsigned Size = Mask.size();
32010   for (unsigned i = 0; i != Size; ++i) {
32011     int M = Mask[i];
32012     if (M < 0)
32013       continue;
32014 
32015     // Make sure we are using the matching element from the input.
32016     if ((M % Size) != i)
32017       return false;
32018 
32019     // Make sure we use the same input for all elements of the same parity.
32020     int Src = M / Size;
32021     if (ParitySrc[i % 2] >= 0 && ParitySrc[i % 2] != Src)
32022       return false;
32023     ParitySrc[i % 2] = Src;
32024   }
32025 
32026   // Make sure each input is used.
32027   if (ParitySrc[0] < 0 || ParitySrc[1] < 0 || ParitySrc[0] == ParitySrc[1])
32028     return false;
32029 
32030   Op0Even = ParitySrc[0] == 0;
32031   return true;
32032 }
32033 
32034 /// Returns true iff the shuffle node \p N can be replaced with ADDSUB(SUBADD)
32035 /// operation. If true is returned then the operands of ADDSUB(SUBADD) operation
32036 /// are written to the parameters \p Opnd0 and \p Opnd1.
32037 ///
32038 /// We combine shuffle to ADDSUB(SUBADD) directly on the abstract vector shuffle nodes
32039 /// so it is easier to generically match. We also insert dummy vector shuffle
32040 /// nodes for the operands which explicitly discard the lanes which are unused
32041 /// by this operation to try to flow through the rest of the combiner
32042 /// the fact that they're unused.
isAddSubOrSubAdd(SDNode * N,const X86Subtarget & Subtarget,SelectionDAG & DAG,SDValue & Opnd0,SDValue & Opnd1,bool & IsSubAdd)32043 static bool isAddSubOrSubAdd(SDNode *N, const X86Subtarget &Subtarget,
32044                              SelectionDAG &DAG, SDValue &Opnd0, SDValue &Opnd1,
32045                              bool &IsSubAdd) {
32046 
32047   EVT VT = N->getValueType(0);
32048   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
32049   if (!Subtarget.hasSSE3() || !TLI.isTypeLegal(VT) ||
32050       !VT.getSimpleVT().isFloatingPoint())
32051     return false;
32052 
32053   // We only handle target-independent shuffles.
32054   // FIXME: It would be easy and harmless to use the target shuffle mask
32055   // extraction tool to support more.
32056   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
32057     return false;
32058 
32059   SDValue V1 = N->getOperand(0);
32060   SDValue V2 = N->getOperand(1);
32061 
32062   // Make sure we have an FADD and an FSUB.
32063   if ((V1.getOpcode() != ISD::FADD && V1.getOpcode() != ISD::FSUB) ||
32064       (V2.getOpcode() != ISD::FADD && V2.getOpcode() != ISD::FSUB) ||
32065       V1.getOpcode() == V2.getOpcode())
32066     return false;
32067 
32068   // If there are other uses of these operations we can't fold them.
32069   if (!V1->hasOneUse() || !V2->hasOneUse())
32070     return false;
32071 
32072   // Ensure that both operations have the same operands. Note that we can
32073   // commute the FADD operands.
32074   SDValue LHS, RHS;
32075   if (V1.getOpcode() == ISD::FSUB) {
32076     LHS = V1->getOperand(0); RHS = V1->getOperand(1);
32077     if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
32078         (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
32079       return false;
32080   } else {
32081     assert(V2.getOpcode() == ISD::FSUB && "Unexpected opcode");
32082     LHS = V2->getOperand(0); RHS = V2->getOperand(1);
32083     if ((V1->getOperand(0) != LHS || V1->getOperand(1) != RHS) &&
32084         (V1->getOperand(0) != RHS || V1->getOperand(1) != LHS))
32085       return false;
32086   }
32087 
32088   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
32089   bool Op0Even;
32090   if (!isAddSubOrSubAddMask(Mask, Op0Even))
32091     return false;
32092 
32093   // It's a subadd if the vector in the even parity is an FADD.
32094   IsSubAdd = Op0Even ? V1->getOpcode() == ISD::FADD
32095                      : V2->getOpcode() == ISD::FADD;
32096 
32097   Opnd0 = LHS;
32098   Opnd1 = RHS;
32099   return true;
32100 }
32101 
32102 /// Combine shuffle of two fma nodes into FMAddSub or FMSubAdd.
combineShuffleToFMAddSub(SDNode * N,const X86Subtarget & Subtarget,SelectionDAG & DAG)32103 static SDValue combineShuffleToFMAddSub(SDNode *N,
32104                                         const X86Subtarget &Subtarget,
32105                                         SelectionDAG &DAG) {
32106   // We only handle target-independent shuffles.
32107   // FIXME: It would be easy and harmless to use the target shuffle mask
32108   // extraction tool to support more.
32109   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
32110     return SDValue();
32111 
32112   MVT VT = N->getSimpleValueType(0);
32113   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
32114   if (!Subtarget.hasAnyFMA() || !TLI.isTypeLegal(VT))
32115     return SDValue();
32116 
32117   // We're trying to match (shuffle fma(a, b, c), X86Fmsub(a, b, c).
32118   SDValue Op0 = N->getOperand(0);
32119   SDValue Op1 = N->getOperand(1);
32120   SDValue FMAdd = Op0, FMSub = Op1;
32121   if (FMSub.getOpcode() != X86ISD::FMSUB)
32122     std::swap(FMAdd, FMSub);
32123 
32124   if (FMAdd.getOpcode() != ISD::FMA || FMSub.getOpcode() != X86ISD::FMSUB ||
32125       FMAdd.getOperand(0) != FMSub.getOperand(0) || !FMAdd.hasOneUse() ||
32126       FMAdd.getOperand(1) != FMSub.getOperand(1) || !FMSub.hasOneUse() ||
32127       FMAdd.getOperand(2) != FMSub.getOperand(2))
32128     return SDValue();
32129 
32130   // Check for correct shuffle mask.
32131   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
32132   bool Op0Even;
32133   if (!isAddSubOrSubAddMask(Mask, Op0Even))
32134     return SDValue();
32135 
32136   // FMAddSub takes zeroth operand from FMSub node.
32137   SDLoc DL(N);
32138   bool IsSubAdd = Op0Even ? Op0 == FMAdd : Op1 == FMAdd;
32139   unsigned Opcode = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
32140   return DAG.getNode(Opcode, DL, VT, FMAdd.getOperand(0), FMAdd.getOperand(1),
32141                      FMAdd.getOperand(2));
32142 }
32143 
32144 /// Try to combine a shuffle into a target-specific add-sub or
32145 /// mul-add-sub node.
combineShuffleToAddSubOrFMAddSub(SDNode * N,const X86Subtarget & Subtarget,SelectionDAG & DAG)32146 static SDValue combineShuffleToAddSubOrFMAddSub(SDNode *N,
32147                                                 const X86Subtarget &Subtarget,
32148                                                 SelectionDAG &DAG) {
32149   if (SDValue V = combineShuffleToFMAddSub(N, Subtarget, DAG))
32150     return V;
32151 
32152   SDValue Opnd0, Opnd1;
32153   bool IsSubAdd;
32154   if (!isAddSubOrSubAdd(N, Subtarget, DAG, Opnd0, Opnd1, IsSubAdd))
32155     return SDValue();
32156 
32157   MVT VT = N->getSimpleValueType(0);
32158   SDLoc DL(N);
32159 
32160   // Try to generate X86ISD::FMADDSUB node here.
32161   SDValue Opnd2;
32162   if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, 2)) {
32163     unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
32164     return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
32165   }
32166 
32167   if (IsSubAdd)
32168     return SDValue();
32169 
32170   // Do not generate X86ISD::ADDSUB node for 512-bit types even though
32171   // the ADDSUB idiom has been successfully recognized. There are no known
32172   // X86 targets with 512-bit ADDSUB instructions!
32173   if (VT.is512BitVector())
32174     return SDValue();
32175 
32176   return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
32177 }
32178 
32179 // We are looking for a shuffle where both sources are concatenated with undef
32180 // and have a width that is half of the output's width. AVX2 has VPERMD/Q, so
32181 // if we can express this as a single-source shuffle, that's preferable.
combineShuffleOfConcatUndef(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)32182 static SDValue combineShuffleOfConcatUndef(SDNode *N, SelectionDAG &DAG,
32183                                            const X86Subtarget &Subtarget) {
32184   if (!Subtarget.hasAVX2() || !isa<ShuffleVectorSDNode>(N))
32185     return SDValue();
32186 
32187   EVT VT = N->getValueType(0);
32188 
32189   // We only care about shuffles of 128/256-bit vectors of 32/64-bit values.
32190   if (!VT.is128BitVector() && !VT.is256BitVector())
32191     return SDValue();
32192 
32193   if (VT.getVectorElementType() != MVT::i32 &&
32194       VT.getVectorElementType() != MVT::i64 &&
32195       VT.getVectorElementType() != MVT::f32 &&
32196       VT.getVectorElementType() != MVT::f64)
32197     return SDValue();
32198 
32199   SDValue N0 = N->getOperand(0);
32200   SDValue N1 = N->getOperand(1);
32201 
32202   // Check that both sources are concats with undef.
32203   if (N0.getOpcode() != ISD::CONCAT_VECTORS ||
32204       N1.getOpcode() != ISD::CONCAT_VECTORS || N0.getNumOperands() != 2 ||
32205       N1.getNumOperands() != 2 || !N0.getOperand(1).isUndef() ||
32206       !N1.getOperand(1).isUndef())
32207     return SDValue();
32208 
32209   // Construct the new shuffle mask. Elements from the first source retain their
32210   // index, but elements from the second source no longer need to skip an undef.
32211   SmallVector<int, 8> Mask;
32212   int NumElts = VT.getVectorNumElements();
32213 
32214   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
32215   for (int Elt : SVOp->getMask())
32216     Mask.push_back(Elt < NumElts ? Elt : (Elt - NumElts / 2));
32217 
32218   SDLoc DL(N);
32219   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, N0.getOperand(0),
32220                                N1.getOperand(0));
32221   return DAG.getVectorShuffle(VT, DL, Concat, DAG.getUNDEF(VT), Mask);
32222 }
32223 
32224 /// Eliminate a redundant shuffle of a horizontal math op.
foldShuffleOfHorizOp(SDNode * N)32225 static SDValue foldShuffleOfHorizOp(SDNode *N) {
32226   if (N->getOpcode() != ISD::VECTOR_SHUFFLE || !N->getOperand(1).isUndef())
32227     return SDValue();
32228 
32229   SDValue HOp = N->getOperand(0);
32230   if (HOp.getOpcode() != X86ISD::HADD && HOp.getOpcode() != X86ISD::FHADD &&
32231       HOp.getOpcode() != X86ISD::HSUB && HOp.getOpcode() != X86ISD::FHSUB)
32232     return SDValue();
32233 
32234   // 128-bit horizontal math instructions are defined to operate on adjacent
32235   // lanes of each operand as:
32236   // v4X32: A[0] + A[1] , A[2] + A[3] , B[0] + B[1] , B[2] + B[3]
32237   // ...similarly for v2f64 and v8i16.
32238   // TODO: Handle UNDEF operands.
32239   if (HOp.getOperand(0) != HOp.getOperand(1))
32240     return SDValue();
32241 
32242   // When the operands of a horizontal math op are identical, the low half of
32243   // the result is the same as the high half. If the shuffle is also replicating
32244   // low and high halves, we don't need the shuffle.
32245   // shuffle (hadd X, X), undef, [low half...high half] --> hadd X, X
32246   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
32247   // TODO: Other mask possibilities like {1,1} and {1,0} could be added here,
32248   // but this should be tied to whatever horizontal op matching and shuffle
32249   // canonicalization are producing.
32250   if (HOp.getValueSizeInBits() == 128 &&
32251       (isTargetShuffleEquivalent(Mask, {0, 0}) ||
32252        isTargetShuffleEquivalent(Mask, {0, 1, 0, 1}) ||
32253        isTargetShuffleEquivalent(Mask, {0, 1, 2, 3, 0, 1, 2, 3})))
32254     return HOp;
32255 
32256   if (HOp.getValueSizeInBits() == 256 &&
32257       (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2}) ||
32258        isTargetShuffleEquivalent(Mask, {0, 1, 0, 1, 4, 5, 4, 5}) ||
32259        isTargetShuffleEquivalent(
32260            Mask, {0, 1, 2, 3, 0, 1, 2, 3, 8, 9, 10, 11, 8, 9, 10, 11})))
32261     return HOp;
32262 
32263   return SDValue();
32264 }
32265 
combineShuffle(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)32266 static SDValue combineShuffle(SDNode *N, SelectionDAG &DAG,
32267                               TargetLowering::DAGCombinerInfo &DCI,
32268                               const X86Subtarget &Subtarget) {
32269   SDLoc dl(N);
32270   EVT VT = N->getValueType(0);
32271   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
32272   // If we have legalized the vector types, look for blends of FADD and FSUB
32273   // nodes that we can fuse into an ADDSUB, FMADDSUB, or FMSUBADD node.
32274   if (TLI.isTypeLegal(VT)) {
32275     if (SDValue AddSub = combineShuffleToAddSubOrFMAddSub(N, Subtarget, DAG))
32276       return AddSub;
32277 
32278     if (SDValue HAddSub = foldShuffleOfHorizOp(N))
32279       return HAddSub;
32280   }
32281 
32282   // During Type Legalization, when promoting illegal vector types,
32283   // the backend might introduce new shuffle dag nodes and bitcasts.
32284   //
32285   // This code performs the following transformation:
32286   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
32287   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
32288   //
32289   // We do this only if both the bitcast and the BINOP dag nodes have
32290   // one use. Also, perform this transformation only if the new binary
32291   // operation is legal. This is to avoid introducing dag nodes that
32292   // potentially need to be further expanded (or custom lowered) into a
32293   // less optimal sequence of dag nodes.
32294   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
32295       N->getOpcode() == ISD::VECTOR_SHUFFLE &&
32296       N->getOperand(0).getOpcode() == ISD::BITCAST &&
32297       N->getOperand(1).isUndef() && N->getOperand(0).hasOneUse()) {
32298     SDValue N0 = N->getOperand(0);
32299     SDValue N1 = N->getOperand(1);
32300 
32301     SDValue BC0 = N0.getOperand(0);
32302     EVT SVT = BC0.getValueType();
32303     unsigned Opcode = BC0.getOpcode();
32304     unsigned NumElts = VT.getVectorNumElements();
32305 
32306     if (BC0.hasOneUse() && SVT.isVector() &&
32307         SVT.getVectorNumElements() * 2 == NumElts &&
32308         TLI.isOperationLegal(Opcode, VT)) {
32309       bool CanFold = false;
32310       switch (Opcode) {
32311       default : break;
32312       case ISD::ADD:
32313       case ISD::SUB:
32314       case ISD::MUL:
32315         // isOperationLegal lies for integer ops on floating point types.
32316         CanFold = VT.isInteger();
32317         break;
32318       case ISD::FADD:
32319       case ISD::FSUB:
32320       case ISD::FMUL:
32321         // isOperationLegal lies for floating point ops on integer types.
32322         CanFold = VT.isFloatingPoint();
32323         break;
32324       }
32325 
32326       unsigned SVTNumElts = SVT.getVectorNumElements();
32327       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
32328       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
32329         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
32330       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
32331         CanFold = SVOp->getMaskElt(i) < 0;
32332 
32333       if (CanFold) {
32334         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
32335         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
32336         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
32337         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, SVOp->getMask());
32338       }
32339     }
32340   }
32341 
32342   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
32343   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
32344   // consecutive, non-overlapping, and in the right order.
32345   SmallVector<SDValue, 16> Elts;
32346   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
32347     if (SDValue Elt = getShuffleScalarElt(N, i, DAG, 0)) {
32348       Elts.push_back(Elt);
32349       continue;
32350     }
32351     Elts.clear();
32352     break;
32353   }
32354 
32355   if (Elts.size() == VT.getVectorNumElements())
32356     if (SDValue LD =
32357             EltsFromConsecutiveLoads(VT, Elts, dl, DAG, Subtarget, true))
32358       return LD;
32359 
32360   // For AVX2, we sometimes want to combine
32361   // (vector_shuffle <mask> (concat_vectors t1, undef)
32362   //                        (concat_vectors t2, undef))
32363   // Into:
32364   // (vector_shuffle <mask> (concat_vectors t1, t2), undef)
32365   // Since the latter can be efficiently lowered with VPERMD/VPERMQ
32366   if (SDValue ShufConcat = combineShuffleOfConcatUndef(N, DAG, Subtarget))
32367     return ShufConcat;
32368 
32369   if (isTargetShuffle(N->getOpcode())) {
32370     SDValue Op(N, 0);
32371     if (SDValue Shuffle = combineTargetShuffle(Op, DAG, DCI, Subtarget))
32372       return Shuffle;
32373 
32374     // Try recursively combining arbitrary sequences of x86 shuffle
32375     // instructions into higher-order shuffles. We do this after combining
32376     // specific PSHUF instruction sequences into their minimal form so that we
32377     // can evaluate how many specialized shuffle instructions are involved in
32378     // a particular chain.
32379     if (SDValue Res = combineX86ShufflesRecursively(
32380             {Op}, 0, Op, {0}, {}, /*Depth*/ 1,
32381             /*HasVarMask*/ false, /*AllowVarMask*/ true, DAG, Subtarget))
32382       return Res;
32383 
32384     // Simplify source operands based on shuffle mask.
32385     // TODO - merge this into combineX86ShufflesRecursively.
32386     APInt KnownUndef, KnownZero;
32387     APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
32388     if (TLI.SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, DCI))
32389       return SDValue(N, 0);
32390   }
32391 
32392   // Look for a truncating shuffle to v2i32 of a PMULUDQ where one of the
32393   // operands is an extend from v2i32 to v2i64. Turn it into a pmulld.
32394   // FIXME: This can probably go away once we default to widening legalization.
32395   if (Subtarget.hasSSE41() && VT == MVT::v4i32 &&
32396       N->getOpcode() == ISD::VECTOR_SHUFFLE &&
32397       N->getOperand(0).getOpcode() == ISD::BITCAST &&
32398       N->getOperand(0).getOperand(0).getOpcode() == X86ISD::PMULUDQ) {
32399     SDValue BC = N->getOperand(0);
32400     SDValue MULUDQ = BC.getOperand(0);
32401     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
32402     ArrayRef<int> Mask = SVOp->getMask();
32403     if (BC.hasOneUse() && MULUDQ.hasOneUse() &&
32404         Mask[0] == 0 && Mask[1] == 2 && Mask[2] == -1 && Mask[3] == -1) {
32405       SDValue Op0 = MULUDQ.getOperand(0);
32406       SDValue Op1 = MULUDQ.getOperand(1);
32407       if (Op0.getOpcode() == ISD::BITCAST &&
32408           Op0.getOperand(0).getOpcode() == ISD::VECTOR_SHUFFLE &&
32409           Op0.getOperand(0).getValueType() == MVT::v4i32) {
32410         ShuffleVectorSDNode *SVOp0 =
32411           cast<ShuffleVectorSDNode>(Op0.getOperand(0));
32412         ArrayRef<int> Mask2 = SVOp0->getMask();
32413         if (Mask2[0] == 0 && Mask2[1] == -1 &&
32414             Mask2[2] == 1 && Mask2[3] == -1) {
32415           Op0 = SVOp0->getOperand(0);
32416           Op1 = DAG.getBitcast(MVT::v4i32, Op1);
32417           Op1 = DAG.getVectorShuffle(MVT::v4i32, dl, Op1, Op1, Mask);
32418           return DAG.getNode(ISD::MUL, dl, MVT::v4i32, Op0, Op1);
32419         }
32420       }
32421       if (Op1.getOpcode() == ISD::BITCAST &&
32422           Op1.getOperand(0).getOpcode() == ISD::VECTOR_SHUFFLE &&
32423           Op1.getOperand(0).getValueType() == MVT::v4i32) {
32424         ShuffleVectorSDNode *SVOp1 =
32425           cast<ShuffleVectorSDNode>(Op1.getOperand(0));
32426         ArrayRef<int> Mask2 = SVOp1->getMask();
32427         if (Mask2[0] == 0 && Mask2[1] == -1 &&
32428             Mask2[2] == 1 && Mask2[3] == -1) {
32429           Op0 = DAG.getBitcast(MVT::v4i32, Op0);
32430           Op0 = DAG.getVectorShuffle(MVT::v4i32, dl, Op0, Op0, Mask);
32431           Op1 = SVOp1->getOperand(0);
32432           return DAG.getNode(ISD::MUL, dl, MVT::v4i32, Op0, Op1);
32433         }
32434       }
32435     }
32436   }
32437 
32438   return SDValue();
32439 }
32440 
SimplifyDemandedVectorEltsForTargetNode(SDValue Op,const APInt & DemandedElts,APInt & KnownUndef,APInt & KnownZero,TargetLoweringOpt & TLO,unsigned Depth) const32441 bool X86TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
32442     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
32443     TargetLoweringOpt &TLO, unsigned Depth) const {
32444   int NumElts = DemandedElts.getBitWidth();
32445   unsigned Opc = Op.getOpcode();
32446   EVT VT = Op.getValueType();
32447 
32448   // Handle special case opcodes.
32449   switch (Opc) {
32450   case X86ISD::VSHL:
32451   case X86ISD::VSRL:
32452   case X86ISD::VSRA: {
32453     // We only need the bottom 64-bits of the (128-bit) shift amount.
32454     SDValue Amt = Op.getOperand(1);
32455     MVT AmtVT = Amt.getSimpleValueType();
32456     assert(AmtVT.is128BitVector() && "Unexpected value type");
32457     APInt AmtUndef, AmtZero;
32458     unsigned NumAmtElts = AmtVT.getVectorNumElements();
32459     APInt AmtElts = APInt::getLowBitsSet(NumAmtElts, NumAmtElts / 2);
32460     if (SimplifyDemandedVectorElts(Amt, AmtElts, AmtUndef, AmtZero, TLO,
32461                                    Depth + 1))
32462       return true;
32463     LLVM_FALLTHROUGH;
32464   }
32465   case X86ISD::VSHLI:
32466   case X86ISD::VSRLI:
32467   case X86ISD::VSRAI: {
32468     SDValue Src = Op.getOperand(0);
32469     APInt SrcUndef;
32470     if (SimplifyDemandedVectorElts(Src, DemandedElts, SrcUndef, KnownZero, TLO,
32471                                    Depth + 1))
32472       return true;
32473     // TODO convert SrcUndef to KnownUndef.
32474     break;
32475   }
32476   case X86ISD::CVTSI2P:
32477   case X86ISD::CVTUI2P: {
32478     SDValue Src = Op.getOperand(0);
32479     MVT SrcVT = Src.getSimpleValueType();
32480     APInt SrcUndef, SrcZero;
32481     APInt SrcElts = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
32482     if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
32483                                    Depth + 1))
32484       return true;
32485     break;
32486   }
32487   case X86ISD::PACKSS:
32488   case X86ISD::PACKUS: {
32489     APInt DemandedLHS, DemandedRHS;
32490     getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
32491 
32492     APInt SrcUndef, SrcZero;
32493     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, SrcUndef,
32494                                    SrcZero, TLO, Depth + 1))
32495       return true;
32496     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, SrcUndef,
32497                                    SrcZero, TLO, Depth + 1))
32498       return true;
32499     break;
32500   }
32501   case X86ISD::VBROADCAST: {
32502     SDValue Src = Op.getOperand(0);
32503     MVT SrcVT = Src.getSimpleValueType();
32504     if (!SrcVT.isVector())
32505       return false;
32506     // Don't bother broadcasting if we just need the 0'th element.
32507     if (DemandedElts == 1) {
32508       if(Src.getValueType() != VT)
32509         Src = widenSubVector(VT.getSimpleVT(), Src, false, Subtarget, TLO.DAG,
32510                              SDLoc(Op));
32511       return TLO.CombineTo(Op, Src);
32512     }
32513     APInt SrcUndef, SrcZero;
32514     APInt SrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(), 0);
32515     if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
32516                                    Depth + 1))
32517       return true;
32518     break;
32519   }
32520   case X86ISD::PSHUFB: {
32521     // TODO - simplify other variable shuffle masks.
32522     SDValue Mask = Op.getOperand(1);
32523     APInt MaskUndef, MaskZero;
32524     if (SimplifyDemandedVectorElts(Mask, DemandedElts, MaskUndef, MaskZero, TLO,
32525                                    Depth + 1))
32526       return true;
32527     break;
32528   }
32529   }
32530 
32531   // Simplify target shuffles.
32532   if (!isTargetShuffle(Opc) || !VT.isSimple())
32533     return false;
32534 
32535   // Get target shuffle mask.
32536   bool IsUnary;
32537   SmallVector<int, 64> OpMask;
32538   SmallVector<SDValue, 2> OpInputs;
32539   if (!getTargetShuffleMask(Op.getNode(), VT.getSimpleVT(), true, OpInputs,
32540                             OpMask, IsUnary))
32541     return false;
32542 
32543   // Shuffle inputs must be the same type as the result.
32544   if (llvm::any_of(OpInputs,
32545                    [VT](SDValue V) { return VT != V.getValueType(); }))
32546     return false;
32547 
32548   // Clear known elts that might have been set above.
32549   KnownZero.clearAllBits();
32550   KnownUndef.clearAllBits();
32551 
32552   // Check if shuffle mask can be simplified to undef/zero/identity.
32553   int NumSrcs = OpInputs.size();
32554   for (int i = 0; i != NumElts; ++i) {
32555     int &M = OpMask[i];
32556     if (!DemandedElts[i])
32557       M = SM_SentinelUndef;
32558     else if (0 <= M && OpInputs[M / NumElts].isUndef())
32559       M = SM_SentinelUndef;
32560   }
32561 
32562   if (isUndefInRange(OpMask, 0, NumElts)) {
32563     KnownUndef.setAllBits();
32564     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
32565   }
32566   if (isUndefOrZeroInRange(OpMask, 0, NumElts)) {
32567     KnownZero.setAllBits();
32568     return TLO.CombineTo(
32569         Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, SDLoc(Op)));
32570   }
32571   for (int Src = 0; Src != NumSrcs; ++Src)
32572     if (isSequentialOrUndefInRange(OpMask, 0, NumElts, Src * NumElts))
32573       return TLO.CombineTo(Op, OpInputs[Src]);
32574 
32575   // Attempt to simplify inputs.
32576   for (int Src = 0; Src != NumSrcs; ++Src) {
32577     int Lo = Src * NumElts;
32578     APInt SrcElts = APInt::getNullValue(NumElts);
32579     for (int i = 0; i != NumElts; ++i)
32580       if (DemandedElts[i]) {
32581         int M = OpMask[i] - Lo;
32582         if (0 <= M && M < NumElts)
32583           SrcElts.setBit(M);
32584       }
32585 
32586     APInt SrcUndef, SrcZero;
32587     if (SimplifyDemandedVectorElts(OpInputs[Src], SrcElts, SrcUndef, SrcZero,
32588                                    TLO, Depth + 1))
32589       return true;
32590   }
32591 
32592   // Extract known zero/undef elements.
32593   // TODO - Propagate input undef/zero elts.
32594   for (int i = 0; i != NumElts; ++i) {
32595     if (OpMask[i] == SM_SentinelUndef)
32596       KnownUndef.setBit(i);
32597     if (OpMask[i] == SM_SentinelZero)
32598       KnownZero.setBit(i);
32599   }
32600 
32601   return false;
32602 }
32603 
SimplifyDemandedBitsForTargetNode(SDValue Op,const APInt & OriginalDemandedBits,const APInt & OriginalDemandedElts,KnownBits & Known,TargetLoweringOpt & TLO,unsigned Depth) const32604 bool X86TargetLowering::SimplifyDemandedBitsForTargetNode(
32605     SDValue Op, const APInt &OriginalDemandedBits,
32606     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
32607     unsigned Depth) const {
32608   EVT VT = Op.getValueType();
32609   unsigned BitWidth = OriginalDemandedBits.getBitWidth();
32610   unsigned Opc = Op.getOpcode();
32611   switch(Opc) {
32612   case X86ISD::PMULDQ:
32613   case X86ISD::PMULUDQ: {
32614     // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
32615     KnownBits KnownOp;
32616     SDValue LHS = Op.getOperand(0);
32617     SDValue RHS = Op.getOperand(1);
32618     // FIXME: Can we bound this better?
32619     APInt DemandedMask = APInt::getLowBitsSet(64, 32);
32620     if (SimplifyDemandedBits(LHS, DemandedMask, KnownOp, TLO, Depth + 1))
32621       return true;
32622     if (SimplifyDemandedBits(RHS, DemandedMask, KnownOp, TLO, Depth + 1))
32623       return true;
32624     break;
32625   }
32626   case X86ISD::VSHLI: {
32627     SDValue Op0 = Op.getOperand(0);
32628     SDValue Op1 = Op.getOperand(1);
32629 
32630     if (auto *ShiftImm = dyn_cast<ConstantSDNode>(Op1)) {
32631       if (ShiftImm->getAPIntValue().uge(BitWidth))
32632         break;
32633 
32634       unsigned ShAmt = ShiftImm->getZExtValue();
32635       APInt DemandedMask = OriginalDemandedBits.lshr(ShAmt);
32636 
32637       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
32638       // single shift.  We can do this if the bottom bits (which are shifted
32639       // out) are never demanded.
32640       if (Op0.getOpcode() == X86ISD::VSRLI &&
32641           OriginalDemandedBits.countTrailingZeros() >= ShAmt) {
32642         if (auto *Shift2Imm = dyn_cast<ConstantSDNode>(Op0.getOperand(1))) {
32643           if (Shift2Imm->getAPIntValue().ult(BitWidth)) {
32644             int Diff = ShAmt - Shift2Imm->getZExtValue();
32645             if (Diff == 0)
32646               return TLO.CombineTo(Op, Op0.getOperand(0));
32647 
32648             unsigned NewOpc = Diff < 0 ? X86ISD::VSRLI : X86ISD::VSHLI;
32649             SDValue NewShift = TLO.DAG.getNode(
32650                 NewOpc, SDLoc(Op), VT, Op0.getOperand(0),
32651                 TLO.DAG.getConstant(std::abs(Diff), SDLoc(Op), MVT::i8));
32652             return TLO.CombineTo(Op, NewShift);
32653           }
32654         }
32655       }
32656 
32657       if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
32658                                TLO, Depth + 1))
32659         return true;
32660 
32661       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
32662       Known.Zero <<= ShAmt;
32663       Known.One <<= ShAmt;
32664 
32665       // Low bits known zero.
32666       Known.Zero.setLowBits(ShAmt);
32667     }
32668     break;
32669   }
32670   case X86ISD::VSRLI: {
32671     if (auto *ShiftImm = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
32672       if (ShiftImm->getAPIntValue().uge(BitWidth))
32673         break;
32674 
32675       unsigned ShAmt = ShiftImm->getZExtValue();
32676       APInt DemandedMask = OriginalDemandedBits << ShAmt;
32677 
32678       if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask,
32679                                OriginalDemandedElts, Known, TLO, Depth + 1))
32680         return true;
32681 
32682       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
32683       Known.Zero.lshrInPlace(ShAmt);
32684       Known.One.lshrInPlace(ShAmt);
32685 
32686       // High bits known zero.
32687       Known.Zero.setHighBits(ShAmt);
32688     }
32689     break;
32690   }
32691   case X86ISD::VSRAI: {
32692     SDValue Op0 = Op.getOperand(0);
32693     SDValue Op1 = Op.getOperand(1);
32694 
32695     if (auto *ShiftImm = dyn_cast<ConstantSDNode>(Op1)) {
32696       if (ShiftImm->getAPIntValue().uge(BitWidth))
32697         break;
32698 
32699       unsigned ShAmt = ShiftImm->getZExtValue();
32700       APInt DemandedMask = OriginalDemandedBits << ShAmt;
32701 
32702       // If we just want the sign bit then we don't need to shift it.
32703       if (OriginalDemandedBits.isSignMask())
32704         return TLO.CombineTo(Op, Op0);
32705 
32706       // fold (VSRAI (VSHLI X, C1), C1) --> X iff NumSignBits(X) > C1
32707       if (Op0.getOpcode() == X86ISD::VSHLI && Op1 == Op0.getOperand(1)) {
32708         SDValue Op00 = Op0.getOperand(0);
32709         unsigned NumSignBits =
32710             TLO.DAG.ComputeNumSignBits(Op00, OriginalDemandedElts);
32711         if (ShAmt < NumSignBits)
32712           return TLO.CombineTo(Op, Op00);
32713       }
32714 
32715       // If any of the demanded bits are produced by the sign extension, we also
32716       // demand the input sign bit.
32717       if (OriginalDemandedBits.countLeadingZeros() < ShAmt)
32718         DemandedMask.setSignBit();
32719 
32720       if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
32721                                TLO, Depth + 1))
32722         return true;
32723 
32724       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
32725       Known.Zero.lshrInPlace(ShAmt);
32726       Known.One.lshrInPlace(ShAmt);
32727 
32728       // If the input sign bit is known to be zero, or if none of the top bits
32729       // are demanded, turn this into an unsigned shift right.
32730       if (Known.Zero[BitWidth - ShAmt - 1] ||
32731           OriginalDemandedBits.countLeadingZeros() >= ShAmt)
32732         return TLO.CombineTo(
32733             Op, TLO.DAG.getNode(X86ISD::VSRLI, SDLoc(Op), VT, Op0, Op1));
32734 
32735       // High bits are known one.
32736       if (Known.One[BitWidth - ShAmt - 1])
32737         Known.One.setHighBits(ShAmt);
32738     }
32739     break;
32740   }
32741   case X86ISD::MOVMSK: {
32742     SDValue Src = Op.getOperand(0);
32743     MVT SrcVT = Src.getSimpleValueType();
32744     unsigned SrcBits = SrcVT.getScalarSizeInBits();
32745     unsigned NumElts = SrcVT.getVectorNumElements();
32746 
32747     // If we don't need the sign bits at all just return zero.
32748     if (OriginalDemandedBits.countTrailingZeros() >= NumElts)
32749       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
32750 
32751     // Only demand the vector elements of the sign bits we need.
32752     APInt KnownUndef, KnownZero;
32753     APInt DemandedElts = OriginalDemandedBits.zextOrTrunc(NumElts);
32754     if (SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, KnownZero,
32755                                    TLO, Depth + 1))
32756       return true;
32757 
32758     Known.Zero = KnownZero.zextOrSelf(BitWidth);
32759     Known.Zero.setHighBits(BitWidth - NumElts);
32760 
32761     // MOVMSK only uses the MSB from each vector element.
32762     KnownBits KnownSrc;
32763     if (SimplifyDemandedBits(Src, APInt::getSignMask(SrcBits), DemandedElts,
32764                              KnownSrc, TLO, Depth + 1))
32765       return true;
32766 
32767     if (KnownSrc.One[SrcBits - 1])
32768       Known.One.setLowBits(NumElts);
32769     else if (KnownSrc.Zero[SrcBits - 1])
32770       Known.Zero.setLowBits(NumElts);
32771     return false;
32772   }
32773   }
32774 
32775   return TargetLowering::SimplifyDemandedBitsForTargetNode(
32776       Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
32777 }
32778 
32779 /// Check if a vector extract from a target-specific shuffle of a load can be
32780 /// folded into a single element load.
32781 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
32782 /// shuffles have been custom lowered so we need to handle those here.
XFormVExtractWithShuffleIntoLoad(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)32783 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
32784                                          TargetLowering::DAGCombinerInfo &DCI) {
32785   if (DCI.isBeforeLegalizeOps())
32786     return SDValue();
32787 
32788   SDValue InVec = N->getOperand(0);
32789   SDValue EltNo = N->getOperand(1);
32790   EVT EltVT = N->getValueType(0);
32791 
32792   if (!isa<ConstantSDNode>(EltNo))
32793     return SDValue();
32794 
32795   EVT OriginalVT = InVec.getValueType();
32796 
32797   // Peek through bitcasts, don't duplicate a load with other uses.
32798   InVec = peekThroughOneUseBitcasts(InVec);
32799 
32800   EVT CurrentVT = InVec.getValueType();
32801   if (!CurrentVT.isVector() ||
32802       CurrentVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
32803     return SDValue();
32804 
32805   if (!isTargetShuffle(InVec.getOpcode()))
32806     return SDValue();
32807 
32808   // Don't duplicate a load with other uses.
32809   if (!InVec.hasOneUse())
32810     return SDValue();
32811 
32812   SmallVector<int, 16> ShuffleMask;
32813   SmallVector<SDValue, 2> ShuffleOps;
32814   bool UnaryShuffle;
32815   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(), true,
32816                             ShuffleOps, ShuffleMask, UnaryShuffle))
32817     return SDValue();
32818 
32819   // Select the input vector, guarding against out of range extract vector.
32820   unsigned NumElems = CurrentVT.getVectorNumElements();
32821   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
32822   int Idx = (Elt > (int)NumElems) ? SM_SentinelUndef : ShuffleMask[Elt];
32823 
32824   if (Idx == SM_SentinelZero)
32825     return EltVT.isInteger() ? DAG.getConstant(0, SDLoc(N), EltVT)
32826                              : DAG.getConstantFP(+0.0, SDLoc(N), EltVT);
32827   if (Idx == SM_SentinelUndef)
32828     return DAG.getUNDEF(EltVT);
32829 
32830   // Bail if any mask element is SM_SentinelZero - getVectorShuffle below
32831   // won't handle it.
32832   if (llvm::any_of(ShuffleMask, [](int M) { return M == SM_SentinelZero; }))
32833     return SDValue();
32834 
32835   assert(0 <= Idx && Idx < (int)(2 * NumElems) && "Shuffle index out of range");
32836   SDValue LdNode = (Idx < (int)NumElems) ? ShuffleOps[0] : ShuffleOps[1];
32837 
32838   // If inputs to shuffle are the same for both ops, then allow 2 uses
32839   unsigned AllowedUses =
32840       (ShuffleOps.size() > 1 && ShuffleOps[0] == ShuffleOps[1]) ? 2 : 1;
32841 
32842   if (LdNode.getOpcode() == ISD::BITCAST) {
32843     // Don't duplicate a load with other uses.
32844     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
32845       return SDValue();
32846 
32847     AllowedUses = 1; // only allow 1 load use if we have a bitcast
32848     LdNode = LdNode.getOperand(0);
32849   }
32850 
32851   if (!ISD::isNormalLoad(LdNode.getNode()))
32852     return SDValue();
32853 
32854   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
32855 
32856   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
32857     return SDValue();
32858 
32859   // If there's a bitcast before the shuffle, check if the load type and
32860   // alignment is valid.
32861   unsigned Align = LN0->getAlignment();
32862   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
32863   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
32864       EltVT.getTypeForEVT(*DAG.getContext()));
32865 
32866   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
32867     return SDValue();
32868 
32869   // All checks match so transform back to vector_shuffle so that DAG combiner
32870   // can finish the job
32871   SDLoc dl(N);
32872 
32873   // Create shuffle node taking into account the case that its a unary shuffle
32874   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT) : ShuffleOps[1];
32875   Shuffle = DAG.getVectorShuffle(CurrentVT, dl, ShuffleOps[0], Shuffle,
32876                                  ShuffleMask);
32877   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
32878   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
32879                      EltNo);
32880 }
32881 
32882 // Try to match patterns such as
32883 // (i16 bitcast (v16i1 x))
32884 // ->
32885 // (i16 movmsk (16i8 sext (v16i1 x)))
32886 // before the illegal vector is scalarized on subtargets that don't have legal
32887 // vxi1 types.
combineBitcastvxi1(SelectionDAG & DAG,SDValue BitCast,const X86Subtarget & Subtarget)32888 static SDValue combineBitcastvxi1(SelectionDAG &DAG, SDValue BitCast,
32889                                   const X86Subtarget &Subtarget) {
32890   EVT VT = BitCast.getValueType();
32891   SDValue N0 = BitCast.getOperand(0);
32892   EVT VecVT = N0->getValueType(0);
32893 
32894   if (!VT.isScalarInteger() || !VecVT.isSimple())
32895     return SDValue();
32896 
32897   // If the input is a truncate from v16i8 or v32i8 go ahead and use a
32898   // movmskb even with avx512. This will be better than truncating to vXi1 and
32899   // using a kmov. This can especially help KNL if the input is a v16i8/v32i8
32900   // vpcmpeqb/vpcmpgtb.
32901   bool IsTruncated = N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
32902                      (N0.getOperand(0).getValueType() == MVT::v16i8 ||
32903                       N0.getOperand(0).getValueType() == MVT::v32i8 ||
32904                       N0.getOperand(0).getValueType() == MVT::v64i8);
32905 
32906   // With AVX512 vxi1 types are legal and we prefer using k-regs.
32907   // MOVMSK is supported in SSE2 or later.
32908   if (!Subtarget.hasSSE2() || (Subtarget.hasAVX512() && !IsTruncated))
32909     return SDValue();
32910 
32911   // There are MOVMSK flavors for types v16i8, v32i8, v4f32, v8f32, v4f64 and
32912   // v8f64. So all legal 128-bit and 256-bit vectors are covered except for
32913   // v8i16 and v16i16.
32914   // For these two cases, we can shuffle the upper element bytes to a
32915   // consecutive sequence at the start of the vector and treat the results as
32916   // v16i8 or v32i8, and for v16i8 this is the preferable solution. However,
32917   // for v16i16 this is not the case, because the shuffle is expensive, so we
32918   // avoid sign-extending to this type entirely.
32919   // For example, t0 := (v8i16 sext(v8i1 x)) needs to be shuffled as:
32920   // (v16i8 shuffle <0,2,4,6,8,10,12,14,u,u,...,u> (v16i8 bitcast t0), undef)
32921   MVT SExtVT;
32922   switch (VecVT.getSimpleVT().SimpleTy) {
32923   default:
32924     return SDValue();
32925   case MVT::v2i1:
32926     SExtVT = MVT::v2i64;
32927     break;
32928   case MVT::v4i1:
32929     SExtVT = MVT::v4i32;
32930     // For cases such as (i4 bitcast (v4i1 setcc v4i64 v1, v2))
32931     // sign-extend to a 256-bit operation to avoid truncation.
32932     if (N0->getOpcode() == ISD::SETCC && Subtarget.hasAVX() &&
32933         N0->getOperand(0).getValueType().is256BitVector()) {
32934       SExtVT = MVT::v4i64;
32935     }
32936     break;
32937   case MVT::v8i1:
32938     SExtVT = MVT::v8i16;
32939     // For cases such as (i8 bitcast (v8i1 setcc v8i32 v1, v2)),
32940     // sign-extend to a 256-bit operation to match the compare.
32941     // If the setcc operand is 128-bit, prefer sign-extending to 128-bit over
32942     // 256-bit because the shuffle is cheaper than sign extending the result of
32943     // the compare.
32944     if (N0->getOpcode() == ISD::SETCC && Subtarget.hasAVX() &&
32945         (N0->getOperand(0).getValueType().is256BitVector() ||
32946          N0->getOperand(0).getValueType().is512BitVector())) {
32947       SExtVT = MVT::v8i32;
32948     }
32949     break;
32950   case MVT::v16i1:
32951     SExtVT = MVT::v16i8;
32952     // For the case (i16 bitcast (v16i1 setcc v16i16 v1, v2)),
32953     // it is not profitable to sign-extend to 256-bit because this will
32954     // require an extra cross-lane shuffle which is more expensive than
32955     // truncating the result of the compare to 128-bits.
32956     break;
32957   case MVT::v32i1:
32958     SExtVT = MVT::v32i8;
32959     break;
32960   case MVT::v64i1:
32961     // If we have AVX512F, but not AVX512BW and the input is truncated from
32962     // v64i8 checked earlier. Then split the input and make two pmovmskbs.
32963     if (Subtarget.hasAVX512() && !Subtarget.hasBWI()) {
32964       SExtVT = MVT::v64i8;
32965       break;
32966     }
32967     return SDValue();
32968   };
32969 
32970   SDLoc DL(BitCast);
32971   SDValue V = DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, N0);
32972 
32973   if (SExtVT == MVT::v64i8) {
32974     SDValue Lo, Hi;
32975     std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
32976     Lo = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Lo);
32977     Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Lo);
32978     Hi = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Hi);
32979     Hi = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Hi);
32980     Hi = DAG.getNode(ISD::SHL, DL, MVT::i64, Hi,
32981                      DAG.getConstant(32, DL, MVT::i8));
32982     V = DAG.getNode(ISD::OR, DL, MVT::i64, Lo, Hi);
32983   } else if (SExtVT == MVT::v16i8 || SExtVT == MVT::v32i8) {
32984     V = getPMOVMSKB(DL, V, DAG, Subtarget);
32985   } else {
32986     if (SExtVT == MVT::v8i16)
32987       V = DAG.getNode(X86ISD::PACKSS, DL, MVT::v16i8, V,
32988                       DAG.getUNDEF(MVT::v8i16));
32989     V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
32990   }
32991   return DAG.getZExtOrTrunc(V, DL, VT);
32992 }
32993 
32994 // Convert a vXi1 constant build vector to the same width scalar integer.
combinevXi1ConstantToInteger(SDValue Op,SelectionDAG & DAG)32995 static SDValue combinevXi1ConstantToInteger(SDValue Op, SelectionDAG &DAG) {
32996   EVT SrcVT = Op.getValueType();
32997   assert(SrcVT.getVectorElementType() == MVT::i1 &&
32998          "Expected a vXi1 vector");
32999   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
33000          "Expected a constant build vector");
33001 
33002   APInt Imm(SrcVT.getVectorNumElements(), 0);
33003   for (unsigned Idx = 0, e = Op.getNumOperands(); Idx < e; ++Idx) {
33004     SDValue In = Op.getOperand(Idx);
33005     if (!In.isUndef() && (cast<ConstantSDNode>(In)->getZExtValue() & 0x1))
33006       Imm.setBit(Idx);
33007   }
33008   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), Imm.getBitWidth());
33009   return DAG.getConstant(Imm, SDLoc(Op), IntVT);
33010 }
33011 
combineCastedMaskArithmetic(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)33012 static SDValue combineCastedMaskArithmetic(SDNode *N, SelectionDAG &DAG,
33013                                            TargetLowering::DAGCombinerInfo &DCI,
33014                                            const X86Subtarget &Subtarget) {
33015   assert(N->getOpcode() == ISD::BITCAST && "Expected a bitcast");
33016 
33017   if (!DCI.isBeforeLegalizeOps())
33018     return SDValue();
33019 
33020   // Only do this if we have k-registers.
33021   if (!Subtarget.hasAVX512())
33022     return SDValue();
33023 
33024   EVT DstVT = N->getValueType(0);
33025   SDValue Op = N->getOperand(0);
33026   EVT SrcVT = Op.getValueType();
33027 
33028   if (!Op.hasOneUse())
33029     return SDValue();
33030 
33031   // Look for logic ops.
33032   if (Op.getOpcode() != ISD::AND &&
33033       Op.getOpcode() != ISD::OR &&
33034       Op.getOpcode() != ISD::XOR)
33035     return SDValue();
33036 
33037   // Make sure we have a bitcast between mask registers and a scalar type.
33038   if (!(SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
33039         DstVT.isScalarInteger()) &&
33040       !(DstVT.isVector() && DstVT.getVectorElementType() == MVT::i1 &&
33041         SrcVT.isScalarInteger()))
33042     return SDValue();
33043 
33044   SDValue LHS = Op.getOperand(0);
33045   SDValue RHS = Op.getOperand(1);
33046 
33047   if (LHS.hasOneUse() && LHS.getOpcode() == ISD::BITCAST &&
33048       LHS.getOperand(0).getValueType() == DstVT)
33049     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT, LHS.getOperand(0),
33050                        DAG.getBitcast(DstVT, RHS));
33051 
33052   if (RHS.hasOneUse() && RHS.getOpcode() == ISD::BITCAST &&
33053       RHS.getOperand(0).getValueType() == DstVT)
33054     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
33055                        DAG.getBitcast(DstVT, LHS), RHS.getOperand(0));
33056 
33057   // If the RHS is a vXi1 build vector, this is a good reason to flip too.
33058   // Most of these have to move a constant from the scalar domain anyway.
33059   if (ISD::isBuildVectorOfConstantSDNodes(RHS.getNode())) {
33060     RHS = combinevXi1ConstantToInteger(RHS, DAG);
33061     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
33062                        DAG.getBitcast(DstVT, LHS), RHS);
33063   }
33064 
33065   return SDValue();
33066 }
33067 
createMMXBuildVector(SDValue N,SelectionDAG & DAG,const X86Subtarget & Subtarget)33068 static SDValue createMMXBuildVector(SDValue N, SelectionDAG &DAG,
33069                                     const X86Subtarget &Subtarget) {
33070   SDLoc DL(N);
33071   unsigned NumElts = N.getNumOperands();
33072 
33073   auto *BV = cast<BuildVectorSDNode>(N);
33074   SDValue Splat = BV->getSplatValue();
33075 
33076   // Build MMX element from integer GPR or SSE float values.
33077   auto CreateMMXElement = [&](SDValue V) {
33078     if (V.isUndef())
33079       return DAG.getUNDEF(MVT::x86mmx);
33080     if (V.getValueType().isFloatingPoint()) {
33081       if (Subtarget.hasSSE1() && !isa<ConstantFPSDNode>(V)) {
33082         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4f32, V);
33083         V = DAG.getBitcast(MVT::v2i64, V);
33084         return DAG.getNode(X86ISD::MOVDQ2Q, DL, MVT::x86mmx, V);
33085       }
33086       V = DAG.getBitcast(MVT::i32, V);
33087     } else {
33088       V = DAG.getAnyExtOrTrunc(V, DL, MVT::i32);
33089     }
33090     return DAG.getNode(X86ISD::MMX_MOVW2D, DL, MVT::x86mmx, V);
33091   };
33092 
33093   // Convert build vector ops to MMX data in the bottom elements.
33094   SmallVector<SDValue, 8> Ops;
33095 
33096   // Broadcast - use (PUNPCKL+)PSHUFW to broadcast single element.
33097   if (Splat) {
33098     if (Splat.isUndef())
33099       return DAG.getUNDEF(MVT::x86mmx);
33100 
33101     Splat = CreateMMXElement(Splat);
33102 
33103     if (Subtarget.hasSSE1()) {
33104       // Unpack v8i8 to splat i8 elements to lowest 16-bits.
33105       if (NumElts == 8)
33106         Splat = DAG.getNode(
33107             ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
33108             DAG.getConstant(Intrinsic::x86_mmx_punpcklbw, DL, MVT::i32), Splat,
33109             Splat);
33110 
33111       // Use PSHUFW to repeat 16-bit elements.
33112       unsigned ShufMask = (NumElts > 2 ? 0 : 0x44);
33113       return DAG.getNode(
33114           ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
33115           DAG.getConstant(Intrinsic::x86_sse_pshuf_w, DL, MVT::i32), Splat,
33116           DAG.getConstant(ShufMask, DL, MVT::i8));
33117     }
33118     Ops.append(NumElts, Splat);
33119   } else {
33120     for (unsigned i = 0; i != NumElts; ++i)
33121       Ops.push_back(CreateMMXElement(N.getOperand(i)));
33122   }
33123 
33124   // Use tree of PUNPCKLs to build up general MMX vector.
33125   while (Ops.size() > 1) {
33126     unsigned NumOps = Ops.size();
33127     unsigned IntrinOp =
33128         (NumOps == 2 ? Intrinsic::x86_mmx_punpckldq
33129                      : (NumOps == 4 ? Intrinsic::x86_mmx_punpcklwd
33130                                     : Intrinsic::x86_mmx_punpcklbw));
33131     SDValue Intrin = DAG.getConstant(IntrinOp, DL, MVT::i32);
33132     for (unsigned i = 0; i != NumOps; i += 2)
33133       Ops[i / 2] = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx, Intrin,
33134                                Ops[i], Ops[i + 1]);
33135     Ops.resize(NumOps / 2);
33136   }
33137 
33138   return Ops[0];
33139 }
33140 
combineBitcast(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)33141 static SDValue combineBitcast(SDNode *N, SelectionDAG &DAG,
33142                               TargetLowering::DAGCombinerInfo &DCI,
33143                               const X86Subtarget &Subtarget) {
33144   SDValue N0 = N->getOperand(0);
33145   EVT VT = N->getValueType(0);
33146   EVT SrcVT = N0.getValueType();
33147 
33148   // Try to match patterns such as
33149   // (i16 bitcast (v16i1 x))
33150   // ->
33151   // (i16 movmsk (16i8 sext (v16i1 x)))
33152   // before the setcc result is scalarized on subtargets that don't have legal
33153   // vxi1 types.
33154   if (DCI.isBeforeLegalize()) {
33155     if (SDValue V = combineBitcastvxi1(DAG, SDValue(N, 0), Subtarget))
33156       return V;
33157 
33158     // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
33159     // type, widen both sides to avoid a trip through memory.
33160     if ((VT == MVT::v4i1 || VT == MVT::v2i1) && SrcVT.isScalarInteger() &&
33161         Subtarget.hasAVX512()) {
33162       SDLoc dl(N);
33163       N0 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, N0);
33164       N0 = DAG.getBitcast(MVT::v8i1, N0);
33165       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, N0,
33166                          DAG.getIntPtrConstant(0, dl));
33167     }
33168 
33169     // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
33170     // type, widen both sides to avoid a trip through memory.
33171     if ((SrcVT == MVT::v4i1 || SrcVT == MVT::v2i1) && VT.isScalarInteger() &&
33172         Subtarget.hasAVX512()) {
33173       SDLoc dl(N);
33174       unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
33175       SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT));
33176       Ops[0] = N0;
33177       N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
33178       N0 = DAG.getBitcast(MVT::i8, N0);
33179       return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
33180     }
33181   }
33182 
33183   // Since MMX types are special and don't usually play with other vector types,
33184   // it's better to handle them early to be sure we emit efficient code by
33185   // avoiding store-load conversions.
33186   if (VT == MVT::x86mmx) {
33187     // Detect MMX constant vectors.
33188     APInt UndefElts;
33189     SmallVector<APInt, 1> EltBits;
33190     if (getTargetConstantBitsFromNode(N0, 64, UndefElts, EltBits)) {
33191       SDLoc DL(N0);
33192       // Handle zero-extension of i32 with MOVD.
33193       if (EltBits[0].countLeadingZeros() >= 32)
33194         return DAG.getNode(X86ISD::MMX_MOVW2D, DL, VT,
33195                            DAG.getConstant(EltBits[0].trunc(32), DL, MVT::i32));
33196       // Else, bitcast to a double.
33197       // TODO - investigate supporting sext 32-bit immediates on x86_64.
33198       APFloat F64(APFloat::IEEEdouble(), EltBits[0]);
33199       return DAG.getBitcast(VT, DAG.getConstantFP(F64, DL, MVT::f64));
33200     }
33201 
33202     // Detect bitcasts to x86mmx low word.
33203     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
33204         (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) &&
33205         N0.getOperand(0).getValueType() == SrcVT.getScalarType()) {
33206       bool LowUndef = true, AllUndefOrZero = true;
33207       for (unsigned i = 1, e = SrcVT.getVectorNumElements(); i != e; ++i) {
33208         SDValue Op = N0.getOperand(i);
33209         LowUndef &= Op.isUndef() || (i >= e/2);
33210         AllUndefOrZero &= (Op.isUndef() || isNullConstant(Op));
33211       }
33212       if (AllUndefOrZero) {
33213         SDValue N00 = N0.getOperand(0);
33214         SDLoc dl(N00);
33215         N00 = LowUndef ? DAG.getAnyExtOrTrunc(N00, dl, MVT::i32)
33216                        : DAG.getZExtOrTrunc(N00, dl, MVT::i32);
33217         return DAG.getNode(X86ISD::MMX_MOVW2D, dl, VT, N00);
33218       }
33219     }
33220 
33221     // Detect bitcasts of 64-bit build vectors and convert to a
33222     // MMX UNPCK/PSHUFW which takes MMX type inputs with the value in the
33223     // lowest element.
33224     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
33225         (SrcVT == MVT::v2f32 || SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 ||
33226          SrcVT == MVT::v8i8))
33227       return createMMXBuildVector(N0, DAG, Subtarget);
33228 
33229     // Detect bitcasts between element or subvector extraction to x86mmx.
33230     if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
33231          N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) &&
33232         isNullConstant(N0.getOperand(1))) {
33233       SDValue N00 = N0.getOperand(0);
33234       if (N00.getValueType().is128BitVector())
33235         return DAG.getNode(X86ISD::MOVDQ2Q, SDLoc(N00), VT,
33236                            DAG.getBitcast(MVT::v2i64, N00));
33237     }
33238 
33239     // Detect bitcasts from FP_TO_SINT to x86mmx.
33240     if (SrcVT == MVT::v2i32 && N0.getOpcode() == ISD::FP_TO_SINT) {
33241       SDLoc DL(N0);
33242       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
33243                                 DAG.getUNDEF(MVT::v2i32));
33244       return DAG.getNode(X86ISD::MOVDQ2Q, DL, VT,
33245                          DAG.getBitcast(MVT::v2i64, Res));
33246     }
33247   }
33248 
33249   // Try to remove a bitcast of constant vXi1 vector. We have to legalize
33250   // most of these to scalar anyway.
33251   if (Subtarget.hasAVX512() && VT.isScalarInteger() &&
33252       SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
33253       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
33254     return combinevXi1ConstantToInteger(N0, DAG);
33255   }
33256 
33257   if (Subtarget.hasAVX512() && SrcVT.isScalarInteger() &&
33258       VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
33259       isa<ConstantSDNode>(N0)) {
33260     auto *C = cast<ConstantSDNode>(N0);
33261     if (C->isAllOnesValue())
33262       return DAG.getConstant(1, SDLoc(N0), VT);
33263     if (C->isNullValue())
33264       return DAG.getConstant(0, SDLoc(N0), VT);
33265   }
33266 
33267   // Try to remove bitcasts from input and output of mask arithmetic to
33268   // remove GPR<->K-register crossings.
33269   if (SDValue V = combineCastedMaskArithmetic(N, DAG, DCI, Subtarget))
33270     return V;
33271 
33272   // Convert a bitcasted integer logic operation that has one bitcasted
33273   // floating-point operand into a floating-point logic operation. This may
33274   // create a load of a constant, but that is cheaper than materializing the
33275   // constant in an integer register and transferring it to an SSE register or
33276   // transferring the SSE operand to integer register and back.
33277   unsigned FPOpcode;
33278   switch (N0.getOpcode()) {
33279     case ISD::AND: FPOpcode = X86ISD::FAND; break;
33280     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
33281     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
33282     default: return SDValue();
33283   }
33284 
33285   if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
33286         (Subtarget.hasSSE2() && VT == MVT::f64)))
33287     return SDValue();
33288 
33289   SDValue LogicOp0 = N0.getOperand(0);
33290   SDValue LogicOp1 = N0.getOperand(1);
33291   SDLoc DL0(N0);
33292 
33293   // bitcast(logic(bitcast(X), Y)) --> logic'(X, bitcast(Y))
33294   if (N0.hasOneUse() && LogicOp0.getOpcode() == ISD::BITCAST &&
33295       LogicOp0.hasOneUse() && LogicOp0.getOperand(0).getValueType() == VT &&
33296       !isa<ConstantSDNode>(LogicOp0.getOperand(0))) {
33297     SDValue CastedOp1 = DAG.getBitcast(VT, LogicOp1);
33298     return DAG.getNode(FPOpcode, DL0, VT, LogicOp0.getOperand(0), CastedOp1);
33299   }
33300   // bitcast(logic(X, bitcast(Y))) --> logic'(bitcast(X), Y)
33301   if (N0.hasOneUse() && LogicOp1.getOpcode() == ISD::BITCAST &&
33302       LogicOp1.hasOneUse() && LogicOp1.getOperand(0).getValueType() == VT &&
33303       !isa<ConstantSDNode>(LogicOp1.getOperand(0))) {
33304     SDValue CastedOp0 = DAG.getBitcast(VT, LogicOp0);
33305     return DAG.getNode(FPOpcode, DL0, VT, LogicOp1.getOperand(0), CastedOp0);
33306   }
33307 
33308   return SDValue();
33309 }
33310 
33311 // Given a select, detect the following pattern:
33312 // 1:    %2 = zext <N x i8> %0 to <N x i32>
33313 // 2:    %3 = zext <N x i8> %1 to <N x i32>
33314 // 3:    %4 = sub nsw <N x i32> %2, %3
33315 // 4:    %5 = icmp sgt <N x i32> %4, [0 x N] or [-1 x N]
33316 // 5:    %6 = sub nsw <N x i32> zeroinitializer, %4
33317 // 6:    %7 = select <N x i1> %5, <N x i32> %4, <N x i32> %6
33318 // This is useful as it is the input into a SAD pattern.
detectZextAbsDiff(const SDValue & Select,SDValue & Op0,SDValue & Op1)33319 static bool detectZextAbsDiff(const SDValue &Select, SDValue &Op0,
33320                               SDValue &Op1) {
33321   // Check the condition of the select instruction is greater-than.
33322   SDValue SetCC = Select->getOperand(0);
33323   if (SetCC.getOpcode() != ISD::SETCC)
33324     return false;
33325   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
33326   if (CC != ISD::SETGT && CC != ISD::SETLT)
33327     return false;
33328 
33329   SDValue SelectOp1 = Select->getOperand(1);
33330   SDValue SelectOp2 = Select->getOperand(2);
33331 
33332   // The following instructions assume SelectOp1 is the subtraction operand
33333   // and SelectOp2 is the negation operand.
33334   // In the case of SETLT this is the other way around.
33335   if (CC == ISD::SETLT)
33336     std::swap(SelectOp1, SelectOp2);
33337 
33338   // The second operand of the select should be the negation of the first
33339   // operand, which is implemented as 0 - SelectOp1.
33340   if (!(SelectOp2.getOpcode() == ISD::SUB &&
33341         ISD::isBuildVectorAllZeros(SelectOp2.getOperand(0).getNode()) &&
33342         SelectOp2.getOperand(1) == SelectOp1))
33343     return false;
33344 
33345   // The first operand of SetCC is the first operand of the select, which is the
33346   // difference between the two input vectors.
33347   if (SetCC.getOperand(0) != SelectOp1)
33348     return false;
33349 
33350   // In SetLT case, The second operand of the comparison can be either 1 or 0.
33351   APInt SplatVal;
33352   if ((CC == ISD::SETLT) &&
33353       !((ISD::isConstantSplatVector(SetCC.getOperand(1).getNode(), SplatVal) &&
33354          SplatVal.isOneValue()) ||
33355         (ISD::isBuildVectorAllZeros(SetCC.getOperand(1).getNode()))))
33356     return false;
33357 
33358   // In SetGT case, The second operand of the comparison can be either -1 or 0.
33359   if ((CC == ISD::SETGT) &&
33360       !(ISD::isBuildVectorAllZeros(SetCC.getOperand(1).getNode()) ||
33361         ISD::isBuildVectorAllOnes(SetCC.getOperand(1).getNode())))
33362     return false;
33363 
33364   // The first operand of the select is the difference between the two input
33365   // vectors.
33366   if (SelectOp1.getOpcode() != ISD::SUB)
33367     return false;
33368 
33369   Op0 = SelectOp1.getOperand(0);
33370   Op1 = SelectOp1.getOperand(1);
33371 
33372   // Check if the operands of the sub are zero-extended from vectors of i8.
33373   if (Op0.getOpcode() != ISD::ZERO_EXTEND ||
33374       Op0.getOperand(0).getValueType().getVectorElementType() != MVT::i8 ||
33375       Op1.getOpcode() != ISD::ZERO_EXTEND ||
33376       Op1.getOperand(0).getValueType().getVectorElementType() != MVT::i8)
33377     return false;
33378 
33379   return true;
33380 }
33381 
33382 // Given two zexts of <k x i8> to <k x i32>, create a PSADBW of the inputs
33383 // to these zexts.
createPSADBW(SelectionDAG & DAG,const SDValue & Zext0,const SDValue & Zext1,const SDLoc & DL,const X86Subtarget & Subtarget)33384 static SDValue createPSADBW(SelectionDAG &DAG, const SDValue &Zext0,
33385                             const SDValue &Zext1, const SDLoc &DL,
33386                             const X86Subtarget &Subtarget) {
33387   // Find the appropriate width for the PSADBW.
33388   EVT InVT = Zext0.getOperand(0).getValueType();
33389   unsigned RegSize = std::max(128u, InVT.getSizeInBits());
33390 
33391   // "Zero-extend" the i8 vectors. This is not a per-element zext, rather we
33392   // fill in the missing vector elements with 0.
33393   unsigned NumConcat = RegSize / InVT.getSizeInBits();
33394   SmallVector<SDValue, 16> Ops(NumConcat, DAG.getConstant(0, DL, InVT));
33395   Ops[0] = Zext0.getOperand(0);
33396   MVT ExtendedVT = MVT::getVectorVT(MVT::i8, RegSize / 8);
33397   SDValue SadOp0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
33398   Ops[0] = Zext1.getOperand(0);
33399   SDValue SadOp1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
33400 
33401   // Actually build the SAD, split as 128/256/512 bits for SSE/AVX2/AVX512BW.
33402   auto PSADBWBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
33403                           ArrayRef<SDValue> Ops) {
33404     MVT VT = MVT::getVectorVT(MVT::i64, Ops[0].getValueSizeInBits() / 64);
33405     return DAG.getNode(X86ISD::PSADBW, DL, VT, Ops);
33406   };
33407   MVT SadVT = MVT::getVectorVT(MVT::i64, RegSize / 64);
33408   return SplitOpsAndApply(DAG, Subtarget, DL, SadVT, { SadOp0, SadOp1 },
33409                           PSADBWBuilder);
33410 }
33411 
33412 // Attempt to replace an min/max v8i16/v16i8 horizontal reduction with
33413 // PHMINPOSUW.
combineHorizontalMinMaxResult(SDNode * Extract,SelectionDAG & DAG,const X86Subtarget & Subtarget)33414 static SDValue combineHorizontalMinMaxResult(SDNode *Extract, SelectionDAG &DAG,
33415                                              const X86Subtarget &Subtarget) {
33416   // Bail without SSE41.
33417   if (!Subtarget.hasSSE41())
33418     return SDValue();
33419 
33420   EVT ExtractVT = Extract->getValueType(0);
33421   if (ExtractVT != MVT::i16 && ExtractVT != MVT::i8)
33422     return SDValue();
33423 
33424   // Check for SMAX/SMIN/UMAX/UMIN horizontal reduction patterns.
33425   ISD::NodeType BinOp;
33426   SDValue Src = DAG.matchBinOpReduction(
33427       Extract, BinOp, {ISD::SMAX, ISD::SMIN, ISD::UMAX, ISD::UMIN});
33428   if (!Src)
33429     return SDValue();
33430 
33431   EVT SrcVT = Src.getValueType();
33432   EVT SrcSVT = SrcVT.getScalarType();
33433   if (SrcSVT != ExtractVT || (SrcVT.getSizeInBits() % 128) != 0)
33434     return SDValue();
33435 
33436   SDLoc DL(Extract);
33437   SDValue MinPos = Src;
33438 
33439   // First, reduce the source down to 128-bit, applying BinOp to lo/hi.
33440   while (SrcVT.getSizeInBits() > 128) {
33441     unsigned NumElts = SrcVT.getVectorNumElements();
33442     unsigned NumSubElts = NumElts / 2;
33443     SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcSVT, NumSubElts);
33444     unsigned SubSizeInBits = SrcVT.getSizeInBits();
33445     SDValue Lo = extractSubVector(MinPos, 0, DAG, DL, SubSizeInBits);
33446     SDValue Hi = extractSubVector(MinPos, NumSubElts, DAG, DL, SubSizeInBits);
33447     MinPos = DAG.getNode(BinOp, DL, SrcVT, Lo, Hi);
33448   }
33449   assert(((SrcVT == MVT::v8i16 && ExtractVT == MVT::i16) ||
33450           (SrcVT == MVT::v16i8 && ExtractVT == MVT::i8)) &&
33451          "Unexpected value type");
33452 
33453   // PHMINPOSUW applies to UMIN(v8i16), for SMIN/SMAX/UMAX we must apply a mask
33454   // to flip the value accordingly.
33455   SDValue Mask;
33456   unsigned MaskEltsBits = ExtractVT.getSizeInBits();
33457   if (BinOp == ISD::SMAX)
33458     Mask = DAG.getConstant(APInt::getSignedMaxValue(MaskEltsBits), DL, SrcVT);
33459   else if (BinOp == ISD::SMIN)
33460     Mask = DAG.getConstant(APInt::getSignedMinValue(MaskEltsBits), DL, SrcVT);
33461   else if (BinOp == ISD::UMAX)
33462     Mask = DAG.getConstant(APInt::getAllOnesValue(MaskEltsBits), DL, SrcVT);
33463 
33464   if (Mask)
33465     MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
33466 
33467   // For v16i8 cases we need to perform UMIN on pairs of byte elements,
33468   // shuffling each upper element down and insert zeros. This means that the
33469   // v16i8 UMIN will leave the upper element as zero, performing zero-extension
33470   // ready for the PHMINPOS.
33471   if (ExtractVT == MVT::i8) {
33472     SDValue Upper = DAG.getVectorShuffle(
33473         SrcVT, DL, MinPos, DAG.getConstant(0, DL, MVT::v16i8),
33474         {1, 16, 3, 16, 5, 16, 7, 16, 9, 16, 11, 16, 13, 16, 15, 16});
33475     MinPos = DAG.getNode(ISD::UMIN, DL, SrcVT, MinPos, Upper);
33476   }
33477 
33478   // Perform the PHMINPOS on a v8i16 vector,
33479   MinPos = DAG.getBitcast(MVT::v8i16, MinPos);
33480   MinPos = DAG.getNode(X86ISD::PHMINPOS, DL, MVT::v8i16, MinPos);
33481   MinPos = DAG.getBitcast(SrcVT, MinPos);
33482 
33483   if (Mask)
33484     MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
33485 
33486   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, MinPos,
33487                      DAG.getIntPtrConstant(0, DL));
33488 }
33489 
33490 // Attempt to replace an all_of/any_of style horizontal reduction with a MOVMSK.
combineHorizontalPredicateResult(SDNode * Extract,SelectionDAG & DAG,const X86Subtarget & Subtarget)33491 static SDValue combineHorizontalPredicateResult(SDNode *Extract,
33492                                                 SelectionDAG &DAG,
33493                                                 const X86Subtarget &Subtarget) {
33494   // Bail without SSE2 or with AVX512VL (which uses predicate registers).
33495   if (!Subtarget.hasSSE2() || Subtarget.hasVLX())
33496     return SDValue();
33497 
33498   EVT ExtractVT = Extract->getValueType(0);
33499   unsigned BitWidth = ExtractVT.getSizeInBits();
33500   if (ExtractVT != MVT::i64 && ExtractVT != MVT::i32 && ExtractVT != MVT::i16 &&
33501       ExtractVT != MVT::i8)
33502     return SDValue();
33503 
33504   // Check for OR(any_of) and AND(all_of) horizontal reduction patterns.
33505   ISD::NodeType BinOp;
33506   SDValue Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::OR, ISD::AND});
33507   if (!Match)
33508     return SDValue();
33509 
33510   // EXTRACT_VECTOR_ELT can require implicit extension of the vector element
33511   // which we can't support here for now.
33512   if (Match.getScalarValueSizeInBits() != BitWidth)
33513     return SDValue();
33514 
33515   // We require AVX2 for PMOVMSKB for v16i16/v32i8;
33516   unsigned MatchSizeInBits = Match.getValueSizeInBits();
33517   if (!(MatchSizeInBits == 128 ||
33518         (MatchSizeInBits == 256 &&
33519          ((Subtarget.hasAVX() && BitWidth >= 32) || Subtarget.hasAVX2()))))
33520     return SDValue();
33521 
33522   // Don't bother performing this for 2-element vectors.
33523   if (Match.getValueType().getVectorNumElements() <= 2)
33524     return SDValue();
33525 
33526   // Check that we are extracting a reduction of all sign bits.
33527   if (DAG.ComputeNumSignBits(Match) != BitWidth)
33528     return SDValue();
33529 
33530   // For 32/64 bit comparisons use MOVMSKPS/MOVMSKPD, else PMOVMSKB.
33531   MVT MaskVT;
33532   if (64 == BitWidth || 32 == BitWidth)
33533     MaskVT = MVT::getVectorVT(MVT::getFloatingPointVT(BitWidth),
33534                               MatchSizeInBits / BitWidth);
33535   else
33536     MaskVT = MVT::getVectorVT(MVT::i8, MatchSizeInBits / 8);
33537 
33538   APInt CompareBits;
33539   ISD::CondCode CondCode;
33540   if (BinOp == ISD::OR) {
33541     // any_of -> MOVMSK != 0
33542     CompareBits = APInt::getNullValue(32);
33543     CondCode = ISD::CondCode::SETNE;
33544   } else {
33545     // all_of -> MOVMSK == ((1 << NumElts) - 1)
33546     CompareBits = APInt::getLowBitsSet(32, MaskVT.getVectorNumElements());
33547     CondCode = ISD::CondCode::SETEQ;
33548   }
33549 
33550   // Perform the select as i32/i64 and then truncate to avoid partial register
33551   // stalls.
33552   unsigned ResWidth = std::max(BitWidth, 32u);
33553   EVT ResVT = EVT::getIntegerVT(*DAG.getContext(), ResWidth);
33554   SDLoc DL(Extract);
33555   SDValue Zero = DAG.getConstant(0, DL, ResVT);
33556   SDValue Ones = DAG.getAllOnesConstant(DL, ResVT);
33557   SDValue Res = DAG.getBitcast(MaskVT, Match);
33558   Res = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Res);
33559   Res = DAG.getSelectCC(DL, Res, DAG.getConstant(CompareBits, DL, MVT::i32),
33560                         Ones, Zero, CondCode);
33561   return DAG.getSExtOrTrunc(Res, DL, ExtractVT);
33562 }
33563 
combineBasicSADPattern(SDNode * Extract,SelectionDAG & DAG,const X86Subtarget & Subtarget)33564 static SDValue combineBasicSADPattern(SDNode *Extract, SelectionDAG &DAG,
33565                                       const X86Subtarget &Subtarget) {
33566   // PSADBW is only supported on SSE2 and up.
33567   if (!Subtarget.hasSSE2())
33568     return SDValue();
33569 
33570   // Verify the type we're extracting from is any integer type above i16.
33571   EVT VT = Extract->getOperand(0).getValueType();
33572   if (!VT.isSimple() || !(VT.getVectorElementType().getSizeInBits() > 16))
33573     return SDValue();
33574 
33575   unsigned RegSize = 128;
33576   if (Subtarget.useBWIRegs())
33577     RegSize = 512;
33578   else if (Subtarget.hasAVX())
33579     RegSize = 256;
33580 
33581   // We handle upto v16i* for SSE2 / v32i* for AVX / v64i* for AVX512.
33582   // TODO: We should be able to handle larger vectors by splitting them before
33583   // feeding them into several SADs, and then reducing over those.
33584   if (RegSize / VT.getVectorNumElements() < 8)
33585     return SDValue();
33586 
33587   // Match shuffle + add pyramid.
33588   ISD::NodeType BinOp;
33589   SDValue Root = DAG.matchBinOpReduction(Extract, BinOp, {ISD::ADD});
33590 
33591   // The operand is expected to be zero extended from i8
33592   // (verified in detectZextAbsDiff).
33593   // In order to convert to i64 and above, additional any/zero/sign
33594   // extend is expected.
33595   // The zero extend from 32 bit has no mathematical effect on the result.
33596   // Also the sign extend is basically zero extend
33597   // (extends the sign bit which is zero).
33598   // So it is correct to skip the sign/zero extend instruction.
33599   if (Root && (Root.getOpcode() == ISD::SIGN_EXTEND ||
33600     Root.getOpcode() == ISD::ZERO_EXTEND ||
33601     Root.getOpcode() == ISD::ANY_EXTEND))
33602     Root = Root.getOperand(0);
33603 
33604   // If there was a match, we want Root to be a select that is the root of an
33605   // abs-diff pattern.
33606   if (!Root || (Root.getOpcode() != ISD::VSELECT))
33607     return SDValue();
33608 
33609   // Check whether we have an abs-diff pattern feeding into the select.
33610   SDValue Zext0, Zext1;
33611   if (!detectZextAbsDiff(Root, Zext0, Zext1))
33612     return SDValue();
33613 
33614   // Create the SAD instruction.
33615   SDLoc DL(Extract);
33616   SDValue SAD = createPSADBW(DAG, Zext0, Zext1, DL, Subtarget);
33617 
33618   // If the original vector was wider than 8 elements, sum over the results
33619   // in the SAD vector.
33620   unsigned Stages = Log2_32(VT.getVectorNumElements());
33621   MVT SadVT = SAD.getSimpleValueType();
33622   if (Stages > 3) {
33623     unsigned SadElems = SadVT.getVectorNumElements();
33624 
33625     for(unsigned i = Stages - 3; i > 0; --i) {
33626       SmallVector<int, 16> Mask(SadElems, -1);
33627       for(unsigned j = 0, MaskEnd = 1 << (i - 1); j < MaskEnd; ++j)
33628         Mask[j] = MaskEnd + j;
33629 
33630       SDValue Shuffle =
33631           DAG.getVectorShuffle(SadVT, DL, SAD, DAG.getUNDEF(SadVT), Mask);
33632       SAD = DAG.getNode(ISD::ADD, DL, SadVT, SAD, Shuffle);
33633     }
33634   }
33635 
33636   MVT Type = Extract->getSimpleValueType(0);
33637   unsigned TypeSizeInBits = Type.getSizeInBits();
33638   // Return the lowest TypeSizeInBits bits.
33639   MVT ResVT = MVT::getVectorVT(Type, SadVT.getSizeInBits() / TypeSizeInBits);
33640   SAD = DAG.getBitcast(ResVT, SAD);
33641   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, Type, SAD,
33642                      Extract->getOperand(1));
33643 }
33644 
33645 // Attempt to peek through a target shuffle and extract the scalar from the
33646 // source.
combineExtractWithShuffle(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)33647 static SDValue combineExtractWithShuffle(SDNode *N, SelectionDAG &DAG,
33648                                          TargetLowering::DAGCombinerInfo &DCI,
33649                                          const X86Subtarget &Subtarget) {
33650   if (DCI.isBeforeLegalizeOps())
33651     return SDValue();
33652 
33653   SDValue Src = N->getOperand(0);
33654   SDValue Idx = N->getOperand(1);
33655 
33656   EVT VT = N->getValueType(0);
33657   EVT SrcVT = Src.getValueType();
33658   EVT SrcSVT = SrcVT.getVectorElementType();
33659   unsigned NumSrcElts = SrcVT.getVectorNumElements();
33660 
33661   // Don't attempt this for boolean mask vectors or unknown extraction indices.
33662   if (SrcSVT == MVT::i1 || !isa<ConstantSDNode>(Idx))
33663     return SDValue();
33664 
33665   // Handle extract(broadcast(scalar_value)), it doesn't matter what index is.
33666   if (X86ISD::VBROADCAST == Src.getOpcode() &&
33667       Src.getOperand(0).getValueType() == VT)
33668     return Src.getOperand(0);
33669 
33670   // Resolve the target shuffle inputs and mask.
33671   SmallVector<int, 16> Mask;
33672   SmallVector<SDValue, 2> Ops;
33673   if (!resolveTargetShuffleInputs(peekThroughBitcasts(Src), Ops, Mask, DAG))
33674     return SDValue();
33675 
33676   // Attempt to narrow/widen the shuffle mask to the correct size.
33677   if (Mask.size() != NumSrcElts) {
33678     if ((NumSrcElts % Mask.size()) == 0) {
33679       SmallVector<int, 16> ScaledMask;
33680       int Scale = NumSrcElts / Mask.size();
33681       scaleShuffleMask<int>(Scale, Mask, ScaledMask);
33682       Mask = std::move(ScaledMask);
33683     } else if ((Mask.size() % NumSrcElts) == 0) {
33684       // Simplify Mask based on demanded element.
33685       int ExtractIdx = (int)N->getConstantOperandVal(1);
33686       int Scale = Mask.size() / NumSrcElts;
33687       int Lo = Scale * ExtractIdx;
33688       int Hi = Scale * (ExtractIdx + 1);
33689       for (int i = 0, e = (int)Mask.size(); i != e; ++i)
33690         if (i < Lo || Hi <= i)
33691           Mask[i] = SM_SentinelUndef;
33692 
33693       SmallVector<int, 16> WidenedMask;
33694       while (Mask.size() > NumSrcElts &&
33695              canWidenShuffleElements(Mask, WidenedMask))
33696         Mask = std::move(WidenedMask);
33697       // TODO - investigate support for wider shuffle masks with known upper
33698       // undef/zero elements for implicit zero-extension.
33699     }
33700   }
33701 
33702   // Check if narrowing/widening failed.
33703   if (Mask.size() != NumSrcElts)
33704     return SDValue();
33705 
33706   int SrcIdx = Mask[N->getConstantOperandVal(1)];
33707   SDLoc dl(N);
33708 
33709   // If the shuffle source element is undef/zero then we can just accept it.
33710   if (SrcIdx == SM_SentinelUndef)
33711     return DAG.getUNDEF(VT);
33712 
33713   if (SrcIdx == SM_SentinelZero)
33714     return VT.isFloatingPoint() ? DAG.getConstantFP(0.0, dl, VT)
33715                                 : DAG.getConstant(0, dl, VT);
33716 
33717   SDValue SrcOp = Ops[SrcIdx / Mask.size()];
33718   SrcOp = DAG.getBitcast(SrcVT, SrcOp);
33719   SrcIdx = SrcIdx % Mask.size();
33720 
33721   // We can only extract other elements from 128-bit vectors and in certain
33722   // circumstances, depending on SSE-level.
33723   // TODO: Investigate using extract_subvector for larger vectors.
33724   // TODO: Investigate float/double extraction if it will be just stored.
33725   if ((SrcVT == MVT::v4i32 || SrcVT == MVT::v2i64) &&
33726       ((SrcIdx == 0 && Subtarget.hasSSE2()) || Subtarget.hasSSE41())) {
33727     assert(SrcSVT == VT && "Unexpected extraction type");
33728     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcSVT, SrcOp,
33729                        DAG.getIntPtrConstant(SrcIdx, dl));
33730   }
33731 
33732   if ((SrcVT == MVT::v8i16 && Subtarget.hasSSE2()) ||
33733       (SrcVT == MVT::v16i8 && Subtarget.hasSSE41())) {
33734     assert(VT.getSizeInBits() >= SrcSVT.getSizeInBits() &&
33735            "Unexpected extraction type");
33736     unsigned OpCode = (SrcVT == MVT::v8i16 ? X86ISD::PEXTRW : X86ISD::PEXTRB);
33737     SDValue ExtOp = DAG.getNode(OpCode, dl, MVT::i32, SrcOp,
33738                                 DAG.getIntPtrConstant(SrcIdx, dl));
33739     return DAG.getZExtOrTrunc(ExtOp, dl, VT);
33740   }
33741 
33742   return SDValue();
33743 }
33744 
33745 /// Detect vector gather/scatter index generation and convert it from being a
33746 /// bunch of shuffles and extracts into a somewhat faster sequence.
33747 /// For i686, the best sequence is apparently storing the value and loading
33748 /// scalars back, while for x64 we should use 64-bit extracts and shifts.
combineExtractVectorElt(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)33749 static SDValue combineExtractVectorElt(SDNode *N, SelectionDAG &DAG,
33750                                        TargetLowering::DAGCombinerInfo &DCI,
33751                                        const X86Subtarget &Subtarget) {
33752   if (SDValue NewOp = combineExtractWithShuffle(N, DAG, DCI, Subtarget))
33753     return NewOp;
33754 
33755   // TODO - Remove this once we can handle the implicit zero-extension of
33756   // X86ISD::PEXTRW/X86ISD::PEXTRB in:
33757   // XFormVExtractWithShuffleIntoLoad, combineHorizontalPredicateResult and
33758   // combineBasicSADPattern.
33759   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
33760     return SDValue();
33761 
33762   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
33763     return NewOp;
33764 
33765   SDValue InputVector = N->getOperand(0);
33766   SDValue EltIdx = N->getOperand(1);
33767 
33768   EVT SrcVT = InputVector.getValueType();
33769   EVT VT = N->getValueType(0);
33770   SDLoc dl(InputVector);
33771 
33772   // Detect mmx extraction of all bits as a i64. It works better as a bitcast.
33773   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
33774       VT == MVT::i64 && SrcVT == MVT::v1i64 && isNullConstant(EltIdx)) {
33775     SDValue MMXSrc = InputVector.getOperand(0);
33776 
33777     // The bitcast source is a direct mmx result.
33778     if (MMXSrc.getValueType() == MVT::x86mmx)
33779       return DAG.getBitcast(VT, InputVector);
33780   }
33781 
33782   // Detect mmx to i32 conversion through a v2i32 elt extract.
33783   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
33784       VT == MVT::i32 && SrcVT == MVT::v2i32 && isNullConstant(EltIdx)) {
33785     SDValue MMXSrc = InputVector.getOperand(0);
33786 
33787     // The bitcast source is a direct mmx result.
33788     if (MMXSrc.getValueType() == MVT::x86mmx)
33789       return DAG.getNode(X86ISD::MMX_MOVD2W, dl, MVT::i32, MMXSrc);
33790   }
33791 
33792   if (VT == MVT::i1 && InputVector.getOpcode() == ISD::BITCAST &&
33793       isa<ConstantSDNode>(EltIdx) &&
33794       isa<ConstantSDNode>(InputVector.getOperand(0))) {
33795     uint64_t ExtractedElt = N->getConstantOperandVal(1);
33796     auto *InputC = cast<ConstantSDNode>(InputVector.getOperand(0));
33797     const APInt &InputValue = InputC->getAPIntValue();
33798     uint64_t Res = InputValue[ExtractedElt];
33799     return DAG.getConstant(Res, dl, MVT::i1);
33800   }
33801 
33802   // Check whether this extract is the root of a sum of absolute differences
33803   // pattern. This has to be done here because we really want it to happen
33804   // pre-legalization,
33805   if (SDValue SAD = combineBasicSADPattern(N, DAG, Subtarget))
33806     return SAD;
33807 
33808   // Attempt to replace an all_of/any_of horizontal reduction with a MOVMSK.
33809   if (SDValue Cmp = combineHorizontalPredicateResult(N, DAG, Subtarget))
33810     return Cmp;
33811 
33812   // Attempt to replace min/max v8i16/v16i8 reductions with PHMINPOSUW.
33813   if (SDValue MinMax = combineHorizontalMinMaxResult(N, DAG, Subtarget))
33814     return MinMax;
33815 
33816   return SDValue();
33817 }
33818 
33819 /// If a vector select has an operand that is -1 or 0, try to simplify the
33820 /// select to a bitwise logic operation.
33821 /// TODO: Move to DAGCombiner, possibly using TargetLowering::hasAndNot()?
33822 static SDValue
combineVSelectWithAllOnesOrZeros(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)33823 combineVSelectWithAllOnesOrZeros(SDNode *N, SelectionDAG &DAG,
33824                                  TargetLowering::DAGCombinerInfo &DCI,
33825                                  const X86Subtarget &Subtarget) {
33826   SDValue Cond = N->getOperand(0);
33827   SDValue LHS = N->getOperand(1);
33828   SDValue RHS = N->getOperand(2);
33829   EVT VT = LHS.getValueType();
33830   EVT CondVT = Cond.getValueType();
33831   SDLoc DL(N);
33832   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
33833 
33834   if (N->getOpcode() != ISD::VSELECT)
33835     return SDValue();
33836 
33837   assert(CondVT.isVector() && "Vector select expects a vector selector!");
33838 
33839   bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
33840   // Check if the first operand is all zeros and Cond type is vXi1.
33841   // This situation only applies to avx512.
33842   if (TValIsAllZeros  && Subtarget.hasAVX512() && Cond.hasOneUse() &&
33843       CondVT.getVectorElementType() == MVT::i1) {
33844     // Invert the cond to not(cond) : xor(op,allones)=not(op)
33845     SDValue CondNew = DAG.getNOT(DL, Cond, CondVT);
33846     // Vselect cond, op1, op2 = Vselect not(cond), op2, op1
33847     return DAG.getSelect(DL, VT, CondNew, RHS, LHS);
33848   }
33849 
33850   // To use the condition operand as a bitwise mask, it must have elements that
33851   // are the same size as the select elements. Ie, the condition operand must
33852   // have already been promoted from the IR select condition type <N x i1>.
33853   // Don't check if the types themselves are equal because that excludes
33854   // vector floating-point selects.
33855   if (CondVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
33856     return SDValue();
33857 
33858   bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
33859   bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
33860 
33861   // Try to invert the condition if true value is not all 1s and false value is
33862   // not all 0s.
33863   if (!TValIsAllOnes && !FValIsAllZeros &&
33864       // Check if the selector will be produced by CMPP*/PCMP*.
33865       Cond.getOpcode() == ISD::SETCC &&
33866       // Check if SETCC has already been promoted.
33867       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
33868           CondVT) {
33869     bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
33870 
33871     if (TValIsAllZeros || FValIsAllOnes) {
33872       SDValue CC = Cond.getOperand(2);
33873       ISD::CondCode NewCC =
33874           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
33875                                Cond.getOperand(0).getValueType().isInteger());
33876       Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1),
33877                           NewCC);
33878       std::swap(LHS, RHS);
33879       TValIsAllOnes = FValIsAllOnes;
33880       FValIsAllZeros = TValIsAllZeros;
33881     }
33882   }
33883 
33884   // Cond value must be 'sign splat' to be converted to a logical op.
33885   if (DAG.ComputeNumSignBits(Cond) != CondVT.getScalarSizeInBits())
33886     return SDValue();
33887 
33888   // vselect Cond, 111..., 000... -> Cond
33889   if (TValIsAllOnes && FValIsAllZeros)
33890     return DAG.getBitcast(VT, Cond);
33891 
33892   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(CondVT))
33893     return SDValue();
33894 
33895   // vselect Cond, 111..., X -> or Cond, X
33896   if (TValIsAllOnes) {
33897     SDValue CastRHS = DAG.getBitcast(CondVT, RHS);
33898     SDValue Or = DAG.getNode(ISD::OR, DL, CondVT, Cond, CastRHS);
33899     return DAG.getBitcast(VT, Or);
33900   }
33901 
33902   // vselect Cond, X, 000... -> and Cond, X
33903   if (FValIsAllZeros) {
33904     SDValue CastLHS = DAG.getBitcast(CondVT, LHS);
33905     SDValue And = DAG.getNode(ISD::AND, DL, CondVT, Cond, CastLHS);
33906     return DAG.getBitcast(VT, And);
33907   }
33908 
33909   // vselect Cond, 000..., X -> andn Cond, X
33910   if (TValIsAllZeros) {
33911     MVT AndNVT = MVT::getVectorVT(MVT::i64, CondVT.getSizeInBits() / 64);
33912     SDValue CastCond = DAG.getBitcast(AndNVT, Cond);
33913     SDValue CastRHS = DAG.getBitcast(AndNVT, RHS);
33914     SDValue AndN = DAG.getNode(X86ISD::ANDNP, DL, AndNVT, CastCond, CastRHS);
33915     return DAG.getBitcast(VT, AndN);
33916   }
33917 
33918   return SDValue();
33919 }
33920 
combineSelectOfTwoConstants(SDNode * N,SelectionDAG & DAG)33921 static SDValue combineSelectOfTwoConstants(SDNode *N, SelectionDAG &DAG) {
33922   SDValue Cond = N->getOperand(0);
33923   SDValue LHS = N->getOperand(1);
33924   SDValue RHS = N->getOperand(2);
33925   SDLoc DL(N);
33926 
33927   auto *TrueC = dyn_cast<ConstantSDNode>(LHS);
33928   auto *FalseC = dyn_cast<ConstantSDNode>(RHS);
33929   if (!TrueC || !FalseC)
33930     return SDValue();
33931 
33932   // Don't do this for crazy integer types.
33933   EVT VT = N->getValueType(0);
33934   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
33935     return SDValue();
33936 
33937   // We're going to use the condition bit in math or logic ops. We could allow
33938   // this with a wider condition value (post-legalization it becomes an i8),
33939   // but if nothing is creating selects that late, it doesn't matter.
33940   if (Cond.getValueType() != MVT::i1)
33941     return SDValue();
33942 
33943   // A power-of-2 multiply is just a shift. LEA also cheaply handles multiply by
33944   // 3, 5, or 9 with i32/i64, so those get transformed too.
33945   // TODO: For constants that overflow or do not differ by power-of-2 or small
33946   // multiplier, convert to 'and' + 'add'.
33947   const APInt &TrueVal = TrueC->getAPIntValue();
33948   const APInt &FalseVal = FalseC->getAPIntValue();
33949   bool OV;
33950   APInt Diff = TrueVal.ssub_ov(FalseVal, OV);
33951   if (OV)
33952     return SDValue();
33953 
33954   APInt AbsDiff = Diff.abs();
33955   if (AbsDiff.isPowerOf2() ||
33956       ((VT == MVT::i32 || VT == MVT::i64) &&
33957        (AbsDiff == 3 || AbsDiff == 5 || AbsDiff == 9))) {
33958 
33959     // We need a positive multiplier constant for shift/LEA codegen. The 'not'
33960     // of the condition can usually be folded into a compare predicate, but even
33961     // without that, the sequence should be cheaper than a CMOV alternative.
33962     if (TrueVal.slt(FalseVal)) {
33963       Cond = DAG.getNOT(DL, Cond, MVT::i1);
33964       std::swap(TrueC, FalseC);
33965     }
33966 
33967     // select Cond, TC, FC --> (zext(Cond) * (TC - FC)) + FC
33968     SDValue R = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
33969 
33970     // Multiply condition by the difference if non-one.
33971     if (!AbsDiff.isOneValue())
33972       R = DAG.getNode(ISD::MUL, DL, VT, R, DAG.getConstant(AbsDiff, DL, VT));
33973 
33974     // Add the base if non-zero.
33975     if (!FalseC->isNullValue())
33976       R = DAG.getNode(ISD::ADD, DL, VT, R, SDValue(FalseC, 0));
33977 
33978     return R;
33979   }
33980 
33981   return SDValue();
33982 }
33983 
33984 /// If this is a *dynamic* select (non-constant condition) and we can match
33985 /// this node with one of the variable blend instructions, restructure the
33986 /// condition so that blends can use the high (sign) bit of each element.
33987 /// This function will also call SimplfiyDemandedBits on already created
33988 /// BLENDV to perform additional simplifications.
combineVSelectToBLENDV(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)33989 static SDValue combineVSelectToBLENDV(SDNode *N, SelectionDAG &DAG,
33990                                            TargetLowering::DAGCombinerInfo &DCI,
33991                                            const X86Subtarget &Subtarget) {
33992   SDValue Cond = N->getOperand(0);
33993   if ((N->getOpcode() != ISD::VSELECT &&
33994        N->getOpcode() != X86ISD::BLENDV) ||
33995       ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
33996     return SDValue();
33997 
33998   // Don't optimize before the condition has been transformed to a legal type
33999   // and don't ever optimize vector selects that map to AVX512 mask-registers.
34000   unsigned BitWidth = Cond.getScalarValueSizeInBits();
34001   if (BitWidth < 8 || BitWidth > 64)
34002     return SDValue();
34003 
34004   // We can only handle the cases where VSELECT is directly legal on the
34005   // subtarget. We custom lower VSELECT nodes with constant conditions and
34006   // this makes it hard to see whether a dynamic VSELECT will correctly
34007   // lower, so we both check the operation's status and explicitly handle the
34008   // cases where a *dynamic* blend will fail even though a constant-condition
34009   // blend could be custom lowered.
34010   // FIXME: We should find a better way to handle this class of problems.
34011   // Potentially, we should combine constant-condition vselect nodes
34012   // pre-legalization into shuffles and not mark as many types as custom
34013   // lowered.
34014   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
34015   EVT VT = N->getValueType(0);
34016   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
34017     return SDValue();
34018   // FIXME: We don't support i16-element blends currently. We could and
34019   // should support them by making *all* the bits in the condition be set
34020   // rather than just the high bit and using an i8-element blend.
34021   if (VT.getVectorElementType() == MVT::i16)
34022     return SDValue();
34023   // Dynamic blending was only available from SSE4.1 onward.
34024   if (VT.is128BitVector() && !Subtarget.hasSSE41())
34025     return SDValue();
34026   // Byte blends are only available in AVX2
34027   if (VT == MVT::v32i8 && !Subtarget.hasAVX2())
34028     return SDValue();
34029   // There are no 512-bit blend instructions that use sign bits.
34030   if (VT.is512BitVector())
34031     return SDValue();
34032 
34033   // TODO: Add other opcodes eventually lowered into BLEND.
34034   for (SDNode::use_iterator UI = Cond->use_begin(), UE = Cond->use_end();
34035        UI != UE; ++UI)
34036     if ((UI->getOpcode() != ISD::VSELECT &&
34037          UI->getOpcode() != X86ISD::BLENDV) ||
34038         UI.getOperandNo() != 0)
34039       return SDValue();
34040 
34041   APInt DemandedMask(APInt::getSignMask(BitWidth));
34042   KnownBits Known;
34043   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
34044                                         !DCI.isBeforeLegalizeOps());
34045   if (!TLI.SimplifyDemandedBits(Cond, DemandedMask, Known, TLO, 0, true))
34046     return SDValue();
34047 
34048   // If we changed the computation somewhere in the DAG, this change will
34049   // affect all users of Cond. Update all the nodes so that we do not use
34050   // the generic VSELECT anymore. Otherwise, we may perform wrong
34051   // optimizations as we messed with the actual expectation for the vector
34052   // boolean values.
34053   for (SDNode *U : Cond->uses()) {
34054     if (U->getOpcode() == X86ISD::BLENDV)
34055       continue;
34056 
34057     SDValue SB = DAG.getNode(X86ISD::BLENDV, SDLoc(U), U->getValueType(0),
34058                              Cond, U->getOperand(1), U->getOperand(2));
34059     DAG.ReplaceAllUsesOfValueWith(SDValue(U, 0), SB);
34060     DCI.AddToWorklist(U);
34061   }
34062   DCI.CommitTargetLoweringOpt(TLO);
34063   return SDValue(N, 0);
34064 }
34065 
34066 /// Do target-specific dag combines on SELECT and VSELECT nodes.
combineSelect(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)34067 static SDValue combineSelect(SDNode *N, SelectionDAG &DAG,
34068                              TargetLowering::DAGCombinerInfo &DCI,
34069                              const X86Subtarget &Subtarget) {
34070   SDLoc DL(N);
34071   SDValue Cond = N->getOperand(0);
34072   SDValue LHS = N->getOperand(1);
34073   SDValue RHS = N->getOperand(2);
34074 
34075   // Try simplification again because we use this function to optimize
34076   // BLENDV nodes that are not handled by the generic combiner.
34077   if (SDValue V = DAG.simplifySelect(Cond, LHS, RHS))
34078     return V;
34079 
34080   EVT VT = LHS.getValueType();
34081   EVT CondVT = Cond.getValueType();
34082   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
34083 
34084   // Convert vselects with constant condition into shuffles.
34085   if (ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()) &&
34086       DCI.isBeforeLegalizeOps()) {
34087     SmallVector<int, 64> Mask;
34088     if (createShuffleMaskFromVSELECT(Mask, Cond))
34089       return DAG.getVectorShuffle(VT, DL, LHS, RHS, Mask);
34090   }
34091 
34092   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
34093   // instructions match the semantics of the common C idiom x<y?x:y but not
34094   // x<=y?x:y, because of how they handle negative zero (which can be
34095   // ignored in unsafe-math mode).
34096   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
34097   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
34098       VT != MVT::f80 && VT != MVT::f128 &&
34099       (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
34100       (Subtarget.hasSSE2() ||
34101        (Subtarget.hasSSE1() && VT.getScalarType() == MVT::f32))) {
34102     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
34103 
34104     unsigned Opcode = 0;
34105     // Check for x CC y ? x : y.
34106     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
34107         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
34108       switch (CC) {
34109       default: break;
34110       case ISD::SETULT:
34111         // Converting this to a min would handle NaNs incorrectly, and swapping
34112         // the operands would cause it to handle comparisons between positive
34113         // and negative zero incorrectly.
34114         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
34115           if (!DAG.getTarget().Options.UnsafeFPMath &&
34116               !(DAG.isKnownNeverZeroFloat(LHS) ||
34117                 DAG.isKnownNeverZeroFloat(RHS)))
34118             break;
34119           std::swap(LHS, RHS);
34120         }
34121         Opcode = X86ISD::FMIN;
34122         break;
34123       case ISD::SETOLE:
34124         // Converting this to a min would handle comparisons between positive
34125         // and negative zero incorrectly.
34126         if (!DAG.getTarget().Options.UnsafeFPMath &&
34127             !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
34128           break;
34129         Opcode = X86ISD::FMIN;
34130         break;
34131       case ISD::SETULE:
34132         // Converting this to a min would handle both negative zeros and NaNs
34133         // incorrectly, but we can swap the operands to fix both.
34134         std::swap(LHS, RHS);
34135         LLVM_FALLTHROUGH;
34136       case ISD::SETOLT:
34137       case ISD::SETLT:
34138       case ISD::SETLE:
34139         Opcode = X86ISD::FMIN;
34140         break;
34141 
34142       case ISD::SETOGE:
34143         // Converting this to a max would handle comparisons between positive
34144         // and negative zero incorrectly.
34145         if (!DAG.getTarget().Options.UnsafeFPMath &&
34146             !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
34147           break;
34148         Opcode = X86ISD::FMAX;
34149         break;
34150       case ISD::SETUGT:
34151         // Converting this to a max would handle NaNs incorrectly, and swapping
34152         // the operands would cause it to handle comparisons between positive
34153         // and negative zero incorrectly.
34154         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
34155           if (!DAG.getTarget().Options.UnsafeFPMath &&
34156               !(DAG.isKnownNeverZeroFloat(LHS) ||
34157                 DAG.isKnownNeverZeroFloat(RHS)))
34158             break;
34159           std::swap(LHS, RHS);
34160         }
34161         Opcode = X86ISD::FMAX;
34162         break;
34163       case ISD::SETUGE:
34164         // Converting this to a max would handle both negative zeros and NaNs
34165         // incorrectly, but we can swap the operands to fix both.
34166         std::swap(LHS, RHS);
34167         LLVM_FALLTHROUGH;
34168       case ISD::SETOGT:
34169       case ISD::SETGT:
34170       case ISD::SETGE:
34171         Opcode = X86ISD::FMAX;
34172         break;
34173       }
34174     // Check for x CC y ? y : x -- a min/max with reversed arms.
34175     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
34176                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
34177       switch (CC) {
34178       default: break;
34179       case ISD::SETOGE:
34180         // Converting this to a min would handle comparisons between positive
34181         // and negative zero incorrectly, and swapping the operands would
34182         // cause it to handle NaNs incorrectly.
34183         if (!DAG.getTarget().Options.UnsafeFPMath &&
34184             !(DAG.isKnownNeverZeroFloat(LHS) ||
34185               DAG.isKnownNeverZeroFloat(RHS))) {
34186           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
34187             break;
34188           std::swap(LHS, RHS);
34189         }
34190         Opcode = X86ISD::FMIN;
34191         break;
34192       case ISD::SETUGT:
34193         // Converting this to a min would handle NaNs incorrectly.
34194         if (!DAG.getTarget().Options.UnsafeFPMath &&
34195             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
34196           break;
34197         Opcode = X86ISD::FMIN;
34198         break;
34199       case ISD::SETUGE:
34200         // Converting this to a min would handle both negative zeros and NaNs
34201         // incorrectly, but we can swap the operands to fix both.
34202         std::swap(LHS, RHS);
34203         LLVM_FALLTHROUGH;
34204       case ISD::SETOGT:
34205       case ISD::SETGT:
34206       case ISD::SETGE:
34207         Opcode = X86ISD::FMIN;
34208         break;
34209 
34210       case ISD::SETULT:
34211         // Converting this to a max would handle NaNs incorrectly.
34212         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
34213           break;
34214         Opcode = X86ISD::FMAX;
34215         break;
34216       case ISD::SETOLE:
34217         // Converting this to a max would handle comparisons between positive
34218         // and negative zero incorrectly, and swapping the operands would
34219         // cause it to handle NaNs incorrectly.
34220         if (!DAG.getTarget().Options.UnsafeFPMath &&
34221             !DAG.isKnownNeverZeroFloat(LHS) &&
34222             !DAG.isKnownNeverZeroFloat(RHS)) {
34223           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
34224             break;
34225           std::swap(LHS, RHS);
34226         }
34227         Opcode = X86ISD::FMAX;
34228         break;
34229       case ISD::SETULE:
34230         // Converting this to a max would handle both negative zeros and NaNs
34231         // incorrectly, but we can swap the operands to fix both.
34232         std::swap(LHS, RHS);
34233         LLVM_FALLTHROUGH;
34234       case ISD::SETOLT:
34235       case ISD::SETLT:
34236       case ISD::SETLE:
34237         Opcode = X86ISD::FMAX;
34238         break;
34239       }
34240     }
34241 
34242     if (Opcode)
34243       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
34244   }
34245 
34246   // Some mask scalar intrinsics rely on checking if only one bit is set
34247   // and implement it in C code like this:
34248   // A[0] = (U & 1) ? A[0] : W[0];
34249   // This creates some redundant instructions that break pattern matching.
34250   // fold (select (setcc (and (X, 1), 0, seteq), Y, Z)) -> select(and(X, 1),Z,Y)
34251   if (Subtarget.hasAVX512() && N->getOpcode() == ISD::SELECT &&
34252       Cond.getOpcode() == ISD::SETCC && (VT == MVT::f32 || VT == MVT::f64)) {
34253     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
34254     SDValue AndNode = Cond.getOperand(0);
34255     if (AndNode.getOpcode() == ISD::AND && CC == ISD::SETEQ &&
34256         isNullConstant(Cond.getOperand(1)) &&
34257         isOneConstant(AndNode.getOperand(1))) {
34258       // LHS and RHS swapped due to
34259       // setcc outputting 1 when AND resulted in 0 and vice versa.
34260       AndNode = DAG.getZExtOrTrunc(AndNode, DL, MVT::i8);
34261       return DAG.getNode(ISD::SELECT, DL, VT, AndNode, RHS, LHS);
34262     }
34263   }
34264 
34265   // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
34266   // lowering on KNL. In this case we convert it to
34267   // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
34268   // The same situation all vectors of i8 and i16 without BWI.
34269   // Make sure we extend these even before type legalization gets a chance to
34270   // split wide vectors.
34271   // Since SKX these selects have a proper lowering.
34272   if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && CondVT.isVector() &&
34273       CondVT.getVectorElementType() == MVT::i1 &&
34274       (ExperimentalVectorWideningLegalization ||
34275        VT.getVectorNumElements() > 4) &&
34276       (VT.getVectorElementType() == MVT::i8 ||
34277        VT.getVectorElementType() == MVT::i16)) {
34278     Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
34279     return DAG.getNode(N->getOpcode(), DL, VT, Cond, LHS, RHS);
34280   }
34281 
34282   if (SDValue V = combineSelectOfTwoConstants(N, DAG))
34283     return V;
34284 
34285   // Canonicalize max and min:
34286   // (x > y) ? x : y -> (x >= y) ? x : y
34287   // (x < y) ? x : y -> (x <= y) ? x : y
34288   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
34289   // the need for an extra compare
34290   // against zero. e.g.
34291   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
34292   // subl   %esi, %edi
34293   // testl  %edi, %edi
34294   // movl   $0, %eax
34295   // cmovgl %edi, %eax
34296   // =>
34297   // xorl   %eax, %eax
34298   // subl   %esi, $edi
34299   // cmovsl %eax, %edi
34300   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
34301       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
34302       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
34303     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
34304     switch (CC) {
34305     default: break;
34306     case ISD::SETLT:
34307     case ISD::SETGT: {
34308       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
34309       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
34310                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
34311       return DAG.getSelect(DL, VT, Cond, LHS, RHS);
34312     }
34313     }
34314   }
34315 
34316   // Match VSELECTs into subs with unsigned saturation.
34317   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
34318       // psubus is available in SSE2 for i8 and i16 vectors.
34319       Subtarget.hasSSE2() && VT.getVectorNumElements() >= 2 &&
34320       isPowerOf2_32(VT.getVectorNumElements()) &&
34321       (VT.getVectorElementType() == MVT::i8 ||
34322        VT.getVectorElementType() == MVT::i16)) {
34323     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
34324 
34325     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
34326     // left side invert the predicate to simplify logic below.
34327     SDValue Other;
34328     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
34329       Other = RHS;
34330       CC = ISD::getSetCCInverse(CC, true);
34331     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
34332       Other = LHS;
34333     }
34334 
34335     if (Other.getNode() && Other->getNumOperands() == 2 &&
34336         Other->getOperand(0) == Cond.getOperand(0)) {
34337       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
34338       SDValue CondRHS = Cond->getOperand(1);
34339 
34340       // Look for a general sub with unsigned saturation first.
34341       // x >= y ? x-y : 0 --> subus x, y
34342       // x >  y ? x-y : 0 --> subus x, y
34343       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
34344           Other->getOpcode() == ISD::SUB && OpRHS == CondRHS)
34345         return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
34346 
34347       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS)) {
34348         if (isa<BuildVectorSDNode>(CondRHS)) {
34349           // If the RHS is a constant we have to reverse the const
34350           // canonicalization.
34351           // x > C-1 ? x+-C : 0 --> subus x, C
34352           // TODO: Handle build_vectors with undef elements.
34353           auto MatchUSUBSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) {
34354             return Cond->getAPIntValue() == (-Op->getAPIntValue() - 1);
34355           };
34356           if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
34357               ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUSUBSAT)) {
34358             OpRHS = DAG.getNode(ISD::SUB, DL, VT,
34359                                 DAG.getConstant(0, DL, VT), OpRHS);
34360             return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
34361           }
34362 
34363           // Another special case: If C was a sign bit, the sub has been
34364           // canonicalized into a xor.
34365           // FIXME: Would it be better to use computeKnownBits to determine
34366           //        whether it's safe to decanonicalize the xor?
34367           // x s< 0 ? x^C : 0 --> subus x, C
34368           if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
34369             if (CC == ISD::SETLT && Other.getOpcode() == ISD::XOR &&
34370                 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
34371                 OpRHSConst->getAPIntValue().isSignMask()) {
34372               // Note that we have to rebuild the RHS constant here to ensure we
34373               // don't rely on particular values of undef lanes.
34374               OpRHS = DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT);
34375               return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
34376             }
34377           }
34378         }
34379       }
34380     }
34381   }
34382 
34383   // Match VSELECTs into add with unsigned saturation.
34384   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
34385       // paddus is available in SSE2 for i8 and i16 vectors.
34386       Subtarget.hasSSE2() && VT.getVectorNumElements() >= 2 &&
34387       isPowerOf2_32(VT.getVectorNumElements()) &&
34388       (VT.getVectorElementType() == MVT::i8 ||
34389        VT.getVectorElementType() == MVT::i16)) {
34390     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
34391 
34392     SDValue CondLHS = Cond->getOperand(0);
34393     SDValue CondRHS = Cond->getOperand(1);
34394 
34395     // Check if one of the arms of the VSELECT is vector with all bits set.
34396     // If it's on the left side invert the predicate to simplify logic below.
34397     SDValue Other;
34398     if (ISD::isBuildVectorAllOnes(LHS.getNode())) {
34399       Other = RHS;
34400       CC = ISD::getSetCCInverse(CC, true);
34401     } else if (ISD::isBuildVectorAllOnes(RHS.getNode())) {
34402       Other = LHS;
34403     }
34404 
34405     if (Other.getNode() && Other.getOpcode() == ISD::ADD) {
34406       SDValue OpLHS = Other.getOperand(0), OpRHS = Other.getOperand(1);
34407 
34408       // Canonicalize condition operands.
34409       if (CC == ISD::SETUGE) {
34410         std::swap(CondLHS, CondRHS);
34411         CC = ISD::SETULE;
34412       }
34413 
34414       // We can test against either of the addition operands.
34415       // x <= x+y ? x+y : ~0 --> addus x, y
34416       // x+y >= x ? x+y : ~0 --> addus x, y
34417       if (CC == ISD::SETULE && Other == CondRHS &&
34418           (OpLHS == CondLHS || OpRHS == CondLHS))
34419         return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS);
34420 
34421       if (isa<BuildVectorSDNode>(OpRHS) && isa<BuildVectorSDNode>(CondRHS) &&
34422           CondLHS == OpLHS) {
34423         // If the RHS is a constant we have to reverse the const
34424         // canonicalization.
34425         // x > ~C ? x+C : ~0 --> addus x, C
34426         auto MatchUADDSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) {
34427           return Cond->getAPIntValue() == ~Op->getAPIntValue();
34428         };
34429         if (CC == ISD::SETULE &&
34430             ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUADDSAT))
34431           return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS);
34432       }
34433     }
34434   }
34435 
34436   // Early exit check
34437   if (!TLI.isTypeLegal(VT))
34438     return SDValue();
34439 
34440   if (SDValue V = combineVSelectWithAllOnesOrZeros(N, DAG, DCI, Subtarget))
34441     return V;
34442 
34443   if (SDValue V = combineVSelectToBLENDV(N, DAG, DCI, Subtarget))
34444     return V;
34445 
34446   // Custom action for SELECT MMX
34447   if (VT == MVT::x86mmx) {
34448     LHS = DAG.getBitcast(MVT::i64, LHS);
34449     RHS = DAG.getBitcast(MVT::i64, RHS);
34450     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::i64, Cond, LHS, RHS);
34451     return DAG.getBitcast(VT, newSelect);
34452   }
34453 
34454   return SDValue();
34455 }
34456 
34457 /// Combine:
34458 ///   (brcond/cmov/setcc .., (cmp (atomic_load_add x, 1), 0), COND_S)
34459 /// to:
34460 ///   (brcond/cmov/setcc .., (LADD x, 1), COND_LE)
34461 /// i.e., reusing the EFLAGS produced by the LOCKed instruction.
34462 /// Note that this is only legal for some op/cc combinations.
combineSetCCAtomicArith(SDValue Cmp,X86::CondCode & CC,SelectionDAG & DAG,const X86Subtarget & Subtarget)34463 static SDValue combineSetCCAtomicArith(SDValue Cmp, X86::CondCode &CC,
34464                                        SelectionDAG &DAG,
34465                                        const X86Subtarget &Subtarget) {
34466   // This combine only operates on CMP-like nodes.
34467   if (!(Cmp.getOpcode() == X86ISD::CMP ||
34468         (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
34469     return SDValue();
34470 
34471   // Can't replace the cmp if it has more uses than the one we're looking at.
34472   // FIXME: We would like to be able to handle this, but would need to make sure
34473   // all uses were updated.
34474   if (!Cmp.hasOneUse())
34475     return SDValue();
34476 
34477   // This only applies to variations of the common case:
34478   //   (icmp slt x, 0) -> (icmp sle (add x, 1), 0)
34479   //   (icmp sge x, 0) -> (icmp sgt (add x, 1), 0)
34480   //   (icmp sle x, 0) -> (icmp slt (sub x, 1), 0)
34481   //   (icmp sgt x, 0) -> (icmp sge (sub x, 1), 0)
34482   // Using the proper condcodes (see below), overflow is checked for.
34483 
34484   // FIXME: We can generalize both constraints:
34485   // - XOR/OR/AND (if they were made to survive AtomicExpand)
34486   // - LHS != 1
34487   // if the result is compared.
34488 
34489   SDValue CmpLHS = Cmp.getOperand(0);
34490   SDValue CmpRHS = Cmp.getOperand(1);
34491 
34492   if (!CmpLHS.hasOneUse())
34493     return SDValue();
34494 
34495   unsigned Opc = CmpLHS.getOpcode();
34496   if (Opc != ISD::ATOMIC_LOAD_ADD && Opc != ISD::ATOMIC_LOAD_SUB)
34497     return SDValue();
34498 
34499   SDValue OpRHS = CmpLHS.getOperand(2);
34500   auto *OpRHSC = dyn_cast<ConstantSDNode>(OpRHS);
34501   if (!OpRHSC)
34502     return SDValue();
34503 
34504   APInt Addend = OpRHSC->getAPIntValue();
34505   if (Opc == ISD::ATOMIC_LOAD_SUB)
34506     Addend = -Addend;
34507 
34508   auto *CmpRHSC = dyn_cast<ConstantSDNode>(CmpRHS);
34509   if (!CmpRHSC)
34510     return SDValue();
34511 
34512   APInt Comparison = CmpRHSC->getAPIntValue();
34513 
34514   // If the addend is the negation of the comparison value, then we can do
34515   // a full comparison by emitting the atomic arithmetic as a locked sub.
34516   if (Comparison == -Addend) {
34517     // The CC is fine, but we need to rewrite the LHS of the comparison as an
34518     // atomic sub.
34519     auto *AN = cast<AtomicSDNode>(CmpLHS.getNode());
34520     auto AtomicSub = DAG.getAtomic(
34521         ISD::ATOMIC_LOAD_SUB, SDLoc(CmpLHS), CmpLHS.getValueType(),
34522         /*Chain*/ CmpLHS.getOperand(0), /*LHS*/ CmpLHS.getOperand(1),
34523         /*RHS*/ DAG.getConstant(-Addend, SDLoc(CmpRHS), CmpRHS.getValueType()),
34524         AN->getMemOperand());
34525     auto LockOp = lowerAtomicArithWithLOCK(AtomicSub, DAG, Subtarget);
34526     DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0),
34527                                   DAG.getUNDEF(CmpLHS.getValueType()));
34528     DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
34529     return LockOp;
34530   }
34531 
34532   // We can handle comparisons with zero in a number of cases by manipulating
34533   // the CC used.
34534   if (!Comparison.isNullValue())
34535     return SDValue();
34536 
34537   if (CC == X86::COND_S && Addend == 1)
34538     CC = X86::COND_LE;
34539   else if (CC == X86::COND_NS && Addend == 1)
34540     CC = X86::COND_G;
34541   else if (CC == X86::COND_G && Addend == -1)
34542     CC = X86::COND_GE;
34543   else if (CC == X86::COND_LE && Addend == -1)
34544     CC = X86::COND_L;
34545   else
34546     return SDValue();
34547 
34548   SDValue LockOp = lowerAtomicArithWithLOCK(CmpLHS, DAG, Subtarget);
34549   DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0),
34550                                 DAG.getUNDEF(CmpLHS.getValueType()));
34551   DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
34552   return LockOp;
34553 }
34554 
34555 // Check whether a boolean test is testing a boolean value generated by
34556 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
34557 // code.
34558 //
34559 // Simplify the following patterns:
34560 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
34561 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
34562 // to (Op EFLAGS Cond)
34563 //
34564 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
34565 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
34566 // to (Op EFLAGS !Cond)
34567 //
34568 // where Op could be BRCOND or CMOV.
34569 //
checkBoolTestSetCCCombine(SDValue Cmp,X86::CondCode & CC)34570 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
34571   // This combine only operates on CMP-like nodes.
34572   if (!(Cmp.getOpcode() == X86ISD::CMP ||
34573         (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
34574     return SDValue();
34575 
34576   // Quit if not used as a boolean value.
34577   if (CC != X86::COND_E && CC != X86::COND_NE)
34578     return SDValue();
34579 
34580   // Check CMP operands. One of them should be 0 or 1 and the other should be
34581   // an SetCC or extended from it.
34582   SDValue Op1 = Cmp.getOperand(0);
34583   SDValue Op2 = Cmp.getOperand(1);
34584 
34585   SDValue SetCC;
34586   const ConstantSDNode* C = nullptr;
34587   bool needOppositeCond = (CC == X86::COND_E);
34588   bool checkAgainstTrue = false; // Is it a comparison against 1?
34589 
34590   if ((C = dyn_cast<ConstantSDNode>(Op1)))
34591     SetCC = Op2;
34592   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
34593     SetCC = Op1;
34594   else // Quit if all operands are not constants.
34595     return SDValue();
34596 
34597   if (C->getZExtValue() == 1) {
34598     needOppositeCond = !needOppositeCond;
34599     checkAgainstTrue = true;
34600   } else if (C->getZExtValue() != 0)
34601     // Quit if the constant is neither 0 or 1.
34602     return SDValue();
34603 
34604   bool truncatedToBoolWithAnd = false;
34605   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
34606   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
34607          SetCC.getOpcode() == ISD::TRUNCATE ||
34608          SetCC.getOpcode() == ISD::AND) {
34609     if (SetCC.getOpcode() == ISD::AND) {
34610       int OpIdx = -1;
34611       if (isOneConstant(SetCC.getOperand(0)))
34612         OpIdx = 1;
34613       if (isOneConstant(SetCC.getOperand(1)))
34614         OpIdx = 0;
34615       if (OpIdx < 0)
34616         break;
34617       SetCC = SetCC.getOperand(OpIdx);
34618       truncatedToBoolWithAnd = true;
34619     } else
34620       SetCC = SetCC.getOperand(0);
34621   }
34622 
34623   switch (SetCC.getOpcode()) {
34624   case X86ISD::SETCC_CARRY:
34625     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
34626     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
34627     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
34628     // truncated to i1 using 'and'.
34629     if (checkAgainstTrue && !truncatedToBoolWithAnd)
34630       break;
34631     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
34632            "Invalid use of SETCC_CARRY!");
34633     LLVM_FALLTHROUGH;
34634   case X86ISD::SETCC:
34635     // Set the condition code or opposite one if necessary.
34636     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
34637     if (needOppositeCond)
34638       CC = X86::GetOppositeBranchCondition(CC);
34639     return SetCC.getOperand(1);
34640   case X86ISD::CMOV: {
34641     // Check whether false/true value has canonical one, i.e. 0 or 1.
34642     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
34643     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
34644     // Quit if true value is not a constant.
34645     if (!TVal)
34646       return SDValue();
34647     // Quit if false value is not a constant.
34648     if (!FVal) {
34649       SDValue Op = SetCC.getOperand(0);
34650       // Skip 'zext' or 'trunc' node.
34651       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
34652           Op.getOpcode() == ISD::TRUNCATE)
34653         Op = Op.getOperand(0);
34654       // A special case for rdrand/rdseed, where 0 is set if false cond is
34655       // found.
34656       if ((Op.getOpcode() != X86ISD::RDRAND &&
34657            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
34658         return SDValue();
34659     }
34660     // Quit if false value is not the constant 0 or 1.
34661     bool FValIsFalse = true;
34662     if (FVal && FVal->getZExtValue() != 0) {
34663       if (FVal->getZExtValue() != 1)
34664         return SDValue();
34665       // If FVal is 1, opposite cond is needed.
34666       needOppositeCond = !needOppositeCond;
34667       FValIsFalse = false;
34668     }
34669     // Quit if TVal is not the constant opposite of FVal.
34670     if (FValIsFalse && TVal->getZExtValue() != 1)
34671       return SDValue();
34672     if (!FValIsFalse && TVal->getZExtValue() != 0)
34673       return SDValue();
34674     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
34675     if (needOppositeCond)
34676       CC = X86::GetOppositeBranchCondition(CC);
34677     return SetCC.getOperand(3);
34678   }
34679   }
34680 
34681   return SDValue();
34682 }
34683 
34684 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
34685 /// Match:
34686 ///   (X86or (X86setcc) (X86setcc))
34687 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
checkBoolTestAndOrSetCCCombine(SDValue Cond,X86::CondCode & CC0,X86::CondCode & CC1,SDValue & Flags,bool & isAnd)34688 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
34689                                            X86::CondCode &CC1, SDValue &Flags,
34690                                            bool &isAnd) {
34691   if (Cond->getOpcode() == X86ISD::CMP) {
34692     if (!isNullConstant(Cond->getOperand(1)))
34693       return false;
34694 
34695     Cond = Cond->getOperand(0);
34696   }
34697 
34698   isAnd = false;
34699 
34700   SDValue SetCC0, SetCC1;
34701   switch (Cond->getOpcode()) {
34702   default: return false;
34703   case ISD::AND:
34704   case X86ISD::AND:
34705     isAnd = true;
34706     LLVM_FALLTHROUGH;
34707   case ISD::OR:
34708   case X86ISD::OR:
34709     SetCC0 = Cond->getOperand(0);
34710     SetCC1 = Cond->getOperand(1);
34711     break;
34712   };
34713 
34714   // Make sure we have SETCC nodes, using the same flags value.
34715   if (SetCC0.getOpcode() != X86ISD::SETCC ||
34716       SetCC1.getOpcode() != X86ISD::SETCC ||
34717       SetCC0->getOperand(1) != SetCC1->getOperand(1))
34718     return false;
34719 
34720   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
34721   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
34722   Flags = SetCC0->getOperand(1);
34723   return true;
34724 }
34725 
34726 // When legalizing carry, we create carries via add X, -1
34727 // If that comes from an actual carry, via setcc, we use the
34728 // carry directly.
combineCarryThroughADD(SDValue EFLAGS)34729 static SDValue combineCarryThroughADD(SDValue EFLAGS) {
34730   if (EFLAGS.getOpcode() == X86ISD::ADD) {
34731     if (isAllOnesConstant(EFLAGS.getOperand(1))) {
34732       SDValue Carry = EFLAGS.getOperand(0);
34733       while (Carry.getOpcode() == ISD::TRUNCATE ||
34734              Carry.getOpcode() == ISD::ZERO_EXTEND ||
34735              Carry.getOpcode() == ISD::SIGN_EXTEND ||
34736              Carry.getOpcode() == ISD::ANY_EXTEND ||
34737              (Carry.getOpcode() == ISD::AND &&
34738               isOneConstant(Carry.getOperand(1))))
34739         Carry = Carry.getOperand(0);
34740       if (Carry.getOpcode() == X86ISD::SETCC ||
34741           Carry.getOpcode() == X86ISD::SETCC_CARRY) {
34742         if (Carry.getConstantOperandVal(0) == X86::COND_B)
34743           return Carry.getOperand(1);
34744       }
34745     }
34746   }
34747 
34748   return SDValue();
34749 }
34750 
34751 /// Optimize an EFLAGS definition used according to the condition code \p CC
34752 /// into a simpler EFLAGS value, potentially returning a new \p CC and replacing
34753 /// uses of chain values.
combineSetCCEFLAGS(SDValue EFLAGS,X86::CondCode & CC,SelectionDAG & DAG,const X86Subtarget & Subtarget)34754 static SDValue combineSetCCEFLAGS(SDValue EFLAGS, X86::CondCode &CC,
34755                                   SelectionDAG &DAG,
34756                                   const X86Subtarget &Subtarget) {
34757   if (CC == X86::COND_B)
34758     if (SDValue Flags = combineCarryThroughADD(EFLAGS))
34759       return Flags;
34760 
34761   if (SDValue R = checkBoolTestSetCCCombine(EFLAGS, CC))
34762     return R;
34763   return combineSetCCAtomicArith(EFLAGS, CC, DAG, Subtarget);
34764 }
34765 
34766 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
combineCMov(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)34767 static SDValue combineCMov(SDNode *N, SelectionDAG &DAG,
34768                            TargetLowering::DAGCombinerInfo &DCI,
34769                            const X86Subtarget &Subtarget) {
34770   SDLoc DL(N);
34771 
34772   SDValue FalseOp = N->getOperand(0);
34773   SDValue TrueOp = N->getOperand(1);
34774   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
34775   SDValue Cond = N->getOperand(3);
34776 
34777   // Try to simplify the EFLAGS and condition code operands.
34778   // We can't always do this as FCMOV only supports a subset of X86 cond.
34779   if (SDValue Flags = combineSetCCEFLAGS(Cond, CC, DAG, Subtarget)) {
34780     if (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC)) {
34781       SDValue Ops[] = {FalseOp, TrueOp, DAG.getConstant(CC, DL, MVT::i8),
34782         Flags};
34783       return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
34784     }
34785   }
34786 
34787   // If this is a select between two integer constants, try to do some
34788   // optimizations.  Note that the operands are ordered the opposite of SELECT
34789   // operands.
34790   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
34791     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
34792       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
34793       // larger than FalseC (the false value).
34794       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
34795         CC = X86::GetOppositeBranchCondition(CC);
34796         std::swap(TrueC, FalseC);
34797         std::swap(TrueOp, FalseOp);
34798       }
34799 
34800       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
34801       // This is efficient for any integer data type (including i8/i16) and
34802       // shift amount.
34803       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
34804         Cond = getSETCC(CC, Cond, DL, DAG);
34805 
34806         // Zero extend the condition if needed.
34807         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
34808 
34809         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
34810         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
34811                            DAG.getConstant(ShAmt, DL, MVT::i8));
34812         return Cond;
34813       }
34814 
34815       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
34816       // for any integer data type, including i8/i16.
34817       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
34818         Cond = getSETCC(CC, Cond, DL, DAG);
34819 
34820         // Zero extend the condition if needed.
34821         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
34822                            FalseC->getValueType(0), Cond);
34823         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
34824                            SDValue(FalseC, 0));
34825         return Cond;
34826       }
34827 
34828       // Optimize cases that will turn into an LEA instruction.  This requires
34829       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
34830       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
34831         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
34832         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
34833 
34834         bool isFastMultiplier = false;
34835         if (Diff < 10) {
34836           switch ((unsigned char)Diff) {
34837           default: break;
34838           case 1:  // result = add base, cond
34839           case 2:  // result = lea base(    , cond*2)
34840           case 3:  // result = lea base(cond, cond*2)
34841           case 4:  // result = lea base(    , cond*4)
34842           case 5:  // result = lea base(cond, cond*4)
34843           case 8:  // result = lea base(    , cond*8)
34844           case 9:  // result = lea base(cond, cond*8)
34845             isFastMultiplier = true;
34846             break;
34847           }
34848         }
34849 
34850         if (isFastMultiplier) {
34851           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
34852           Cond = getSETCC(CC, Cond, DL ,DAG);
34853           // Zero extend the condition if needed.
34854           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
34855                              Cond);
34856           // Scale the condition by the difference.
34857           if (Diff != 1)
34858             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
34859                                DAG.getConstant(Diff, DL, Cond.getValueType()));
34860 
34861           // Add the base if non-zero.
34862           if (FalseC->getAPIntValue() != 0)
34863             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
34864                                SDValue(FalseC, 0));
34865           return Cond;
34866         }
34867       }
34868     }
34869   }
34870 
34871   // Handle these cases:
34872   //   (select (x != c), e, c) -> select (x != c), e, x),
34873   //   (select (x == c), c, e) -> select (x == c), x, e)
34874   // where the c is an integer constant, and the "select" is the combination
34875   // of CMOV and CMP.
34876   //
34877   // The rationale for this change is that the conditional-move from a constant
34878   // needs two instructions, however, conditional-move from a register needs
34879   // only one instruction.
34880   //
34881   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
34882   //  some instruction-combining opportunities. This opt needs to be
34883   //  postponed as late as possible.
34884   //
34885   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
34886     // the DCI.xxxx conditions are provided to postpone the optimization as
34887     // late as possible.
34888 
34889     ConstantSDNode *CmpAgainst = nullptr;
34890     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
34891         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
34892         !isa<ConstantSDNode>(Cond.getOperand(0))) {
34893 
34894       if (CC == X86::COND_NE &&
34895           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
34896         CC = X86::GetOppositeBranchCondition(CC);
34897         std::swap(TrueOp, FalseOp);
34898       }
34899 
34900       if (CC == X86::COND_E &&
34901           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
34902         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
34903                           DAG.getConstant(CC, DL, MVT::i8), Cond };
34904         return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
34905       }
34906     }
34907   }
34908 
34909   // Fold and/or of setcc's to double CMOV:
34910   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
34911   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
34912   //
34913   // This combine lets us generate:
34914   //   cmovcc1 (jcc1 if we don't have CMOV)
34915   //   cmovcc2 (same)
34916   // instead of:
34917   //   setcc1
34918   //   setcc2
34919   //   and/or
34920   //   cmovne (jne if we don't have CMOV)
34921   // When we can't use the CMOV instruction, it might increase branch
34922   // mispredicts.
34923   // When we can use CMOV, or when there is no mispredict, this improves
34924   // throughput and reduces register pressure.
34925   //
34926   if (CC == X86::COND_NE) {
34927     SDValue Flags;
34928     X86::CondCode CC0, CC1;
34929     bool isAndSetCC;
34930     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
34931       if (isAndSetCC) {
34932         std::swap(FalseOp, TrueOp);
34933         CC0 = X86::GetOppositeBranchCondition(CC0);
34934         CC1 = X86::GetOppositeBranchCondition(CC1);
34935       }
34936 
34937       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
34938         Flags};
34939       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), LOps);
34940       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
34941       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
34942       return CMOV;
34943     }
34944   }
34945 
34946   // Fold (CMOV C1, (ADD (CTTZ X), C2), (X != 0)) ->
34947   //      (ADD (CMOV C1-C2, (CTTZ X), (X != 0)), C2)
34948   // Or (CMOV (ADD (CTTZ X), C2), C1, (X == 0)) ->
34949   //    (ADD (CMOV (CTTZ X), C1-C2, (X == 0)), C2)
34950   if ((CC == X86::COND_NE || CC == X86::COND_E) &&
34951       Cond.getOpcode() == X86ISD::CMP && isNullConstant(Cond.getOperand(1))) {
34952     SDValue Add = TrueOp;
34953     SDValue Const = FalseOp;
34954     // Canonicalize the condition code for easier matching and output.
34955     if (CC == X86::COND_E)
34956       std::swap(Add, Const);
34957 
34958     // We might have replaced the constant in the cmov with the LHS of the
34959     // compare. If so change it to the RHS of the compare.
34960     if (Const == Cond.getOperand(0))
34961       Const = Cond.getOperand(1);
34962 
34963     // Ok, now make sure that Add is (add (cttz X), C2) and Const is a constant.
34964     if (isa<ConstantSDNode>(Const) && Add.getOpcode() == ISD::ADD &&
34965         Add.hasOneUse() && isa<ConstantSDNode>(Add.getOperand(1)) &&
34966         (Add.getOperand(0).getOpcode() == ISD::CTTZ_ZERO_UNDEF ||
34967          Add.getOperand(0).getOpcode() == ISD::CTTZ) &&
34968         Add.getOperand(0).getOperand(0) == Cond.getOperand(0)) {
34969       EVT VT = N->getValueType(0);
34970       // This should constant fold.
34971       SDValue Diff = DAG.getNode(ISD::SUB, DL, VT, Const, Add.getOperand(1));
34972       SDValue CMov = DAG.getNode(X86ISD::CMOV, DL, VT, Diff, Add.getOperand(0),
34973                                  DAG.getConstant(X86::COND_NE, DL, MVT::i8),
34974                                  Cond);
34975       return DAG.getNode(ISD::ADD, DL, VT, CMov, Add.getOperand(1));
34976     }
34977   }
34978 
34979   return SDValue();
34980 }
34981 
34982 /// Different mul shrinking modes.
34983 enum ShrinkMode { MULS8, MULU8, MULS16, MULU16 };
34984 
canReduceVMulWidth(SDNode * N,SelectionDAG & DAG,ShrinkMode & Mode)34985 static bool canReduceVMulWidth(SDNode *N, SelectionDAG &DAG, ShrinkMode &Mode) {
34986   EVT VT = N->getOperand(0).getValueType();
34987   if (VT.getScalarSizeInBits() != 32)
34988     return false;
34989 
34990   assert(N->getNumOperands() == 2 && "NumOperands of Mul are 2");
34991   unsigned SignBits[2] = {1, 1};
34992   bool IsPositive[2] = {false, false};
34993   for (unsigned i = 0; i < 2; i++) {
34994     SDValue Opd = N->getOperand(i);
34995 
34996     SignBits[i] = DAG.ComputeNumSignBits(Opd);
34997     IsPositive[i] = DAG.SignBitIsZero(Opd);
34998   }
34999 
35000   bool AllPositive = IsPositive[0] && IsPositive[1];
35001   unsigned MinSignBits = std::min(SignBits[0], SignBits[1]);
35002   // When ranges are from -128 ~ 127, use MULS8 mode.
35003   if (MinSignBits >= 25)
35004     Mode = MULS8;
35005   // When ranges are from 0 ~ 255, use MULU8 mode.
35006   else if (AllPositive && MinSignBits >= 24)
35007     Mode = MULU8;
35008   // When ranges are from -32768 ~ 32767, use MULS16 mode.
35009   else if (MinSignBits >= 17)
35010     Mode = MULS16;
35011   // When ranges are from 0 ~ 65535, use MULU16 mode.
35012   else if (AllPositive && MinSignBits >= 16)
35013     Mode = MULU16;
35014   else
35015     return false;
35016   return true;
35017 }
35018 
35019 /// When the operands of vector mul are extended from smaller size values,
35020 /// like i8 and i16, the type of mul may be shrinked to generate more
35021 /// efficient code. Two typical patterns are handled:
35022 /// Pattern1:
35023 ///     %2 = sext/zext <N x i8> %1 to <N x i32>
35024 ///     %4 = sext/zext <N x i8> %3 to <N x i32>
35025 //   or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
35026 ///     %5 = mul <N x i32> %2, %4
35027 ///
35028 /// Pattern2:
35029 ///     %2 = zext/sext <N x i16> %1 to <N x i32>
35030 ///     %4 = zext/sext <N x i16> %3 to <N x i32>
35031 ///  or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
35032 ///     %5 = mul <N x i32> %2, %4
35033 ///
35034 /// There are four mul shrinking modes:
35035 /// If %2 == sext32(trunc8(%2)), i.e., the scalar value range of %2 is
35036 /// -128 to 128, and the scalar value range of %4 is also -128 to 128,
35037 /// generate pmullw+sext32 for it (MULS8 mode).
35038 /// If %2 == zext32(trunc8(%2)), i.e., the scalar value range of %2 is
35039 /// 0 to 255, and the scalar value range of %4 is also 0 to 255,
35040 /// generate pmullw+zext32 for it (MULU8 mode).
35041 /// If %2 == sext32(trunc16(%2)), i.e., the scalar value range of %2 is
35042 /// -32768 to 32767, and the scalar value range of %4 is also -32768 to 32767,
35043 /// generate pmullw+pmulhw for it (MULS16 mode).
35044 /// If %2 == zext32(trunc16(%2)), i.e., the scalar value range of %2 is
35045 /// 0 to 65535, and the scalar value range of %4 is also 0 to 65535,
35046 /// generate pmullw+pmulhuw for it (MULU16 mode).
reduceVMULWidth(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)35047 static SDValue reduceVMULWidth(SDNode *N, SelectionDAG &DAG,
35048                                const X86Subtarget &Subtarget) {
35049   // Check for legality
35050   // pmullw/pmulhw are not supported by SSE.
35051   if (!Subtarget.hasSSE2())
35052     return SDValue();
35053 
35054   // Check for profitability
35055   // pmulld is supported since SSE41. It is better to use pmulld
35056   // instead of pmullw+pmulhw, except for subtargets where pmulld is slower than
35057   // the expansion.
35058   bool OptForMinSize = DAG.getMachineFunction().getFunction().optForMinSize();
35059   if (Subtarget.hasSSE41() && (OptForMinSize || !Subtarget.isPMULLDSlow()))
35060     return SDValue();
35061 
35062   ShrinkMode Mode;
35063   if (!canReduceVMulWidth(N, DAG, Mode))
35064     return SDValue();
35065 
35066   SDLoc DL(N);
35067   SDValue N0 = N->getOperand(0);
35068   SDValue N1 = N->getOperand(1);
35069   EVT VT = N->getOperand(0).getValueType();
35070   unsigned NumElts = VT.getVectorNumElements();
35071   if ((NumElts % 2) != 0)
35072     return SDValue();
35073 
35074   unsigned RegSize = 128;
35075   MVT OpsVT = MVT::getVectorVT(MVT::i16, RegSize / 16);
35076   EVT ReducedVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16, NumElts);
35077 
35078   // Shrink the operands of mul.
35079   SDValue NewN0 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N0);
35080   SDValue NewN1 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N1);
35081 
35082   if (ExperimentalVectorWideningLegalization ||
35083       NumElts >= OpsVT.getVectorNumElements()) {
35084     // Generate the lower part of mul: pmullw. For MULU8/MULS8, only the
35085     // lower part is needed.
35086     SDValue MulLo = DAG.getNode(ISD::MUL, DL, ReducedVT, NewN0, NewN1);
35087     if (Mode == MULU8 || Mode == MULS8)
35088       return DAG.getNode((Mode == MULU8) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND,
35089                          DL, VT, MulLo);
35090 
35091     MVT ResVT = MVT::getVectorVT(MVT::i32, NumElts / 2);
35092     // Generate the higher part of mul: pmulhw/pmulhuw. For MULU16/MULS16,
35093     // the higher part is also needed.
35094     SDValue MulHi = DAG.getNode(Mode == MULS16 ? ISD::MULHS : ISD::MULHU, DL,
35095                                 ReducedVT, NewN0, NewN1);
35096 
35097     // Repack the lower part and higher part result of mul into a wider
35098     // result.
35099     // Generate shuffle functioning as punpcklwd.
35100     SmallVector<int, 16> ShuffleMask(NumElts);
35101     for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
35102       ShuffleMask[2 * i] = i;
35103       ShuffleMask[2 * i + 1] = i + NumElts;
35104     }
35105     SDValue ResLo =
35106         DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
35107     ResLo = DAG.getBitcast(ResVT, ResLo);
35108     // Generate shuffle functioning as punpckhwd.
35109     for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
35110       ShuffleMask[2 * i] = i + NumElts / 2;
35111       ShuffleMask[2 * i + 1] = i + NumElts * 3 / 2;
35112     }
35113     SDValue ResHi =
35114         DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
35115     ResHi = DAG.getBitcast(ResVT, ResHi);
35116     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ResLo, ResHi);
35117   }
35118 
35119   // When VT.getVectorNumElements() < OpsVT.getVectorNumElements(), we want
35120   // to legalize the mul explicitly because implicit legalization for type
35121   // <4 x i16> to <4 x i32> sometimes involves unnecessary unpack
35122   // instructions which will not exist when we explicitly legalize it by
35123   // extending <4 x i16> to <8 x i16> (concatenating the <4 x i16> val with
35124   // <4 x i16> undef).
35125   //
35126   // Legalize the operands of mul.
35127   // FIXME: We may be able to handle non-concatenated vectors by insertion.
35128   unsigned ReducedSizeInBits = ReducedVT.getSizeInBits();
35129   if ((RegSize % ReducedSizeInBits) != 0)
35130     return SDValue();
35131 
35132   SmallVector<SDValue, 16> Ops(RegSize / ReducedSizeInBits,
35133                                DAG.getUNDEF(ReducedVT));
35134   Ops[0] = NewN0;
35135   NewN0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, OpsVT, Ops);
35136   Ops[0] = NewN1;
35137   NewN1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, OpsVT, Ops);
35138 
35139   if (Mode == MULU8 || Mode == MULS8) {
35140     // Generate lower part of mul: pmullw. For MULU8/MULS8, only the lower
35141     // part is needed.
35142     SDValue Mul = DAG.getNode(ISD::MUL, DL, OpsVT, NewN0, NewN1);
35143 
35144     // convert the type of mul result to VT.
35145     MVT ResVT = MVT::getVectorVT(MVT::i32, RegSize / 32);
35146     SDValue Res = DAG.getNode(Mode == MULU8 ? ISD::ZERO_EXTEND_VECTOR_INREG
35147                                             : ISD::SIGN_EXTEND_VECTOR_INREG,
35148                               DL, ResVT, Mul);
35149     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
35150                        DAG.getIntPtrConstant(0, DL));
35151   }
35152 
35153   // Generate the lower and higher part of mul: pmulhw/pmulhuw. For
35154   // MULU16/MULS16, both parts are needed.
35155   SDValue MulLo = DAG.getNode(ISD::MUL, DL, OpsVT, NewN0, NewN1);
35156   SDValue MulHi = DAG.getNode(Mode == MULS16 ? ISD::MULHS : ISD::MULHU, DL,
35157                               OpsVT, NewN0, NewN1);
35158 
35159   // Repack the lower part and higher part result of mul into a wider
35160   // result. Make sure the type of mul result is VT.
35161   MVT ResVT = MVT::getVectorVT(MVT::i32, RegSize / 32);
35162   SDValue Res = getUnpackl(DAG, DL, OpsVT, MulLo, MulHi);
35163   Res = DAG.getBitcast(ResVT, Res);
35164   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
35165                      DAG.getIntPtrConstant(0, DL));
35166 }
35167 
combineMulSpecial(uint64_t MulAmt,SDNode * N,SelectionDAG & DAG,EVT VT,const SDLoc & DL)35168 static SDValue combineMulSpecial(uint64_t MulAmt, SDNode *N, SelectionDAG &DAG,
35169                                  EVT VT, const SDLoc &DL) {
35170 
35171   auto combineMulShlAddOrSub = [&](int Mult, int Shift, bool isAdd) {
35172     SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
35173                                  DAG.getConstant(Mult, DL, VT));
35174     Result = DAG.getNode(ISD::SHL, DL, VT, Result,
35175                          DAG.getConstant(Shift, DL, MVT::i8));
35176     Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
35177                          N->getOperand(0));
35178     return Result;
35179   };
35180 
35181   auto combineMulMulAddOrSub = [&](int Mul1, int Mul2, bool isAdd) {
35182     SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
35183                                  DAG.getConstant(Mul1, DL, VT));
35184     Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, Result,
35185                          DAG.getConstant(Mul2, DL, VT));
35186     Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
35187                          N->getOperand(0));
35188     return Result;
35189   };
35190 
35191   switch (MulAmt) {
35192   default:
35193     break;
35194   case 11:
35195     // mul x, 11 => add ((shl (mul x, 5), 1), x)
35196     return combineMulShlAddOrSub(5, 1, /*isAdd*/ true);
35197   case 21:
35198     // mul x, 21 => add ((shl (mul x, 5), 2), x)
35199     return combineMulShlAddOrSub(5, 2, /*isAdd*/ true);
35200   case 41:
35201     // mul x, 41 => add ((shl (mul x, 5), 3), x)
35202     return combineMulShlAddOrSub(5, 3, /*isAdd*/ true);
35203   case 22:
35204     // mul x, 22 => add (add ((shl (mul x, 5), 2), x), x)
35205     return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
35206                        combineMulShlAddOrSub(5, 2, /*isAdd*/ true));
35207   case 19:
35208     // mul x, 19 => add ((shl (mul x, 9), 1), x)
35209     return combineMulShlAddOrSub(9, 1, /*isAdd*/ true);
35210   case 37:
35211     // mul x, 37 => add ((shl (mul x, 9), 2), x)
35212     return combineMulShlAddOrSub(9, 2, /*isAdd*/ true);
35213   case 73:
35214     // mul x, 73 => add ((shl (mul x, 9), 3), x)
35215     return combineMulShlAddOrSub(9, 3, /*isAdd*/ true);
35216   case 13:
35217     // mul x, 13 => add ((shl (mul x, 3), 2), x)
35218     return combineMulShlAddOrSub(3, 2, /*isAdd*/ true);
35219   case 23:
35220     // mul x, 23 => sub ((shl (mul x, 3), 3), x)
35221     return combineMulShlAddOrSub(3, 3, /*isAdd*/ false);
35222   case 26:
35223     // mul x, 26 => add ((mul (mul x, 5), 5), x)
35224     return combineMulMulAddOrSub(5, 5, /*isAdd*/ true);
35225   case 28:
35226     // mul x, 28 => add ((mul (mul x, 9), 3), x)
35227     return combineMulMulAddOrSub(9, 3, /*isAdd*/ true);
35228   case 29:
35229     // mul x, 29 => add (add ((mul (mul x, 9), 3), x), x)
35230     return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
35231                        combineMulMulAddOrSub(9, 3, /*isAdd*/ true));
35232   }
35233 
35234   // Another trick. If this is a power 2 + 2/4/8, we can use a shift followed
35235   // by a single LEA.
35236   // First check if this a sum of two power of 2s because that's easy. Then
35237   // count how many zeros are up to the first bit.
35238   // TODO: We can do this even without LEA at a cost of two shifts and an add.
35239   if (isPowerOf2_64(MulAmt & (MulAmt - 1))) {
35240     unsigned ScaleShift = countTrailingZeros(MulAmt);
35241     if (ScaleShift >= 1 && ScaleShift < 4) {
35242       unsigned ShiftAmt = Log2_64((MulAmt & (MulAmt - 1)));
35243       SDValue Shift1 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
35244                                    DAG.getConstant(ShiftAmt, DL, MVT::i8));
35245       SDValue Shift2 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
35246                                    DAG.getConstant(ScaleShift, DL, MVT::i8));
35247       return DAG.getNode(ISD::ADD, DL, VT, Shift1, Shift2);
35248     }
35249   }
35250 
35251   return SDValue();
35252 }
35253 
35254 // If the upper 17 bits of each element are zero then we can use PMADDWD,
35255 // which is always at least as quick as PMULLD, except on KNL.
combineMulToPMADDWD(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)35256 static SDValue combineMulToPMADDWD(SDNode *N, SelectionDAG &DAG,
35257                                    const X86Subtarget &Subtarget) {
35258   if (!Subtarget.hasSSE2())
35259     return SDValue();
35260 
35261   if (Subtarget.isPMADDWDSlow())
35262     return SDValue();
35263 
35264   EVT VT = N->getValueType(0);
35265 
35266   // Only support vXi32 vectors.
35267   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32)
35268     return SDValue();
35269 
35270   // Make sure the vXi16 type is legal. This covers the AVX512 without BWI case.
35271   // Also allow v2i32 if it will be widened.
35272   MVT WVT = MVT::getVectorVT(MVT::i16, 2 * VT.getVectorNumElements());
35273   if (!((ExperimentalVectorWideningLegalization && VT == MVT::v2i32) ||
35274         DAG.getTargetLoweringInfo().isTypeLegal(WVT)))
35275     return SDValue();
35276 
35277   SDValue N0 = N->getOperand(0);
35278   SDValue N1 = N->getOperand(1);
35279 
35280   // If we are zero extending two steps without SSE4.1, its better to reduce
35281   // the vmul width instead.
35282   if (!Subtarget.hasSSE41() &&
35283       (N0.getOpcode() == ISD::ZERO_EXTEND &&
35284        N0.getOperand(0).getScalarValueSizeInBits() <= 8) &&
35285       (N1.getOpcode() == ISD::ZERO_EXTEND &&
35286        N1.getOperand(0).getScalarValueSizeInBits() <= 8))
35287     return SDValue();
35288 
35289   APInt Mask17 = APInt::getHighBitsSet(32, 17);
35290   if (!DAG.MaskedValueIsZero(N1, Mask17) ||
35291       !DAG.MaskedValueIsZero(N0, Mask17))
35292     return SDValue();
35293 
35294   // Use SplitOpsAndApply to handle AVX splitting.
35295   auto PMADDWDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
35296                            ArrayRef<SDValue> Ops) {
35297     MVT VT = MVT::getVectorVT(MVT::i32, Ops[0].getValueSizeInBits() / 32);
35298     return DAG.getNode(X86ISD::VPMADDWD, DL, VT, Ops);
35299   };
35300   return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT,
35301                           { DAG.getBitcast(WVT, N0), DAG.getBitcast(WVT, N1) },
35302                           PMADDWDBuilder);
35303 }
35304 
combineMulToPMULDQ(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)35305 static SDValue combineMulToPMULDQ(SDNode *N, SelectionDAG &DAG,
35306                                   const X86Subtarget &Subtarget) {
35307   if (!Subtarget.hasSSE2())
35308     return SDValue();
35309 
35310   EVT VT = N->getValueType(0);
35311 
35312   // Only support vXi64 vectors.
35313   if (!VT.isVector() || VT.getVectorElementType() != MVT::i64 ||
35314       VT.getVectorNumElements() < 2 ||
35315       !isPowerOf2_32(VT.getVectorNumElements()))
35316     return SDValue();
35317 
35318   SDValue N0 = N->getOperand(0);
35319   SDValue N1 = N->getOperand(1);
35320 
35321   // MULDQ returns the 64-bit result of the signed multiplication of the lower
35322   // 32-bits. We can lower with this if the sign bits stretch that far.
35323   if (Subtarget.hasSSE41() && DAG.ComputeNumSignBits(N0) > 32 &&
35324       DAG.ComputeNumSignBits(N1) > 32) {
35325     auto PMULDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
35326                             ArrayRef<SDValue> Ops) {
35327       return DAG.getNode(X86ISD::PMULDQ, DL, Ops[0].getValueType(), Ops);
35328     };
35329     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { N0, N1 },
35330                             PMULDQBuilder, /*CheckBWI*/false);
35331   }
35332 
35333   // If the upper bits are zero we can use a single pmuludq.
35334   APInt Mask = APInt::getHighBitsSet(64, 32);
35335   if (DAG.MaskedValueIsZero(N0, Mask) && DAG.MaskedValueIsZero(N1, Mask)) {
35336     auto PMULUDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
35337                              ArrayRef<SDValue> Ops) {
35338       return DAG.getNode(X86ISD::PMULUDQ, DL, Ops[0].getValueType(), Ops);
35339     };
35340     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { N0, N1 },
35341                             PMULUDQBuilder, /*CheckBWI*/false);
35342   }
35343 
35344   return SDValue();
35345 }
35346 
35347 /// Optimize a single multiply with constant into two operations in order to
35348 /// implement it with two cheaper instructions, e.g. LEA + SHL, LEA + LEA.
combineMul(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)35349 static SDValue combineMul(SDNode *N, SelectionDAG &DAG,
35350                           TargetLowering::DAGCombinerInfo &DCI,
35351                           const X86Subtarget &Subtarget) {
35352   EVT VT = N->getValueType(0);
35353 
35354   if (SDValue V = combineMulToPMADDWD(N, DAG, Subtarget))
35355     return V;
35356 
35357   if (SDValue V = combineMulToPMULDQ(N, DAG, Subtarget))
35358     return V;
35359 
35360   if (DCI.isBeforeLegalize() && VT.isVector())
35361     return reduceVMULWidth(N, DAG, Subtarget);
35362 
35363   if (!MulConstantOptimization)
35364     return SDValue();
35365   // An imul is usually smaller than the alternative sequence.
35366   if (DAG.getMachineFunction().getFunction().optForMinSize())
35367     return SDValue();
35368 
35369   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
35370     return SDValue();
35371 
35372   if (VT != MVT::i64 && VT != MVT::i32)
35373     return SDValue();
35374 
35375   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
35376   if (!C)
35377     return SDValue();
35378   if (isPowerOf2_64(C->getZExtValue()))
35379     return SDValue();
35380 
35381   int64_t SignMulAmt = C->getSExtValue();
35382   assert(SignMulAmt != INT64_MIN && "Int min should have been handled!");
35383   uint64_t AbsMulAmt = SignMulAmt < 0 ? -SignMulAmt : SignMulAmt;
35384 
35385   SDLoc DL(N);
35386   if (AbsMulAmt == 3 || AbsMulAmt == 5 || AbsMulAmt == 9) {
35387     SDValue NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
35388                                  DAG.getConstant(AbsMulAmt, DL, VT));
35389     if (SignMulAmt < 0)
35390       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
35391                            NewMul);
35392 
35393     return NewMul;
35394   }
35395 
35396   uint64_t MulAmt1 = 0;
35397   uint64_t MulAmt2 = 0;
35398   if ((AbsMulAmt % 9) == 0) {
35399     MulAmt1 = 9;
35400     MulAmt2 = AbsMulAmt / 9;
35401   } else if ((AbsMulAmt % 5) == 0) {
35402     MulAmt1 = 5;
35403     MulAmt2 = AbsMulAmt / 5;
35404   } else if ((AbsMulAmt % 3) == 0) {
35405     MulAmt1 = 3;
35406     MulAmt2 = AbsMulAmt / 3;
35407   }
35408 
35409   SDValue NewMul;
35410   // For negative multiply amounts, only allow MulAmt2 to be a power of 2.
35411   if (MulAmt2 &&
35412       (isPowerOf2_64(MulAmt2) ||
35413        (SignMulAmt >= 0 && (MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)))) {
35414 
35415     if (isPowerOf2_64(MulAmt2) &&
35416         !(SignMulAmt >= 0 && N->hasOneUse() &&
35417           N->use_begin()->getOpcode() == ISD::ADD))
35418       // If second multiplifer is pow2, issue it first. We want the multiply by
35419       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
35420       // is an add. Only do this for positive multiply amounts since the
35421       // negate would prevent it from being used as an address mode anyway.
35422       std::swap(MulAmt1, MulAmt2);
35423 
35424     if (isPowerOf2_64(MulAmt1))
35425       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
35426                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
35427     else
35428       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
35429                            DAG.getConstant(MulAmt1, DL, VT));
35430 
35431     if (isPowerOf2_64(MulAmt2))
35432       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
35433                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
35434     else
35435       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
35436                            DAG.getConstant(MulAmt2, DL, VT));
35437 
35438     // Negate the result.
35439     if (SignMulAmt < 0)
35440       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
35441                            NewMul);
35442   } else if (!Subtarget.slowLEA())
35443     NewMul = combineMulSpecial(C->getZExtValue(), N, DAG, VT, DL);
35444 
35445   if (!NewMul) {
35446     assert(C->getZExtValue() != 0 &&
35447            C->getZExtValue() != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX) &&
35448            "Both cases that could cause potential overflows should have "
35449            "already been handled.");
35450     if (isPowerOf2_64(AbsMulAmt - 1)) {
35451       // (mul x, 2^N + 1) => (add (shl x, N), x)
35452       NewMul = DAG.getNode(
35453           ISD::ADD, DL, VT, N->getOperand(0),
35454           DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
35455                       DAG.getConstant(Log2_64(AbsMulAmt - 1), DL,
35456                                       MVT::i8)));
35457       // To negate, subtract the number from zero
35458       if (SignMulAmt < 0)
35459         NewMul = DAG.getNode(ISD::SUB, DL, VT,
35460                              DAG.getConstant(0, DL, VT), NewMul);
35461     } else if (isPowerOf2_64(AbsMulAmt + 1)) {
35462       // (mul x, 2^N - 1) => (sub (shl x, N), x)
35463       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
35464                            DAG.getConstant(Log2_64(AbsMulAmt + 1),
35465                                            DL, MVT::i8));
35466       // To negate, reverse the operands of the subtract.
35467       if (SignMulAmt < 0)
35468         NewMul = DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), NewMul);
35469       else
35470         NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
35471     } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt - 2)) {
35472       // (mul x, 2^N + 2) => (add (add (shl x, N), x), x)
35473       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
35474                            DAG.getConstant(Log2_64(AbsMulAmt - 2),
35475                                            DL, MVT::i8));
35476       NewMul = DAG.getNode(ISD::ADD, DL, VT, NewMul, N->getOperand(0));
35477       NewMul = DAG.getNode(ISD::ADD, DL, VT, NewMul, N->getOperand(0));
35478     } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt + 2)) {
35479       // (mul x, 2^N - 2) => (sub (sub (shl x, N), x), x)
35480       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
35481                            DAG.getConstant(Log2_64(AbsMulAmt + 2),
35482                                            DL, MVT::i8));
35483       NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
35484       NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
35485     }
35486   }
35487 
35488   return NewMul;
35489 }
35490 
combineShiftLeft(SDNode * N,SelectionDAG & DAG)35491 static SDValue combineShiftLeft(SDNode *N, SelectionDAG &DAG) {
35492   SDValue N0 = N->getOperand(0);
35493   SDValue N1 = N->getOperand(1);
35494   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
35495   EVT VT = N0.getValueType();
35496 
35497   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
35498   // since the result of setcc_c is all zero's or all ones.
35499   if (VT.isInteger() && !VT.isVector() &&
35500       N1C && N0.getOpcode() == ISD::AND &&
35501       N0.getOperand(1).getOpcode() == ISD::Constant) {
35502     SDValue N00 = N0.getOperand(0);
35503     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
35504     Mask <<= N1C->getAPIntValue();
35505     bool MaskOK = false;
35506     // We can handle cases concerning bit-widening nodes containing setcc_c if
35507     // we carefully interrogate the mask to make sure we are semantics
35508     // preserving.
35509     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
35510     // of the underlying setcc_c operation if the setcc_c was zero extended.
35511     // Consider the following example:
35512     //   zext(setcc_c)                 -> i32 0x0000FFFF
35513     //   c1                            -> i32 0x0000FFFF
35514     //   c2                            -> i32 0x00000001
35515     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
35516     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
35517     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
35518       MaskOK = true;
35519     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
35520                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
35521       MaskOK = true;
35522     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
35523                 N00.getOpcode() == ISD::ANY_EXTEND) &&
35524                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
35525       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
35526     }
35527     if (MaskOK && Mask != 0) {
35528       SDLoc DL(N);
35529       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
35530     }
35531   }
35532 
35533   // Hardware support for vector shifts is sparse which makes us scalarize the
35534   // vector operations in many cases. Also, on sandybridge ADD is faster than
35535   // shl.
35536   // (shl V, 1) -> add V,V
35537   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
35538     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
35539       assert(N0.getValueType().isVector() && "Invalid vector shift type");
35540       // We shift all of the values by one. In many cases we do not have
35541       // hardware support for this operation. This is better expressed as an ADD
35542       // of two values.
35543       if (N1SplatC->getAPIntValue() == 1)
35544         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
35545     }
35546 
35547   return SDValue();
35548 }
35549 
combineShiftRightArithmetic(SDNode * N,SelectionDAG & DAG)35550 static SDValue combineShiftRightArithmetic(SDNode *N, SelectionDAG &DAG) {
35551   SDValue N0 = N->getOperand(0);
35552   SDValue N1 = N->getOperand(1);
35553   EVT VT = N0.getValueType();
35554   unsigned Size = VT.getSizeInBits();
35555 
35556   // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
35557   // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
35558   // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
35559   // depending on sign of (SarConst - [56,48,32,24,16])
35560 
35561   // sexts in X86 are MOVs. The MOVs have the same code size
35562   // as above SHIFTs (only SHIFT on 1 has lower code size).
35563   // However the MOVs have 2 advantages to a SHIFT:
35564   // 1. MOVs can write to a register that differs from source
35565   // 2. MOVs accept memory operands
35566 
35567   if (VT.isVector() || N1.getOpcode() != ISD::Constant ||
35568       N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
35569       N0.getOperand(1).getOpcode() != ISD::Constant)
35570     return SDValue();
35571 
35572   SDValue N00 = N0.getOperand(0);
35573   SDValue N01 = N0.getOperand(1);
35574   APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
35575   APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
35576   EVT CVT = N1.getValueType();
35577 
35578   if (SarConst.isNegative())
35579     return SDValue();
35580 
35581   for (MVT SVT : { MVT::i8, MVT::i16, MVT::i32 }) {
35582     unsigned ShiftSize = SVT.getSizeInBits();
35583     // skipping types without corresponding sext/zext and
35584     // ShlConst that is not one of [56,48,32,24,16]
35585     if (ShiftSize >= Size || ShlConst != Size - ShiftSize)
35586       continue;
35587     SDLoc DL(N);
35588     SDValue NN =
35589         DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
35590     SarConst = SarConst - (Size - ShiftSize);
35591     if (SarConst == 0)
35592       return NN;
35593     else if (SarConst.isNegative())
35594       return DAG.getNode(ISD::SHL, DL, VT, NN,
35595                          DAG.getConstant(-SarConst, DL, CVT));
35596     else
35597       return DAG.getNode(ISD::SRA, DL, VT, NN,
35598                          DAG.getConstant(SarConst, DL, CVT));
35599   }
35600   return SDValue();
35601 }
35602 
combineShiftRightLogical(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)35603 static SDValue combineShiftRightLogical(SDNode *N, SelectionDAG &DAG,
35604                                         TargetLowering::DAGCombinerInfo &DCI) {
35605   SDValue N0 = N->getOperand(0);
35606   SDValue N1 = N->getOperand(1);
35607   EVT VT = N0.getValueType();
35608 
35609   // Only do this on the last DAG combine as it can interfere with other
35610   // combines.
35611   if (!DCI.isAfterLegalizeDAG())
35612     return SDValue();
35613 
35614   // Try to improve a sequence of srl (and X, C1), C2 by inverting the order.
35615   // TODO: This is a generic DAG combine that became an x86-only combine to
35616   // avoid shortcomings in other folds such as bswap, bit-test ('bt'), and
35617   // and-not ('andn').
35618   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
35619     return SDValue();
35620 
35621   auto *ShiftC = dyn_cast<ConstantSDNode>(N1);
35622   auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
35623   if (!ShiftC || !AndC)
35624     return SDValue();
35625 
35626   // If we can shrink the constant mask below 8-bits or 32-bits, then this
35627   // transform should reduce code size. It may also enable secondary transforms
35628   // from improved known-bits analysis or instruction selection.
35629   APInt MaskVal = AndC->getAPIntValue();
35630 
35631   // If this can be matched by a zero extend, don't optimize.
35632   if (MaskVal.isMask()) {
35633     unsigned TO = MaskVal.countTrailingOnes();
35634     if (TO >= 8 && isPowerOf2_32(TO))
35635       return SDValue();
35636   }
35637 
35638   APInt NewMaskVal = MaskVal.lshr(ShiftC->getAPIntValue());
35639   unsigned OldMaskSize = MaskVal.getMinSignedBits();
35640   unsigned NewMaskSize = NewMaskVal.getMinSignedBits();
35641   if ((OldMaskSize > 8 && NewMaskSize <= 8) ||
35642       (OldMaskSize > 32 && NewMaskSize <= 32)) {
35643     // srl (and X, AndC), ShiftC --> and (srl X, ShiftC), (AndC >> ShiftC)
35644     SDLoc DL(N);
35645     SDValue NewMask = DAG.getConstant(NewMaskVal, DL, VT);
35646     SDValue NewShift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), N1);
35647     return DAG.getNode(ISD::AND, DL, VT, NewShift, NewMask);
35648   }
35649   return SDValue();
35650 }
35651 
combineShift(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)35652 static SDValue combineShift(SDNode* N, SelectionDAG &DAG,
35653                             TargetLowering::DAGCombinerInfo &DCI,
35654                             const X86Subtarget &Subtarget) {
35655   if (N->getOpcode() == ISD::SHL)
35656     if (SDValue V = combineShiftLeft(N, DAG))
35657       return V;
35658 
35659   if (N->getOpcode() == ISD::SRA)
35660     if (SDValue V = combineShiftRightArithmetic(N, DAG))
35661       return V;
35662 
35663   if (N->getOpcode() == ISD::SRL)
35664     if (SDValue V = combineShiftRightLogical(N, DAG, DCI))
35665       return V;
35666 
35667   return SDValue();
35668 }
35669 
combineVectorPack(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)35670 static SDValue combineVectorPack(SDNode *N, SelectionDAG &DAG,
35671                                  TargetLowering::DAGCombinerInfo &DCI,
35672                                  const X86Subtarget &Subtarget) {
35673   unsigned Opcode = N->getOpcode();
35674   assert((X86ISD::PACKSS == Opcode || X86ISD::PACKUS == Opcode) &&
35675          "Unexpected shift opcode");
35676 
35677   EVT VT = N->getValueType(0);
35678   SDValue N0 = N->getOperand(0);
35679   SDValue N1 = N->getOperand(1);
35680   unsigned DstBitsPerElt = VT.getScalarSizeInBits();
35681   unsigned SrcBitsPerElt = 2 * DstBitsPerElt;
35682   assert(N0.getScalarValueSizeInBits() == SrcBitsPerElt &&
35683          N1.getScalarValueSizeInBits() == SrcBitsPerElt &&
35684          "Unexpected PACKSS/PACKUS input type");
35685 
35686   bool IsSigned = (X86ISD::PACKSS == Opcode);
35687 
35688   // Constant Folding.
35689   APInt UndefElts0, UndefElts1;
35690   SmallVector<APInt, 32> EltBits0, EltBits1;
35691   if ((N0->isUndef() || N->isOnlyUserOf(N0.getNode())) &&
35692       (N1->isUndef() || N->isOnlyUserOf(N1.getNode())) &&
35693       getTargetConstantBitsFromNode(N0, SrcBitsPerElt, UndefElts0, EltBits0) &&
35694       getTargetConstantBitsFromNode(N1, SrcBitsPerElt, UndefElts1, EltBits1)) {
35695     unsigned NumLanes = VT.getSizeInBits() / 128;
35696     unsigned NumDstElts = VT.getVectorNumElements();
35697     unsigned NumSrcElts = NumDstElts / 2;
35698     unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
35699     unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
35700 
35701     APInt Undefs(NumDstElts, 0);
35702     SmallVector<APInt, 32> Bits(NumDstElts, APInt::getNullValue(DstBitsPerElt));
35703     for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
35704       for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
35705         unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
35706         auto &UndefElts = (Elt >= NumSrcEltsPerLane ? UndefElts1 : UndefElts0);
35707         auto &EltBits = (Elt >= NumSrcEltsPerLane ? EltBits1 : EltBits0);
35708 
35709         if (UndefElts[SrcIdx]) {
35710           Undefs.setBit(Lane * NumDstEltsPerLane + Elt);
35711           continue;
35712         }
35713 
35714         APInt &Val = EltBits[SrcIdx];
35715         if (IsSigned) {
35716           // PACKSS: Truncate signed value with signed saturation.
35717           // Source values less than dst minint are saturated to minint.
35718           // Source values greater than dst maxint are saturated to maxint.
35719           if (Val.isSignedIntN(DstBitsPerElt))
35720             Val = Val.trunc(DstBitsPerElt);
35721           else if (Val.isNegative())
35722             Val = APInt::getSignedMinValue(DstBitsPerElt);
35723           else
35724             Val = APInt::getSignedMaxValue(DstBitsPerElt);
35725         } else {
35726           // PACKUS: Truncate signed value with unsigned saturation.
35727           // Source values less than zero are saturated to zero.
35728           // Source values greater than dst maxuint are saturated to maxuint.
35729           if (Val.isIntN(DstBitsPerElt))
35730             Val = Val.trunc(DstBitsPerElt);
35731           else if (Val.isNegative())
35732             Val = APInt::getNullValue(DstBitsPerElt);
35733           else
35734             Val = APInt::getAllOnesValue(DstBitsPerElt);
35735         }
35736         Bits[Lane * NumDstEltsPerLane + Elt] = Val;
35737       }
35738     }
35739 
35740     return getConstVector(Bits, Undefs, VT.getSimpleVT(), DAG, SDLoc(N));
35741   }
35742 
35743   // Try to combine a PACKUSWB/PACKSSWB implemented truncate with a regular
35744   // truncate to create a larger truncate.
35745   if (Subtarget.hasAVX512() &&
35746       N0.getOpcode() == ISD::TRUNCATE && N1.isUndef() && VT == MVT::v16i8 &&
35747       N0.getOperand(0).getValueType() == MVT::v8i32) {
35748     if ((IsSigned && DAG.ComputeNumSignBits(N0) > 8) ||
35749         (!IsSigned &&
35750          DAG.MaskedValueIsZero(N0, APInt::getHighBitsSet(16, 8)))) {
35751       if (Subtarget.hasVLX())
35752         return DAG.getNode(X86ISD::VTRUNC, SDLoc(N), VT, N0.getOperand(0));
35753 
35754       // Widen input to v16i32 so we can truncate that.
35755       SDLoc dl(N);
35756       SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i32,
35757                                    N0.getOperand(0), DAG.getUNDEF(MVT::v8i32));
35758       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Concat);
35759     }
35760   }
35761 
35762   // Attempt to combine as shuffle.
35763   SDValue Op(N, 0);
35764   if (SDValue Res =
35765           combineX86ShufflesRecursively({Op}, 0, Op, {0}, {}, /*Depth*/ 1,
35766                                         /*HasVarMask*/ false,
35767                                         /*AllowVarMask*/ true, DAG, Subtarget))
35768     return Res;
35769 
35770   return SDValue();
35771 }
35772 
combineVectorShiftVar(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)35773 static SDValue combineVectorShiftVar(SDNode *N, SelectionDAG &DAG,
35774                                      TargetLowering::DAGCombinerInfo &DCI,
35775                                      const X86Subtarget &Subtarget) {
35776   assert((X86ISD::VSHL == N->getOpcode() || X86ISD::VSRA == N->getOpcode() ||
35777           X86ISD::VSRL == N->getOpcode()) &&
35778          "Unexpected shift opcode");
35779   EVT VT = N->getValueType(0);
35780 
35781   // Shift zero -> zero.
35782   if (ISD::isBuildVectorAllZeros(N->getOperand(0).getNode()))
35783     return DAG.getConstant(0, SDLoc(N), VT);
35784 
35785   APInt KnownUndef, KnownZero;
35786   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
35787   APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
35788   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, KnownUndef,
35789                                      KnownZero, DCI))
35790     return SDValue(N, 0);
35791 
35792   return SDValue();
35793 }
35794 
combineVectorShiftImm(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)35795 static SDValue combineVectorShiftImm(SDNode *N, SelectionDAG &DAG,
35796                                      TargetLowering::DAGCombinerInfo &DCI,
35797                                      const X86Subtarget &Subtarget) {
35798   unsigned Opcode = N->getOpcode();
35799   assert((X86ISD::VSHLI == Opcode || X86ISD::VSRAI == Opcode ||
35800           X86ISD::VSRLI == Opcode) &&
35801          "Unexpected shift opcode");
35802   bool LogicalShift = X86ISD::VSHLI == Opcode || X86ISD::VSRLI == Opcode;
35803   EVT VT = N->getValueType(0);
35804   SDValue N0 = N->getOperand(0);
35805   SDValue N1 = N->getOperand(1);
35806   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
35807   assert(VT == N0.getValueType() && (NumBitsPerElt % 8) == 0 &&
35808          "Unexpected value type");
35809   assert(N1.getValueType() == MVT::i8 && "Unexpected shift amount type");
35810 
35811   // Out of range logical bit shifts are guaranteed to be zero.
35812   // Out of range arithmetic bit shifts splat the sign bit.
35813   unsigned ShiftVal = cast<ConstantSDNode>(N1)->getZExtValue();
35814   if (ShiftVal >= NumBitsPerElt) {
35815     if (LogicalShift)
35816       return DAG.getConstant(0, SDLoc(N), VT);
35817     else
35818       ShiftVal = NumBitsPerElt - 1;
35819   }
35820 
35821   // Shift N0 by zero -> N0.
35822   if (!ShiftVal)
35823     return N0;
35824 
35825   // Shift zero -> zero.
35826   if (ISD::isBuildVectorAllZeros(N0.getNode()))
35827     return DAG.getConstant(0, SDLoc(N), VT);
35828 
35829   // Fold (VSRAI (VSRAI X, C1), C2) --> (VSRAI X, (C1 + C2)) with (C1 + C2)
35830   // clamped to (NumBitsPerElt - 1).
35831   if (Opcode == X86ISD::VSRAI && N0.getOpcode() == X86ISD::VSRAI) {
35832     unsigned ShiftVal2 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
35833     unsigned NewShiftVal = ShiftVal + ShiftVal2;
35834     if (NewShiftVal >= NumBitsPerElt)
35835       NewShiftVal = NumBitsPerElt - 1;
35836     return DAG.getNode(X86ISD::VSRAI, SDLoc(N), VT, N0.getOperand(0),
35837                        DAG.getConstant(NewShiftVal, SDLoc(N), MVT::i8));
35838   }
35839 
35840   // We can decode 'whole byte' logical bit shifts as shuffles.
35841   if (LogicalShift && (ShiftVal % 8) == 0) {
35842     SDValue Op(N, 0);
35843     if (SDValue Res = combineX86ShufflesRecursively(
35844             {Op}, 0, Op, {0}, {}, /*Depth*/ 1,
35845             /*HasVarMask*/ false, /*AllowVarMask*/ true, DAG, Subtarget))
35846       return Res;
35847   }
35848 
35849   // Constant Folding.
35850   APInt UndefElts;
35851   SmallVector<APInt, 32> EltBits;
35852   if (N->isOnlyUserOf(N0.getNode()) &&
35853       getTargetConstantBitsFromNode(N0, NumBitsPerElt, UndefElts, EltBits)) {
35854     assert(EltBits.size() == VT.getVectorNumElements() &&
35855            "Unexpected shift value type");
35856     for (APInt &Elt : EltBits) {
35857       if (X86ISD::VSHLI == Opcode)
35858         Elt <<= ShiftVal;
35859       else if (X86ISD::VSRAI == Opcode)
35860         Elt.ashrInPlace(ShiftVal);
35861       else
35862         Elt.lshrInPlace(ShiftVal);
35863     }
35864     return getConstVector(EltBits, UndefElts, VT.getSimpleVT(), DAG, SDLoc(N));
35865   }
35866 
35867   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
35868   if (TLI.SimplifyDemandedBits(SDValue(N, 0),
35869                                APInt::getAllOnesValue(NumBitsPerElt), DCI))
35870     return SDValue(N, 0);
35871 
35872   return SDValue();
35873 }
35874 
combineVectorInsert(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)35875 static SDValue combineVectorInsert(SDNode *N, SelectionDAG &DAG,
35876                                    TargetLowering::DAGCombinerInfo &DCI,
35877                                    const X86Subtarget &Subtarget) {
35878   assert(
35879       ((N->getOpcode() == X86ISD::PINSRB && N->getValueType(0) == MVT::v16i8) ||
35880        (N->getOpcode() == X86ISD::PINSRW &&
35881         N->getValueType(0) == MVT::v8i16)) &&
35882       "Unexpected vector insertion");
35883 
35884   // Attempt to combine PINSRB/PINSRW patterns to a shuffle.
35885   SDValue Op(N, 0);
35886   if (SDValue Res =
35887           combineX86ShufflesRecursively({Op}, 0, Op, {0}, {}, /*Depth*/ 1,
35888                                         /*HasVarMask*/ false,
35889                                         /*AllowVarMask*/ true, DAG, Subtarget))
35890     return Res;
35891 
35892   return SDValue();
35893 }
35894 
35895 /// Recognize the distinctive (AND (setcc ...) (setcc ..)) where both setccs
35896 /// reference the same FP CMP, and rewrite for CMPEQSS and friends. Likewise for
35897 /// OR -> CMPNEQSS.
combineCompareEqual(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)35898 static SDValue combineCompareEqual(SDNode *N, SelectionDAG &DAG,
35899                                    TargetLowering::DAGCombinerInfo &DCI,
35900                                    const X86Subtarget &Subtarget) {
35901   unsigned opcode;
35902 
35903   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
35904   // we're requiring SSE2 for both.
35905   if (Subtarget.hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
35906     SDValue N0 = N->getOperand(0);
35907     SDValue N1 = N->getOperand(1);
35908     SDValue CMP0 = N0->getOperand(1);
35909     SDValue CMP1 = N1->getOperand(1);
35910     SDLoc DL(N);
35911 
35912     // The SETCCs should both refer to the same CMP.
35913     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
35914       return SDValue();
35915 
35916     SDValue CMP00 = CMP0->getOperand(0);
35917     SDValue CMP01 = CMP0->getOperand(1);
35918     EVT     VT    = CMP00.getValueType();
35919 
35920     if (VT == MVT::f32 || VT == MVT::f64) {
35921       bool ExpectingFlags = false;
35922       // Check for any users that want flags:
35923       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
35924            !ExpectingFlags && UI != UE; ++UI)
35925         switch (UI->getOpcode()) {
35926         default:
35927         case ISD::BR_CC:
35928         case ISD::BRCOND:
35929         case ISD::SELECT:
35930           ExpectingFlags = true;
35931           break;
35932         case ISD::CopyToReg:
35933         case ISD::SIGN_EXTEND:
35934         case ISD::ZERO_EXTEND:
35935         case ISD::ANY_EXTEND:
35936           break;
35937         }
35938 
35939       if (!ExpectingFlags) {
35940         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
35941         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
35942 
35943         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
35944           X86::CondCode tmp = cc0;
35945           cc0 = cc1;
35946           cc1 = tmp;
35947         }
35948 
35949         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
35950             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
35951           // FIXME: need symbolic constants for these magic numbers.
35952           // See X86ATTInstPrinter.cpp:printSSECC().
35953           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
35954           if (Subtarget.hasAVX512()) {
35955             SDValue FSetCC =
35956                 DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CMP00, CMP01,
35957                             DAG.getConstant(x86cc, DL, MVT::i8));
35958             // Need to fill with zeros to ensure the bitcast will produce zeroes
35959             // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
35960             SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v16i1,
35961                                       DAG.getConstant(0, DL, MVT::v16i1),
35962                                       FSetCC, DAG.getIntPtrConstant(0, DL));
35963             return DAG.getZExtOrTrunc(DAG.getBitcast(MVT::i16, Ins), DL,
35964                                       N->getSimpleValueType(0));
35965           }
35966           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
35967                                               CMP00.getValueType(), CMP00, CMP01,
35968                                               DAG.getConstant(x86cc, DL,
35969                                                               MVT::i8));
35970 
35971           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
35972           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
35973 
35974           if (is64BitFP && !Subtarget.is64Bit()) {
35975             // On a 32-bit target, we cannot bitcast the 64-bit float to a
35976             // 64-bit integer, since that's not a legal type. Since
35977             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
35978             // bits, but can do this little dance to extract the lowest 32 bits
35979             // and work with those going forward.
35980             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
35981                                            OnesOrZeroesF);
35982             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
35983             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
35984                                         Vector32, DAG.getIntPtrConstant(0, DL));
35985             IntVT = MVT::i32;
35986           }
35987 
35988           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
35989           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
35990                                       DAG.getConstant(1, DL, IntVT));
35991           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
35992                                               ANDed);
35993           return OneBitOfTruth;
35994         }
35995       }
35996     }
35997   }
35998   return SDValue();
35999 }
36000 
36001 /// Try to fold: (and (xor X, -1), Y) -> (andnp X, Y).
combineANDXORWithAllOnesIntoANDNP(SDNode * N,SelectionDAG & DAG)36002 static SDValue combineANDXORWithAllOnesIntoANDNP(SDNode *N, SelectionDAG &DAG) {
36003   assert(N->getOpcode() == ISD::AND);
36004 
36005   MVT VT = N->getSimpleValueType(0);
36006   if (!VT.is128BitVector() && !VT.is256BitVector() && !VT.is512BitVector())
36007     return SDValue();
36008 
36009   SDValue X, Y;
36010   SDValue N0 = peekThroughBitcasts(N->getOperand(0));
36011   SDValue N1 = peekThroughBitcasts(N->getOperand(1));
36012   if (N0.getOpcode() == ISD::XOR &&
36013       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode())) {
36014     X = N0.getOperand(0);
36015     Y = N1;
36016   } else if (N1.getOpcode() == ISD::XOR &&
36017              ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode())) {
36018     X = N1.getOperand(0);
36019     Y = N0;
36020   } else
36021     return SDValue();
36022 
36023   X = DAG.getBitcast(VT, X);
36024   Y = DAG.getBitcast(VT, Y);
36025   return DAG.getNode(X86ISD::ANDNP, SDLoc(N), VT, X, Y);
36026 }
36027 
36028 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
36029 // register. In most cases we actually compare or select YMM-sized registers
36030 // and mixing the two types creates horrible code. This method optimizes
36031 // some of the transition sequences.
36032 // Even with AVX-512 this is still useful for removing casts around logical
36033 // operations on vXi1 mask types.
PromoteMaskArithmetic(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)36034 static SDValue PromoteMaskArithmetic(SDNode *N, SelectionDAG &DAG,
36035                                      const X86Subtarget &Subtarget) {
36036   EVT VT = N->getValueType(0);
36037   assert(VT.isVector() && "Expected vector type");
36038 
36039   assert((N->getOpcode() == ISD::ANY_EXTEND ||
36040           N->getOpcode() == ISD::ZERO_EXTEND ||
36041           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
36042 
36043   SDValue Narrow = N->getOperand(0);
36044   EVT NarrowVT = Narrow.getValueType();
36045 
36046   if (Narrow->getOpcode() != ISD::XOR &&
36047       Narrow->getOpcode() != ISD::AND &&
36048       Narrow->getOpcode() != ISD::OR)
36049     return SDValue();
36050 
36051   SDValue N0  = Narrow->getOperand(0);
36052   SDValue N1  = Narrow->getOperand(1);
36053   SDLoc DL(Narrow);
36054 
36055   // The Left side has to be a trunc.
36056   if (N0.getOpcode() != ISD::TRUNCATE)
36057     return SDValue();
36058 
36059   // The type of the truncated inputs.
36060   if (N0->getOperand(0).getValueType() != VT)
36061     return SDValue();
36062 
36063   // The right side has to be a 'trunc' or a constant vector.
36064   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE &&
36065                   N1.getOperand(0).getValueType() == VT;
36066   if (!RHSTrunc &&
36067       !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()))
36068     return SDValue();
36069 
36070   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
36071 
36072   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), VT))
36073     return SDValue();
36074 
36075   // Set N0 and N1 to hold the inputs to the new wide operation.
36076   N0 = N0->getOperand(0);
36077   if (RHSTrunc)
36078     N1 = N1->getOperand(0);
36079   else
36080     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N1);
36081 
36082   // Generate the wide operation.
36083   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, VT, N0, N1);
36084   unsigned Opcode = N->getOpcode();
36085   switch (Opcode) {
36086   default: llvm_unreachable("Unexpected opcode");
36087   case ISD::ANY_EXTEND:
36088     return Op;
36089   case ISD::ZERO_EXTEND:
36090     return DAG.getZeroExtendInReg(Op, DL, NarrowVT.getScalarType());
36091   case ISD::SIGN_EXTEND:
36092     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
36093                        Op, DAG.getValueType(NarrowVT));
36094   }
36095 }
36096 
36097 /// If both input operands of a logic op are being cast from floating point
36098 /// types, try to convert this into a floating point logic node to avoid
36099 /// unnecessary moves from SSE to integer registers.
convertIntLogicToFPLogic(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)36100 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
36101                                         const X86Subtarget &Subtarget) {
36102   unsigned FPOpcode = ISD::DELETED_NODE;
36103   if (N->getOpcode() == ISD::AND)
36104     FPOpcode = X86ISD::FAND;
36105   else if (N->getOpcode() == ISD::OR)
36106     FPOpcode = X86ISD::FOR;
36107   else if (N->getOpcode() == ISD::XOR)
36108     FPOpcode = X86ISD::FXOR;
36109 
36110   assert(FPOpcode != ISD::DELETED_NODE &&
36111          "Unexpected input node for FP logic conversion");
36112 
36113   EVT VT = N->getValueType(0);
36114   SDValue N0 = N->getOperand(0);
36115   SDValue N1 = N->getOperand(1);
36116   SDLoc DL(N);
36117   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
36118       ((Subtarget.hasSSE1() && VT == MVT::i32) ||
36119        (Subtarget.hasSSE2() && VT == MVT::i64))) {
36120     SDValue N00 = N0.getOperand(0);
36121     SDValue N10 = N1.getOperand(0);
36122     EVT N00Type = N00.getValueType();
36123     EVT N10Type = N10.getValueType();
36124     if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
36125       SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
36126       return DAG.getBitcast(VT, FPLogic);
36127     }
36128   }
36129   return SDValue();
36130 }
36131 
36132 /// If this is a zero/all-bits result that is bitwise-anded with a low bits
36133 /// mask. (Mask == 1 for the x86 lowering of a SETCC + ZEXT), replace the 'and'
36134 /// with a shift-right to eliminate loading the vector constant mask value.
combineAndMaskToShift(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)36135 static SDValue combineAndMaskToShift(SDNode *N, SelectionDAG &DAG,
36136                                      const X86Subtarget &Subtarget) {
36137   SDValue Op0 = peekThroughBitcasts(N->getOperand(0));
36138   SDValue Op1 = peekThroughBitcasts(N->getOperand(1));
36139   EVT VT0 = Op0.getValueType();
36140   EVT VT1 = Op1.getValueType();
36141 
36142   if (VT0 != VT1 || !VT0.isSimple() || !VT0.isInteger())
36143     return SDValue();
36144 
36145   APInt SplatVal;
36146   if (!ISD::isConstantSplatVector(Op1.getNode(), SplatVal) ||
36147       !SplatVal.isMask())
36148     return SDValue();
36149 
36150   // Don't prevent creation of ANDN.
36151   if (isBitwiseNot(Op0))
36152     return SDValue();
36153 
36154   if (!SupportedVectorShiftWithImm(VT0.getSimpleVT(), Subtarget, ISD::SRL))
36155     return SDValue();
36156 
36157   unsigned EltBitWidth = VT0.getScalarSizeInBits();
36158   if (EltBitWidth != DAG.ComputeNumSignBits(Op0))
36159     return SDValue();
36160 
36161   SDLoc DL(N);
36162   unsigned ShiftVal = SplatVal.countTrailingOnes();
36163   SDValue ShAmt = DAG.getConstant(EltBitWidth - ShiftVal, DL, MVT::i8);
36164   SDValue Shift = DAG.getNode(X86ISD::VSRLI, DL, VT0, Op0, ShAmt);
36165   return DAG.getBitcast(N->getValueType(0), Shift);
36166 }
36167 
36168 // Get the index node from the lowered DAG of a GEP IR instruction with one
36169 // indexing dimension.
getIndexFromUnindexedLoad(LoadSDNode * Ld)36170 static SDValue getIndexFromUnindexedLoad(LoadSDNode *Ld) {
36171   if (Ld->isIndexed())
36172     return SDValue();
36173 
36174   SDValue Base = Ld->getBasePtr();
36175 
36176   if (Base.getOpcode() != ISD::ADD)
36177     return SDValue();
36178 
36179   SDValue ShiftedIndex = Base.getOperand(0);
36180 
36181   if (ShiftedIndex.getOpcode() != ISD::SHL)
36182     return SDValue();
36183 
36184   return ShiftedIndex.getOperand(0);
36185 
36186 }
36187 
hasBZHI(const X86Subtarget & Subtarget,MVT VT)36188 static bool hasBZHI(const X86Subtarget &Subtarget, MVT VT) {
36189   if (Subtarget.hasBMI2() && VT.isScalarInteger()) {
36190     switch (VT.getSizeInBits()) {
36191     default: return false;
36192     case 64: return Subtarget.is64Bit() ? true : false;
36193     case 32: return true;
36194     }
36195   }
36196   return false;
36197 }
36198 
36199 // This function recognizes cases where X86 bzhi instruction can replace and
36200 // 'and-load' sequence.
36201 // In case of loading integer value from an array of constants which is defined
36202 // as follows:
36203 //
36204 //   int array[SIZE] = {0x0, 0x1, 0x3, 0x7, 0xF ..., 2^(SIZE-1) - 1}
36205 //
36206 // then applying a bitwise and on the result with another input.
36207 // It's equivalent to performing bzhi (zero high bits) on the input, with the
36208 // same index of the load.
combineAndLoadToBZHI(SDNode * Node,SelectionDAG & DAG,const X86Subtarget & Subtarget)36209 static SDValue combineAndLoadToBZHI(SDNode *Node, SelectionDAG &DAG,
36210                                     const X86Subtarget &Subtarget) {
36211   MVT VT = Node->getSimpleValueType(0);
36212   SDLoc dl(Node);
36213 
36214   // Check if subtarget has BZHI instruction for the node's type
36215   if (!hasBZHI(Subtarget, VT))
36216     return SDValue();
36217 
36218   // Try matching the pattern for both operands.
36219   for (unsigned i = 0; i < 2; i++) {
36220     SDValue N = Node->getOperand(i);
36221     LoadSDNode *Ld = dyn_cast<LoadSDNode>(N.getNode());
36222 
36223      // continue if the operand is not a load instruction
36224     if (!Ld)
36225       return SDValue();
36226 
36227     const Value *MemOp = Ld->getMemOperand()->getValue();
36228 
36229     if (!MemOp)
36230       return SDValue();
36231 
36232     if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(MemOp)) {
36233       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) {
36234         if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
36235 
36236           Constant *Init = GV->getInitializer();
36237           Type *Ty = Init->getType();
36238           if (!isa<ConstantDataArray>(Init) ||
36239               !Ty->getArrayElementType()->isIntegerTy() ||
36240               Ty->getArrayElementType()->getScalarSizeInBits() !=
36241                   VT.getSizeInBits() ||
36242               Ty->getArrayNumElements() >
36243                   Ty->getArrayElementType()->getScalarSizeInBits())
36244             continue;
36245 
36246           // Check if the array's constant elements are suitable to our case.
36247           uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
36248           bool ConstantsMatch = true;
36249           for (uint64_t j = 0; j < ArrayElementCount; j++) {
36250             ConstantInt *Elem =
36251                 dyn_cast<ConstantInt>(Init->getAggregateElement(j));
36252             if (Elem->getZExtValue() != (((uint64_t)1 << j) - 1)) {
36253               ConstantsMatch = false;
36254               break;
36255             }
36256           }
36257           if (!ConstantsMatch)
36258             continue;
36259 
36260           // Do the transformation (For 32-bit type):
36261           // -> (and (load arr[idx]), inp)
36262           // <- (and (srl 0xFFFFFFFF, (sub 32, idx)))
36263           //    that will be replaced with one bzhi instruction.
36264           SDValue Inp = (i == 0) ? Node->getOperand(1) : Node->getOperand(0);
36265           SDValue SizeC = DAG.getConstant(VT.getSizeInBits(), dl, MVT::i32);
36266 
36267           // Get the Node which indexes into the array.
36268           SDValue Index = getIndexFromUnindexedLoad(Ld);
36269           if (!Index)
36270             return SDValue();
36271           Index = DAG.getZExtOrTrunc(Index, dl, MVT::i32);
36272 
36273           SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, SizeC, Index);
36274           Sub = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Sub);
36275 
36276           SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
36277           SDValue LShr = DAG.getNode(ISD::SRL, dl, VT, AllOnes, Sub);
36278 
36279           return DAG.getNode(ISD::AND, dl, VT, Inp, LShr);
36280         }
36281       }
36282     }
36283   }
36284   return SDValue();
36285 }
36286 
36287 // Look for (and (ctpop X), 1) which is the IR form of __builtin_parity.
36288 // Turn it into series of XORs and a setnp.
combineParity(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)36289 static SDValue combineParity(SDNode *N, SelectionDAG &DAG,
36290                              const X86Subtarget &Subtarget) {
36291   EVT VT = N->getValueType(0);
36292 
36293   // We only support 64-bit and 32-bit. 64-bit requires special handling
36294   // unless the 64-bit popcnt instruction is legal.
36295   if (VT != MVT::i32 && VT != MVT::i64)
36296     return SDValue();
36297 
36298   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
36299   if (TLI.isTypeLegal(VT) && TLI.isOperationLegal(ISD::CTPOP, VT))
36300     return SDValue();
36301 
36302   SDValue N0 = N->getOperand(0);
36303   SDValue N1 = N->getOperand(1);
36304 
36305   // LHS needs to be a single use CTPOP.
36306   if (N0.getOpcode() != ISD::CTPOP || !N0.hasOneUse())
36307     return SDValue();
36308 
36309   // RHS needs to be 1.
36310   if (!isOneConstant(N1))
36311     return SDValue();
36312 
36313   SDLoc DL(N);
36314   SDValue X = N0.getOperand(0);
36315 
36316   // If this is 64-bit, its always best to xor the two 32-bit pieces together
36317   // even if we have popcnt.
36318   if (VT == MVT::i64) {
36319     SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
36320                              DAG.getNode(ISD::SRL, DL, VT, X,
36321                                          DAG.getConstant(32, DL, MVT::i8)));
36322     SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, X);
36323     X = DAG.getNode(ISD::XOR, DL, MVT::i32, Lo, Hi);
36324     // Generate a 32-bit parity idiom. This will bring us back here if we need
36325     // to expand it too.
36326     SDValue Parity = DAG.getNode(ISD::AND, DL, MVT::i32,
36327                                  DAG.getNode(ISD::CTPOP, DL, MVT::i32, X),
36328                                  DAG.getConstant(1, DL, MVT::i32));
36329     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Parity);
36330   }
36331   assert(VT == MVT::i32 && "Unexpected VT!");
36332 
36333   // Xor the high and low 16-bits together using a 32-bit operation.
36334   SDValue Hi16 = DAG.getNode(ISD::SRL, DL, VT, X,
36335                              DAG.getConstant(16, DL, MVT::i8));
36336   X = DAG.getNode(ISD::XOR, DL, VT, X, Hi16);
36337 
36338   // Finally xor the low 2 bytes together and use a 8-bit flag setting xor.
36339   // This should allow an h-reg to be used to save a shift.
36340   // FIXME: We only get an h-reg in 32-bit mode.
36341   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
36342                            DAG.getNode(ISD::SRL, DL, VT, X,
36343                                        DAG.getConstant(8, DL, MVT::i8)));
36344   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, X);
36345   SDVTList VTs = DAG.getVTList(MVT::i8, MVT::i32);
36346   SDValue Flags = DAG.getNode(X86ISD::XOR, DL, VTs, Lo, Hi).getValue(1);
36347 
36348   // Copy the inverse of the parity flag into a register with setcc.
36349   SDValue Setnp = getSETCC(X86::COND_NP, Flags, DL, DAG);
36350   // Zero extend to original type.
36351   return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0), Setnp);
36352 }
36353 
combineAnd(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)36354 static SDValue combineAnd(SDNode *N, SelectionDAG &DAG,
36355                           TargetLowering::DAGCombinerInfo &DCI,
36356                           const X86Subtarget &Subtarget) {
36357   EVT VT = N->getValueType(0);
36358 
36359   // If this is SSE1 only convert to FAND to avoid scalarization.
36360   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
36361     return DAG.getBitcast(
36362         MVT::v4i32, DAG.getNode(X86ISD::FAND, SDLoc(N), MVT::v4f32,
36363                                 DAG.getBitcast(MVT::v4f32, N->getOperand(0)),
36364                                 DAG.getBitcast(MVT::v4f32, N->getOperand(1))));
36365   }
36366 
36367   // Use a 32-bit and+zext if upper bits known zero.
36368   if (VT == MVT::i64 && Subtarget.is64Bit() &&
36369       !isa<ConstantSDNode>(N->getOperand(1))) {
36370     APInt HiMask = APInt::getHighBitsSet(64, 32);
36371     if (DAG.MaskedValueIsZero(N->getOperand(1), HiMask) ||
36372         DAG.MaskedValueIsZero(N->getOperand(0), HiMask)) {
36373       SDLoc dl(N);
36374       SDValue LHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N->getOperand(0));
36375       SDValue RHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N->getOperand(1));
36376       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64,
36377                          DAG.getNode(ISD::AND, dl, MVT::i32, LHS, RHS));
36378     }
36379   }
36380 
36381   // This must be done before legalization has expanded the ctpop.
36382   if (SDValue V = combineParity(N, DAG, Subtarget))
36383     return V;
36384 
36385   if (DCI.isBeforeLegalizeOps())
36386     return SDValue();
36387 
36388   if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
36389     return R;
36390 
36391   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
36392     return FPLogic;
36393 
36394   if (SDValue R = combineANDXORWithAllOnesIntoANDNP(N, DAG))
36395     return R;
36396 
36397   if (SDValue ShiftRight = combineAndMaskToShift(N, DAG, Subtarget))
36398     return ShiftRight;
36399 
36400   if (SDValue R = combineAndLoadToBZHI(N, DAG, Subtarget))
36401     return R;
36402 
36403   // Attempt to recursively combine a bitmask AND with shuffles.
36404   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
36405     SDValue Op(N, 0);
36406     if (SDValue Res = combineX86ShufflesRecursively(
36407             {Op}, 0, Op, {0}, {}, /*Depth*/ 1,
36408             /*HasVarMask*/ false, /*AllowVarMask*/ true, DAG, Subtarget))
36409       return Res;
36410   }
36411 
36412   // Attempt to combine a scalar bitmask AND with an extracted shuffle.
36413   if ((VT.getScalarSizeInBits() % 8) == 0 &&
36414       N->getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
36415       isa<ConstantSDNode>(N->getOperand(0).getOperand(1))) {
36416     SDValue BitMask = N->getOperand(1);
36417     SDValue SrcVec = N->getOperand(0).getOperand(0);
36418     EVT SrcVecVT = SrcVec.getValueType();
36419 
36420     // Check that the constant bitmask masks whole bytes.
36421     APInt UndefElts;
36422     SmallVector<APInt, 64> EltBits;
36423     if (VT == SrcVecVT.getScalarType() &&
36424         N->getOperand(0)->isOnlyUserOf(SrcVec.getNode()) &&
36425         getTargetConstantBitsFromNode(BitMask, 8, UndefElts, EltBits) &&
36426         llvm::all_of(EltBits, [](APInt M) {
36427           return M.isNullValue() || M.isAllOnesValue();
36428         })) {
36429       unsigned NumElts = SrcVecVT.getVectorNumElements();
36430       unsigned Scale = SrcVecVT.getScalarSizeInBits() / 8;
36431       unsigned Idx = N->getOperand(0).getConstantOperandVal(1);
36432 
36433       // Create a root shuffle mask from the byte mask and the extracted index.
36434       SmallVector<int, 16> ShuffleMask(NumElts * Scale, SM_SentinelUndef);
36435       for (unsigned i = 0; i != Scale; ++i) {
36436         if (UndefElts[i])
36437           continue;
36438         int VecIdx = Scale * Idx + i;
36439         ShuffleMask[VecIdx] =
36440             EltBits[i].isNullValue() ? SM_SentinelZero : VecIdx;
36441       }
36442 
36443       if (SDValue Shuffle = combineX86ShufflesRecursively(
36444               {SrcVec}, 0, SrcVec, ShuffleMask, {}, /*Depth*/ 2,
36445               /*HasVarMask*/ false, /*AllowVarMask*/ true, DAG, Subtarget))
36446         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), VT, Shuffle,
36447                            N->getOperand(0).getOperand(1));
36448     }
36449   }
36450 
36451   return SDValue();
36452 }
36453 
36454 // Try to match OR(AND(~MASK,X),AND(MASK,Y)) logic pattern.
matchLogicBlend(SDNode * N,SDValue & X,SDValue & Y,SDValue & Mask)36455 static bool matchLogicBlend(SDNode *N, SDValue &X, SDValue &Y, SDValue &Mask) {
36456   if (N->getOpcode() != ISD::OR)
36457     return false;
36458 
36459   SDValue N0 = N->getOperand(0);
36460   SDValue N1 = N->getOperand(1);
36461 
36462   // Canonicalize AND to LHS.
36463   if (N1.getOpcode() == ISD::AND)
36464     std::swap(N0, N1);
36465 
36466   // Attempt to match OR(AND(M,Y),ANDNP(M,X)).
36467   if (N0.getOpcode() != ISD::AND || N1.getOpcode() != X86ISD::ANDNP)
36468     return false;
36469 
36470   Mask = N1.getOperand(0);
36471   X = N1.getOperand(1);
36472 
36473   // Check to see if the mask appeared in both the AND and ANDNP.
36474   if (N0.getOperand(0) == Mask)
36475     Y = N0.getOperand(1);
36476   else if (N0.getOperand(1) == Mask)
36477     Y = N0.getOperand(0);
36478   else
36479     return false;
36480 
36481   // TODO: Attempt to match against AND(XOR(-1,M),Y) as well, waiting for
36482   // ANDNP combine allows other combines to happen that prevent matching.
36483   return true;
36484 }
36485 
36486 // Try to fold:
36487 //   (or (and (m, y), (pandn m, x)))
36488 // into:
36489 //   (vselect m, x, y)
36490 // As a special case, try to fold:
36491 //   (or (and (m, (sub 0, x)), (pandn m, x)))
36492 // into:
36493 //   (sub (xor X, M), M)
combineLogicBlendIntoPBLENDV(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)36494 static SDValue combineLogicBlendIntoPBLENDV(SDNode *N, SelectionDAG &DAG,
36495                                             const X86Subtarget &Subtarget) {
36496   assert(N->getOpcode() == ISD::OR && "Unexpected Opcode");
36497 
36498   EVT VT = N->getValueType(0);
36499   if (!((VT.is128BitVector() && Subtarget.hasSSE2()) ||
36500         (VT.is256BitVector() && Subtarget.hasInt256())))
36501     return SDValue();
36502 
36503   SDValue X, Y, Mask;
36504   if (!matchLogicBlend(N, X, Y, Mask))
36505     return SDValue();
36506 
36507   // Validate that X, Y, and Mask are bitcasts, and see through them.
36508   Mask = peekThroughBitcasts(Mask);
36509   X = peekThroughBitcasts(X);
36510   Y = peekThroughBitcasts(Y);
36511 
36512   EVT MaskVT = Mask.getValueType();
36513   unsigned EltBits = MaskVT.getScalarSizeInBits();
36514 
36515   // TODO: Attempt to handle floating point cases as well?
36516   if (!MaskVT.isInteger() || DAG.ComputeNumSignBits(Mask) != EltBits)
36517     return SDValue();
36518 
36519   SDLoc DL(N);
36520 
36521   // Try to match:
36522   //   (or (and (M, (sub 0, X)), (pandn M, X)))
36523   // which is a special case of vselect:
36524   //   (vselect M, (sub 0, X), X)
36525   // Per:
36526   // http://graphics.stanford.edu/~seander/bithacks.html#ConditionalNegate
36527   // We know that, if fNegate is 0 or 1:
36528   //   (fNegate ? -v : v) == ((v ^ -fNegate) + fNegate)
36529   //
36530   // Here, we have a mask, M (all 1s or 0), and, similarly, we know that:
36531   //   ((M & 1) ? -X : X) == ((X ^ -(M & 1)) + (M & 1))
36532   //   ( M      ? -X : X) == ((X ^   M     ) + (M & 1))
36533   // This lets us transform our vselect to:
36534   //   (add (xor X, M), (and M, 1))
36535   // And further to:
36536   //   (sub (xor X, M), M)
36537   if (X.getValueType() == MaskVT && Y.getValueType() == MaskVT &&
36538       DAG.getTargetLoweringInfo().isOperationLegal(ISD::SUB, MaskVT)) {
36539     auto IsNegV = [](SDNode *N, SDValue V) {
36540       return N->getOpcode() == ISD::SUB && N->getOperand(1) == V &&
36541         ISD::isBuildVectorAllZeros(N->getOperand(0).getNode());
36542     };
36543     SDValue V;
36544     if (IsNegV(Y.getNode(), X))
36545       V = X;
36546     else if (IsNegV(X.getNode(), Y))
36547       V = Y;
36548 
36549     if (V) {
36550       SDValue SubOp1 = DAG.getNode(ISD::XOR, DL, MaskVT, V, Mask);
36551       SDValue SubOp2 = Mask;
36552 
36553       // If the negate was on the false side of the select, then
36554       // the operands of the SUB need to be swapped. PR 27251.
36555       // This is because the pattern being matched above is
36556       // (vselect M, (sub (0, X), X)  -> (sub (xor X, M), M)
36557       // but if the pattern matched was
36558       // (vselect M, X, (sub (0, X))), that is really negation of the pattern
36559       // above, -(vselect M, (sub 0, X), X), and therefore the replacement
36560       // pattern also needs to be a negation of the replacement pattern above.
36561       // And -(sub X, Y) is just sub (Y, X), so swapping the operands of the
36562       // sub accomplishes the negation of the replacement pattern.
36563       if (V == Y)
36564          std::swap(SubOp1, SubOp2);
36565 
36566       SDValue Res = DAG.getNode(ISD::SUB, DL, MaskVT, SubOp1, SubOp2);
36567       return DAG.getBitcast(VT, Res);
36568     }
36569   }
36570 
36571   // PBLENDVB is only available on SSE 4.1.
36572   if (!Subtarget.hasSSE41())
36573     return SDValue();
36574 
36575   MVT BlendVT = VT.is256BitVector() ? MVT::v32i8 : MVT::v16i8;
36576 
36577   X = DAG.getBitcast(BlendVT, X);
36578   Y = DAG.getBitcast(BlendVT, Y);
36579   Mask = DAG.getBitcast(BlendVT, Mask);
36580   Mask = DAG.getSelect(DL, BlendVT, Mask, Y, X);
36581   return DAG.getBitcast(VT, Mask);
36582 }
36583 
36584 // Helper function for combineOrCmpEqZeroToCtlzSrl
36585 // Transforms:
36586 //   seteq(cmp x, 0)
36587 //   into:
36588 //   srl(ctlz x), log2(bitsize(x))
36589 // Input pattern is checked by caller.
lowerX86CmpEqZeroToCtlzSrl(SDValue Op,EVT ExtTy,SelectionDAG & DAG)36590 static SDValue lowerX86CmpEqZeroToCtlzSrl(SDValue Op, EVT ExtTy,
36591                                           SelectionDAG &DAG) {
36592   SDValue Cmp = Op.getOperand(1);
36593   EVT VT = Cmp.getOperand(0).getValueType();
36594   unsigned Log2b = Log2_32(VT.getSizeInBits());
36595   SDLoc dl(Op);
36596   SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Cmp->getOperand(0));
36597   // The result of the shift is true or false, and on X86, the 32-bit
36598   // encoding of shr and lzcnt is more desirable.
36599   SDValue Trunc = DAG.getZExtOrTrunc(Clz, dl, MVT::i32);
36600   SDValue Scc = DAG.getNode(ISD::SRL, dl, MVT::i32, Trunc,
36601                             DAG.getConstant(Log2b, dl, MVT::i8));
36602   return DAG.getZExtOrTrunc(Scc, dl, ExtTy);
36603 }
36604 
36605 // Try to transform:
36606 //   zext(or(setcc(eq, (cmp x, 0)), setcc(eq, (cmp y, 0))))
36607 //   into:
36608 //   srl(or(ctlz(x), ctlz(y)), log2(bitsize(x))
36609 // Will also attempt to match more generic cases, eg:
36610 //   zext(or(or(setcc(eq, cmp 0), setcc(eq, cmp 0)), setcc(eq, cmp 0)))
36611 // Only applies if the target supports the FastLZCNT feature.
combineOrCmpEqZeroToCtlzSrl(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)36612 static SDValue combineOrCmpEqZeroToCtlzSrl(SDNode *N, SelectionDAG &DAG,
36613                                            TargetLowering::DAGCombinerInfo &DCI,
36614                                            const X86Subtarget &Subtarget) {
36615   if (DCI.isBeforeLegalize() || !Subtarget.getTargetLowering()->isCtlzFast())
36616     return SDValue();
36617 
36618   auto isORCandidate = [](SDValue N) {
36619     return (N->getOpcode() == ISD::OR && N->hasOneUse());
36620   };
36621 
36622   // Check the zero extend is extending to 32-bit or more. The code generated by
36623   // srl(ctlz) for 16-bit or less variants of the pattern would require extra
36624   // instructions to clear the upper bits.
36625   if (!N->hasOneUse() || !N->getSimpleValueType(0).bitsGE(MVT::i32) ||
36626       !isORCandidate(N->getOperand(0)))
36627     return SDValue();
36628 
36629   // Check the node matches: setcc(eq, cmp 0)
36630   auto isSetCCCandidate = [](SDValue N) {
36631     return N->getOpcode() == X86ISD::SETCC && N->hasOneUse() &&
36632            X86::CondCode(N->getConstantOperandVal(0)) == X86::COND_E &&
36633            N->getOperand(1).getOpcode() == X86ISD::CMP &&
36634            isNullConstant(N->getOperand(1).getOperand(1)) &&
36635            N->getOperand(1).getValueType().bitsGE(MVT::i32);
36636   };
36637 
36638   SDNode *OR = N->getOperand(0).getNode();
36639   SDValue LHS = OR->getOperand(0);
36640   SDValue RHS = OR->getOperand(1);
36641 
36642   // Save nodes matching or(or, setcc(eq, cmp 0)).
36643   SmallVector<SDNode *, 2> ORNodes;
36644   while (((isORCandidate(LHS) && isSetCCCandidate(RHS)) ||
36645           (isORCandidate(RHS) && isSetCCCandidate(LHS)))) {
36646     ORNodes.push_back(OR);
36647     OR = (LHS->getOpcode() == ISD::OR) ? LHS.getNode() : RHS.getNode();
36648     LHS = OR->getOperand(0);
36649     RHS = OR->getOperand(1);
36650   }
36651 
36652   // The last OR node should match or(setcc(eq, cmp 0), setcc(eq, cmp 0)).
36653   if (!(isSetCCCandidate(LHS) && isSetCCCandidate(RHS)) ||
36654       !isORCandidate(SDValue(OR, 0)))
36655     return SDValue();
36656 
36657   // We have a or(setcc(eq, cmp 0), setcc(eq, cmp 0)) pattern, try to lower it
36658   // to
36659   // or(srl(ctlz),srl(ctlz)).
36660   // The dag combiner can then fold it into:
36661   // srl(or(ctlz, ctlz)).
36662   EVT VT = OR->getValueType(0);
36663   SDValue NewLHS = lowerX86CmpEqZeroToCtlzSrl(LHS, VT, DAG);
36664   SDValue Ret, NewRHS;
36665   if (NewLHS && (NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, VT, DAG)))
36666     Ret = DAG.getNode(ISD::OR, SDLoc(OR), VT, NewLHS, NewRHS);
36667 
36668   if (!Ret)
36669     return SDValue();
36670 
36671   // Try to lower nodes matching the or(or, setcc(eq, cmp 0)) pattern.
36672   while (ORNodes.size() > 0) {
36673     OR = ORNodes.pop_back_val();
36674     LHS = OR->getOperand(0);
36675     RHS = OR->getOperand(1);
36676     // Swap rhs with lhs to match or(setcc(eq, cmp, 0), or).
36677     if (RHS->getOpcode() == ISD::OR)
36678       std::swap(LHS, RHS);
36679     EVT VT = OR->getValueType(0);
36680     SDValue NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, VT, DAG);
36681     if (!NewRHS)
36682       return SDValue();
36683     Ret = DAG.getNode(ISD::OR, SDLoc(OR), VT, Ret, NewRHS);
36684   }
36685 
36686   if (Ret)
36687     Ret = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), Ret);
36688 
36689   return Ret;
36690 }
36691 
combineOr(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)36692 static SDValue combineOr(SDNode *N, SelectionDAG &DAG,
36693                          TargetLowering::DAGCombinerInfo &DCI,
36694                          const X86Subtarget &Subtarget) {
36695   SDValue N0 = N->getOperand(0);
36696   SDValue N1 = N->getOperand(1);
36697   EVT VT = N->getValueType(0);
36698 
36699   // If this is SSE1 only convert to FOR to avoid scalarization.
36700   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
36701     return DAG.getBitcast(MVT::v4i32,
36702                           DAG.getNode(X86ISD::FOR, SDLoc(N), MVT::v4f32,
36703                                       DAG.getBitcast(MVT::v4f32, N0),
36704                                       DAG.getBitcast(MVT::v4f32, N1)));
36705   }
36706 
36707   if (DCI.isBeforeLegalizeOps())
36708     return SDValue();
36709 
36710   if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
36711     return R;
36712 
36713   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
36714     return FPLogic;
36715 
36716   if (SDValue R = combineLogicBlendIntoPBLENDV(N, DAG, Subtarget))
36717     return R;
36718 
36719   // Attempt to recursively combine an OR of shuffles.
36720   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
36721     SDValue Op(N, 0);
36722     if (SDValue Res = combineX86ShufflesRecursively(
36723             {Op}, 0, Op, {0}, {}, /*Depth*/ 1,
36724             /*HasVarMask*/ false, /*AllowVarMask*/ true, DAG, Subtarget))
36725       return Res;
36726   }
36727 
36728   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
36729     return SDValue();
36730 
36731   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
36732   bool OptForSize = DAG.getMachineFunction().getFunction().optForSize();
36733   unsigned Bits = VT.getScalarSizeInBits();
36734 
36735   // SHLD/SHRD instructions have lower register pressure, but on some
36736   // platforms they have higher latency than the equivalent
36737   // series of shifts/or that would otherwise be generated.
36738   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
36739   // have higher latencies and we are not optimizing for size.
36740   if (!OptForSize && Subtarget.isSHLDSlow())
36741     return SDValue();
36742 
36743   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
36744     std::swap(N0, N1);
36745   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
36746     return SDValue();
36747   if (!N0.hasOneUse() || !N1.hasOneUse())
36748     return SDValue();
36749 
36750   SDValue ShAmt0 = N0.getOperand(1);
36751   if (ShAmt0.getValueType() != MVT::i8)
36752     return SDValue();
36753   SDValue ShAmt1 = N1.getOperand(1);
36754   if (ShAmt1.getValueType() != MVT::i8)
36755     return SDValue();
36756 
36757   // Peek through any modulo shift masks.
36758   SDValue ShMsk0;
36759   if (ShAmt0.getOpcode() == ISD::AND &&
36760       isa<ConstantSDNode>(ShAmt0.getOperand(1)) &&
36761       ShAmt0.getConstantOperandVal(1) == (Bits - 1)) {
36762     ShMsk0 = ShAmt0;
36763     ShAmt0 = ShAmt0.getOperand(0);
36764   }
36765   SDValue ShMsk1;
36766   if (ShAmt1.getOpcode() == ISD::AND &&
36767       isa<ConstantSDNode>(ShAmt1.getOperand(1)) &&
36768       ShAmt1.getConstantOperandVal(1) == (Bits - 1)) {
36769     ShMsk1 = ShAmt1;
36770     ShAmt1 = ShAmt1.getOperand(0);
36771   }
36772 
36773   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
36774     ShAmt0 = ShAmt0.getOperand(0);
36775   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
36776     ShAmt1 = ShAmt1.getOperand(0);
36777 
36778   SDLoc DL(N);
36779   unsigned Opc = X86ISD::SHLD;
36780   SDValue Op0 = N0.getOperand(0);
36781   SDValue Op1 = N1.getOperand(0);
36782   if (ShAmt0.getOpcode() == ISD::SUB ||
36783       ShAmt0.getOpcode() == ISD::XOR) {
36784     Opc = X86ISD::SHRD;
36785     std::swap(Op0, Op1);
36786     std::swap(ShAmt0, ShAmt1);
36787     std::swap(ShMsk0, ShMsk1);
36788   }
36789 
36790   // OR( SHL( X, C ), SRL( Y, 32 - C ) ) -> SHLD( X, Y, C )
36791   // OR( SRL( X, C ), SHL( Y, 32 - C ) ) -> SHRD( X, Y, C )
36792   // OR( SHL( X, C ), SRL( SRL( Y, 1 ), XOR( C, 31 ) ) ) -> SHLD( X, Y, C )
36793   // OR( SRL( X, C ), SHL( SHL( Y, 1 ), XOR( C, 31 ) ) ) -> SHRD( X, Y, C )
36794   // OR( SHL( X, AND( C, 31 ) ), SRL( Y, AND( 0 - C, 31 ) ) ) -> SHLD( X, Y, C )
36795   // OR( SRL( X, AND( C, 31 ) ), SHL( Y, AND( 0 - C, 31 ) ) ) -> SHRD( X, Y, C )
36796   if (ShAmt1.getOpcode() == ISD::SUB) {
36797     SDValue Sum = ShAmt1.getOperand(0);
36798     if (auto *SumC = dyn_cast<ConstantSDNode>(Sum)) {
36799       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
36800       if (ShAmt1Op1.getOpcode() == ISD::TRUNCATE)
36801         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
36802       if ((SumC->getAPIntValue() == Bits ||
36803            (SumC->getAPIntValue() == 0 && ShMsk1)) &&
36804           ShAmt1Op1 == ShAmt0)
36805         return DAG.getNode(Opc, DL, VT, Op0, Op1,
36806                            DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ShAmt0));
36807     }
36808   } else if (auto *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
36809     auto *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
36810     if (ShAmt0C && (ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue()) == Bits)
36811       return DAG.getNode(Opc, DL, VT,
36812                          N0.getOperand(0), N1.getOperand(0),
36813                          DAG.getNode(ISD::TRUNCATE, DL,
36814                                        MVT::i8, ShAmt0));
36815   } else if (ShAmt1.getOpcode() == ISD::XOR) {
36816     SDValue Mask = ShAmt1.getOperand(1);
36817     if (auto *MaskC = dyn_cast<ConstantSDNode>(Mask)) {
36818       unsigned InnerShift = (X86ISD::SHLD == Opc ? ISD::SRL : ISD::SHL);
36819       SDValue ShAmt1Op0 = ShAmt1.getOperand(0);
36820       if (ShAmt1Op0.getOpcode() == ISD::TRUNCATE)
36821         ShAmt1Op0 = ShAmt1Op0.getOperand(0);
36822       if (MaskC->getSExtValue() == (Bits - 1) &&
36823           (ShAmt1Op0 == ShAmt0 || ShAmt1Op0 == ShMsk0)) {
36824         if (Op1.getOpcode() == InnerShift &&
36825             isa<ConstantSDNode>(Op1.getOperand(1)) &&
36826             Op1.getConstantOperandVal(1) == 1) {
36827           return DAG.getNode(Opc, DL, VT, Op0, Op1.getOperand(0),
36828                              DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ShAmt0));
36829         }
36830         // Test for ADD( Y, Y ) as an equivalent to SHL( Y, 1 ).
36831         if (InnerShift == ISD::SHL && Op1.getOpcode() == ISD::ADD &&
36832             Op1.getOperand(0) == Op1.getOperand(1)) {
36833           return DAG.getNode(Opc, DL, VT, Op0, Op1.getOperand(0),
36834                              DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ShAmt0));
36835         }
36836       }
36837     }
36838   }
36839 
36840   return SDValue();
36841 }
36842 
36843 /// Try to turn tests against the signbit in the form of:
36844 ///   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
36845 /// into:
36846 ///   SETGT(X, -1)
foldXorTruncShiftIntoCmp(SDNode * N,SelectionDAG & DAG)36847 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
36848   // This is only worth doing if the output type is i8 or i1.
36849   EVT ResultType = N->getValueType(0);
36850   if (ResultType != MVT::i8 && ResultType != MVT::i1)
36851     return SDValue();
36852 
36853   SDValue N0 = N->getOperand(0);
36854   SDValue N1 = N->getOperand(1);
36855 
36856   // We should be performing an xor against a truncated shift.
36857   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
36858     return SDValue();
36859 
36860   // Make sure we are performing an xor against one.
36861   if (!isOneConstant(N1))
36862     return SDValue();
36863 
36864   // SetCC on x86 zero extends so only act on this if it's a logical shift.
36865   SDValue Shift = N0.getOperand(0);
36866   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
36867     return SDValue();
36868 
36869   // Make sure we are truncating from one of i16, i32 or i64.
36870   EVT ShiftTy = Shift.getValueType();
36871   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
36872     return SDValue();
36873 
36874   // Make sure the shift amount extracts the sign bit.
36875   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
36876       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
36877     return SDValue();
36878 
36879   // Create a greater-than comparison against -1.
36880   // N.B. Using SETGE against 0 works but we want a canonical looking
36881   // comparison, using SETGT matches up with what TranslateX86CC.
36882   SDLoc DL(N);
36883   SDValue ShiftOp = Shift.getOperand(0);
36884   EVT ShiftOpTy = ShiftOp.getValueType();
36885   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
36886   EVT SetCCResultType = TLI.getSetCCResultType(DAG.getDataLayout(),
36887                                                *DAG.getContext(), ResultType);
36888   SDValue Cond = DAG.getSetCC(DL, SetCCResultType, ShiftOp,
36889                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
36890   if (SetCCResultType != ResultType)
36891     Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, ResultType, Cond);
36892   return Cond;
36893 }
36894 
36895 /// Turn vector tests of the signbit in the form of:
36896 ///   xor (sra X, elt_size(X)-1), -1
36897 /// into:
36898 ///   pcmpgt X, -1
36899 ///
36900 /// This should be called before type legalization because the pattern may not
36901 /// persist after that.
foldVectorXorShiftIntoCmp(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)36902 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
36903                                          const X86Subtarget &Subtarget) {
36904   EVT VT = N->getValueType(0);
36905   if (!VT.isSimple())
36906     return SDValue();
36907 
36908   switch (VT.getSimpleVT().SimpleTy) {
36909   default: return SDValue();
36910   case MVT::v16i8:
36911   case MVT::v8i16:
36912   case MVT::v4i32: if (!Subtarget.hasSSE2()) return SDValue(); break;
36913   case MVT::v2i64: if (!Subtarget.hasSSE42()) return SDValue(); break;
36914   case MVT::v32i8:
36915   case MVT::v16i16:
36916   case MVT::v8i32:
36917   case MVT::v4i64: if (!Subtarget.hasAVX2()) return SDValue(); break;
36918   }
36919 
36920   // There must be a shift right algebraic before the xor, and the xor must be a
36921   // 'not' operation.
36922   SDValue Shift = N->getOperand(0);
36923   SDValue Ones = N->getOperand(1);
36924   if (Shift.getOpcode() != ISD::SRA || !Shift.hasOneUse() ||
36925       !ISD::isBuildVectorAllOnes(Ones.getNode()))
36926     return SDValue();
36927 
36928   // The shift should be smearing the sign bit across each vector element.
36929   auto *ShiftBV = dyn_cast<BuildVectorSDNode>(Shift.getOperand(1));
36930   if (!ShiftBV)
36931     return SDValue();
36932 
36933   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
36934   auto *ShiftAmt = ShiftBV->getConstantSplatNode();
36935   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
36936     return SDValue();
36937 
36938   // Create a greater-than comparison against -1. We don't use the more obvious
36939   // greater-than-or-equal-to-zero because SSE/AVX don't have that instruction.
36940   return DAG.getNode(X86ISD::PCMPGT, SDLoc(N), VT, Shift.getOperand(0), Ones);
36941 }
36942 
36943 /// Check if truncation with saturation form type \p SrcVT to \p DstVT
36944 /// is valid for the given \p Subtarget.
isSATValidOnAVX512Subtarget(EVT SrcVT,EVT DstVT,const X86Subtarget & Subtarget)36945 static bool isSATValidOnAVX512Subtarget(EVT SrcVT, EVT DstVT,
36946                                         const X86Subtarget &Subtarget) {
36947   if (!Subtarget.hasAVX512())
36948     return false;
36949 
36950   // FIXME: Scalar type may be supported if we move it to vector register.
36951   if (!SrcVT.isVector())
36952     return false;
36953 
36954   EVT SrcElVT = SrcVT.getScalarType();
36955   EVT DstElVT = DstVT.getScalarType();
36956   if (DstElVT != MVT::i8 && DstElVT != MVT::i16 && DstElVT != MVT::i32)
36957     return false;
36958   if (SrcVT.is512BitVector() || Subtarget.hasVLX())
36959     return SrcElVT.getSizeInBits() >= 32 || Subtarget.hasBWI();
36960   return false;
36961 }
36962 
36963 /// Detect patterns of truncation with unsigned saturation:
36964 ///
36965 /// 1. (truncate (umin (x, unsigned_max_of_dest_type)) to dest_type).
36966 ///   Return the source value x to be truncated or SDValue() if the pattern was
36967 ///   not matched.
36968 ///
36969 /// 2. (truncate (smin (smax (x, C1), C2)) to dest_type),
36970 ///   where C1 >= 0 and C2 is unsigned max of destination type.
36971 ///
36972 ///    (truncate (smax (smin (x, C2), C1)) to dest_type)
36973 ///   where C1 >= 0, C2 is unsigned max of destination type and C1 <= C2.
36974 ///
36975 ///   These two patterns are equivalent to:
36976 ///   (truncate (umin (smax(x, C1), unsigned_max_of_dest_type)) to dest_type)
36977 ///   So return the smax(x, C1) value to be truncated or SDValue() if the
36978 ///   pattern was not matched.
detectUSatPattern(SDValue In,EVT VT,SelectionDAG & DAG,const SDLoc & DL)36979 static SDValue detectUSatPattern(SDValue In, EVT VT, SelectionDAG &DAG,
36980                                  const SDLoc &DL) {
36981   EVT InVT = In.getValueType();
36982 
36983   // Saturation with truncation. We truncate from InVT to VT.
36984   assert(InVT.getScalarSizeInBits() > VT.getScalarSizeInBits() &&
36985          "Unexpected types for truncate operation");
36986 
36987   // Match min/max and return limit value as a parameter.
36988   auto MatchMinMax = [](SDValue V, unsigned Opcode, APInt &Limit) -> SDValue {
36989     if (V.getOpcode() == Opcode &&
36990         ISD::isConstantSplatVector(V.getOperand(1).getNode(), Limit))
36991       return V.getOperand(0);
36992     return SDValue();
36993   };
36994 
36995   APInt C1, C2;
36996   if (SDValue UMin = MatchMinMax(In, ISD::UMIN, C2))
36997     // C2 should be equal to UINT32_MAX / UINT16_MAX / UINT8_MAX according
36998     // the element size of the destination type.
36999     if (C2.isMask(VT.getScalarSizeInBits()))
37000       return UMin;
37001 
37002   if (SDValue SMin = MatchMinMax(In, ISD::SMIN, C2))
37003     if (MatchMinMax(SMin, ISD::SMAX, C1))
37004       if (C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()))
37005         return SMin;
37006 
37007   if (SDValue SMax = MatchMinMax(In, ISD::SMAX, C1))
37008     if (SDValue SMin = MatchMinMax(SMax, ISD::SMIN, C2))
37009       if (C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()) &&
37010           C2.uge(C1)) {
37011         return DAG.getNode(ISD::SMAX, DL, InVT, SMin, In.getOperand(1));
37012       }
37013 
37014   return SDValue();
37015 }
37016 
37017 /// Detect patterns of truncation with signed saturation:
37018 /// (truncate (smin ((smax (x, signed_min_of_dest_type)),
37019 ///                  signed_max_of_dest_type)) to dest_type)
37020 /// or:
37021 /// (truncate (smax ((smin (x, signed_max_of_dest_type)),
37022 ///                  signed_min_of_dest_type)) to dest_type).
37023 /// With MatchPackUS, the smax/smin range is [0, unsigned_max_of_dest_type].
37024 /// Return the source value to be truncated or SDValue() if the pattern was not
37025 /// matched.
detectSSatPattern(SDValue In,EVT VT,bool MatchPackUS=false)37026 static SDValue detectSSatPattern(SDValue In, EVT VT, bool MatchPackUS = false) {
37027   unsigned NumDstBits = VT.getScalarSizeInBits();
37028   unsigned NumSrcBits = In.getScalarValueSizeInBits();
37029   assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
37030 
37031   auto MatchMinMax = [](SDValue V, unsigned Opcode,
37032                         const APInt &Limit) -> SDValue {
37033     APInt C;
37034     if (V.getOpcode() == Opcode &&
37035         ISD::isConstantSplatVector(V.getOperand(1).getNode(), C) && C == Limit)
37036       return V.getOperand(0);
37037     return SDValue();
37038   };
37039 
37040   APInt SignedMax, SignedMin;
37041   if (MatchPackUS) {
37042     SignedMax = APInt::getAllOnesValue(NumDstBits).zext(NumSrcBits);
37043     SignedMin = APInt(NumSrcBits, 0);
37044   } else {
37045     SignedMax = APInt::getSignedMaxValue(NumDstBits).sext(NumSrcBits);
37046     SignedMin = APInt::getSignedMinValue(NumDstBits).sext(NumSrcBits);
37047   }
37048 
37049   if (SDValue SMin = MatchMinMax(In, ISD::SMIN, SignedMax))
37050     if (SDValue SMax = MatchMinMax(SMin, ISD::SMAX, SignedMin))
37051       return SMax;
37052 
37053   if (SDValue SMax = MatchMinMax(In, ISD::SMAX, SignedMin))
37054     if (SDValue SMin = MatchMinMax(SMax, ISD::SMIN, SignedMax))
37055       return SMin;
37056 
37057   return SDValue();
37058 }
37059 
37060 /// Detect a pattern of truncation with signed saturation.
37061 /// The types should allow to use VPMOVSS* instruction on AVX512.
37062 /// Return the source value to be truncated or SDValue() if the pattern was not
37063 /// matched.
detectAVX512SSatPattern(SDValue In,EVT VT,const X86Subtarget & Subtarget,const TargetLowering & TLI)37064 static SDValue detectAVX512SSatPattern(SDValue In, EVT VT,
37065                                        const X86Subtarget &Subtarget,
37066                                        const TargetLowering &TLI) {
37067   if (!TLI.isTypeLegal(In.getValueType()))
37068     return SDValue();
37069   if (!isSATValidOnAVX512Subtarget(In.getValueType(), VT, Subtarget))
37070     return SDValue();
37071   return detectSSatPattern(In, VT);
37072 }
37073 
37074 /// Detect a pattern of truncation with saturation:
37075 /// (truncate (umin (x, unsigned_max_of_dest_type)) to dest_type).
37076 /// The types should allow to use VPMOVUS* instruction on AVX512.
37077 /// Return the source value to be truncated or SDValue() if the pattern was not
37078 /// matched.
detectAVX512USatPattern(SDValue In,EVT VT,SelectionDAG & DAG,const SDLoc & DL,const X86Subtarget & Subtarget,const TargetLowering & TLI)37079 static SDValue detectAVX512USatPattern(SDValue In, EVT VT, SelectionDAG &DAG,
37080                                        const SDLoc &DL,
37081                                        const X86Subtarget &Subtarget,
37082                                        const TargetLowering &TLI) {
37083   if (!TLI.isTypeLegal(In.getValueType()))
37084     return SDValue();
37085   if (!isSATValidOnAVX512Subtarget(In.getValueType(), VT, Subtarget))
37086     return SDValue();
37087   return detectUSatPattern(In, VT, DAG, DL);
37088 }
37089 
combineTruncateWithSat(SDValue In,EVT VT,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)37090 static SDValue combineTruncateWithSat(SDValue In, EVT VT, const SDLoc &DL,
37091                                       SelectionDAG &DAG,
37092                                       const X86Subtarget &Subtarget) {
37093   EVT SVT = VT.getScalarType();
37094   EVT InVT = In.getValueType();
37095   EVT InSVT = InVT.getScalarType();
37096   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
37097   if (TLI.isTypeLegal(InVT) && TLI.isTypeLegal(VT) &&
37098       isSATValidOnAVX512Subtarget(InVT, VT, Subtarget)) {
37099     if (auto SSatVal = detectSSatPattern(In, VT))
37100       return DAG.getNode(X86ISD::VTRUNCS, DL, VT, SSatVal);
37101     if (auto USatVal = detectUSatPattern(In, VT, DAG, DL))
37102       return DAG.getNode(X86ISD::VTRUNCUS, DL, VT, USatVal);
37103   }
37104   if (VT.isVector() && isPowerOf2_32(VT.getVectorNumElements()) &&
37105       !Subtarget.hasAVX512() &&
37106       (SVT == MVT::i8 || SVT == MVT::i16) &&
37107       (InSVT == MVT::i16 || InSVT == MVT::i32)) {
37108     if (auto USatVal = detectSSatPattern(In, VT, true)) {
37109       // vXi32 -> vXi8 must be performed as PACKUSWB(PACKSSDW,PACKSSDW).
37110       if (SVT == MVT::i8 && InSVT == MVT::i32) {
37111         EVT MidVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
37112                                      VT.getVectorNumElements());
37113         SDValue Mid = truncateVectorWithPACK(X86ISD::PACKSS, MidVT, USatVal, DL,
37114                                              DAG, Subtarget);
37115         if (Mid)
37116           return truncateVectorWithPACK(X86ISD::PACKUS, VT, Mid, DL, DAG,
37117                                         Subtarget);
37118       } else if (SVT == MVT::i8 || Subtarget.hasSSE41())
37119         return truncateVectorWithPACK(X86ISD::PACKUS, VT, USatVal, DL, DAG,
37120                                       Subtarget);
37121     }
37122     if (auto SSatVal = detectSSatPattern(In, VT))
37123       return truncateVectorWithPACK(X86ISD::PACKSS, VT, SSatVal, DL, DAG,
37124                                     Subtarget);
37125   }
37126   return SDValue();
37127 }
37128 
37129 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
37130 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
37131 /// X86ISD::AVG instruction.
detectAVGPattern(SDValue In,EVT VT,SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & DL)37132 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
37133                                 const X86Subtarget &Subtarget,
37134                                 const SDLoc &DL) {
37135   if (!VT.isVector())
37136     return SDValue();
37137   EVT InVT = In.getValueType();
37138   unsigned NumElems = VT.getVectorNumElements();
37139 
37140   EVT ScalarVT = VT.getVectorElementType();
37141   if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
37142         NumElems >= 2 && isPowerOf2_32(NumElems)))
37143     return SDValue();
37144 
37145   // InScalarVT is the intermediate type in AVG pattern and it should be greater
37146   // than the original input type (i8/i16).
37147   EVT InScalarVT = InVT.getVectorElementType();
37148   if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
37149     return SDValue();
37150 
37151   if (!Subtarget.hasSSE2())
37152     return SDValue();
37153 
37154   // Detect the following pattern:
37155   //
37156   //   %1 = zext <N x i8> %a to <N x i32>
37157   //   %2 = zext <N x i8> %b to <N x i32>
37158   //   %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
37159   //   %4 = add nuw nsw <N x i32> %3, %2
37160   //   %5 = lshr <N x i32> %N, <i32 1 x N>
37161   //   %6 = trunc <N x i32> %5 to <N x i8>
37162   //
37163   // In AVX512, the last instruction can also be a trunc store.
37164   if (In.getOpcode() != ISD::SRL)
37165     return SDValue();
37166 
37167   // A lambda checking the given SDValue is a constant vector and each element
37168   // is in the range [Min, Max].
37169   auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
37170     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(V);
37171     if (!BV || !BV->isConstant())
37172       return false;
37173     for (SDValue Op : V->ops()) {
37174       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
37175       if (!C)
37176         return false;
37177       const APInt &Val = C->getAPIntValue();
37178       if (Val.ult(Min) || Val.ugt(Max))
37179         return false;
37180     }
37181     return true;
37182   };
37183 
37184   // Check if each element of the vector is left-shifted by one.
37185   auto LHS = In.getOperand(0);
37186   auto RHS = In.getOperand(1);
37187   if (!IsConstVectorInRange(RHS, 1, 1))
37188     return SDValue();
37189   if (LHS.getOpcode() != ISD::ADD)
37190     return SDValue();
37191 
37192   // Detect a pattern of a + b + 1 where the order doesn't matter.
37193   SDValue Operands[3];
37194   Operands[0] = LHS.getOperand(0);
37195   Operands[1] = LHS.getOperand(1);
37196 
37197   auto AVGBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
37198                        ArrayRef<SDValue> Ops) {
37199     return DAG.getNode(X86ISD::AVG, DL, Ops[0].getValueType(), Ops);
37200   };
37201 
37202   // Take care of the case when one of the operands is a constant vector whose
37203   // element is in the range [1, 256].
37204   if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
37205       Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
37206       Operands[0].getOperand(0).getValueType() == VT) {
37207     // The pattern is detected. Subtract one from the constant vector, then
37208     // demote it and emit X86ISD::AVG instruction.
37209     SDValue VecOnes = DAG.getConstant(1, DL, InVT);
37210     Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], VecOnes);
37211     Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
37212     return SplitOpsAndApply(DAG, Subtarget, DL, VT,
37213                             { Operands[0].getOperand(0), Operands[1] },
37214                             AVGBuilder);
37215   }
37216 
37217   if (Operands[0].getOpcode() == ISD::ADD)
37218     std::swap(Operands[0], Operands[1]);
37219   else if (Operands[1].getOpcode() != ISD::ADD)
37220     return SDValue();
37221   Operands[2] = Operands[1].getOperand(0);
37222   Operands[1] = Operands[1].getOperand(1);
37223 
37224   // Now we have three operands of two additions. Check that one of them is a
37225   // constant vector with ones, and the other two are promoted from i8/i16.
37226   for (int i = 0; i < 3; ++i) {
37227     if (!IsConstVectorInRange(Operands[i], 1, 1))
37228       continue;
37229     std::swap(Operands[i], Operands[2]);
37230 
37231     // Check if Operands[0] and Operands[1] are results of type promotion.
37232     for (int j = 0; j < 2; ++j)
37233       if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
37234           Operands[j].getOperand(0).getValueType() != VT)
37235         return SDValue();
37236 
37237     // The pattern is detected, emit X86ISD::AVG instruction(s).
37238     return SplitOpsAndApply(DAG, Subtarget, DL, VT,
37239                             { Operands[0].getOperand(0),
37240                               Operands[1].getOperand(0) }, AVGBuilder);
37241   }
37242 
37243   return SDValue();
37244 }
37245 
combineLoad(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)37246 static SDValue combineLoad(SDNode *N, SelectionDAG &DAG,
37247                            TargetLowering::DAGCombinerInfo &DCI,
37248                            const X86Subtarget &Subtarget) {
37249   LoadSDNode *Ld = cast<LoadSDNode>(N);
37250   EVT RegVT = Ld->getValueType(0);
37251   EVT MemVT = Ld->getMemoryVT();
37252   SDLoc dl(Ld);
37253   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
37254 
37255   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
37256   // into two 16-byte operations. Also split non-temporal aligned loads on
37257   // pre-AVX2 targets as 32-byte loads will lower to regular temporal loads.
37258   ISD::LoadExtType Ext = Ld->getExtensionType();
37259   bool Fast;
37260   unsigned AddressSpace = Ld->getAddressSpace();
37261   unsigned Alignment = Ld->getAlignment();
37262   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
37263       Ext == ISD::NON_EXTLOAD &&
37264       ((Ld->isNonTemporal() && !Subtarget.hasInt256() && Alignment >= 16) ||
37265        (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
37266                                AddressSpace, Alignment, &Fast) && !Fast))) {
37267     unsigned NumElems = RegVT.getVectorNumElements();
37268     if (NumElems < 2)
37269       return SDValue();
37270 
37271     SDValue Ptr = Ld->getBasePtr();
37272 
37273     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
37274                                   NumElems/2);
37275     SDValue Load1 =
37276         DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
37277                     Alignment, Ld->getMemOperand()->getFlags());
37278 
37279     Ptr = DAG.getMemBasePlusOffset(Ptr, 16, dl);
37280     SDValue Load2 =
37281         DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
37282                     Ld->getPointerInfo().getWithOffset(16),
37283                     MinAlign(Alignment, 16U), Ld->getMemOperand()->getFlags());
37284     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
37285                              Load1.getValue(1),
37286                              Load2.getValue(1));
37287 
37288     SDValue NewVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Load1, Load2);
37289     return DCI.CombineTo(N, NewVec, TF, true);
37290   }
37291 
37292   return SDValue();
37293 }
37294 
37295 /// If V is a build vector of boolean constants and exactly one of those
37296 /// constants is true, return the operand index of that true element.
37297 /// Otherwise, return -1.
getOneTrueElt(SDValue V)37298 static int getOneTrueElt(SDValue V) {
37299   // This needs to be a build vector of booleans.
37300   // TODO: Checking for the i1 type matches the IR definition for the mask,
37301   // but the mask check could be loosened to i8 or other types. That might
37302   // also require checking more than 'allOnesValue'; eg, the x86 HW
37303   // instructions only require that the MSB is set for each mask element.
37304   // The ISD::MSTORE comments/definition do not specify how the mask operand
37305   // is formatted.
37306   auto *BV = dyn_cast<BuildVectorSDNode>(V);
37307   if (!BV || BV->getValueType(0).getVectorElementType() != MVT::i1)
37308     return -1;
37309 
37310   int TrueIndex = -1;
37311   unsigned NumElts = BV->getValueType(0).getVectorNumElements();
37312   for (unsigned i = 0; i < NumElts; ++i) {
37313     const SDValue &Op = BV->getOperand(i);
37314     if (Op.isUndef())
37315       continue;
37316     auto *ConstNode = dyn_cast<ConstantSDNode>(Op);
37317     if (!ConstNode)
37318       return -1;
37319     if (ConstNode->getAPIntValue().isAllOnesValue()) {
37320       // If we already found a one, this is too many.
37321       if (TrueIndex >= 0)
37322         return -1;
37323       TrueIndex = i;
37324     }
37325   }
37326   return TrueIndex;
37327 }
37328 
37329 /// Given a masked memory load/store operation, return true if it has one mask
37330 /// bit set. If it has one mask bit set, then also return the memory address of
37331 /// the scalar element to load/store, the vector index to insert/extract that
37332 /// scalar element, and the alignment for the scalar memory access.
getParamsForOneTrueMaskedElt(MaskedLoadStoreSDNode * MaskedOp,SelectionDAG & DAG,SDValue & Addr,SDValue & Index,unsigned & Alignment)37333 static bool getParamsForOneTrueMaskedElt(MaskedLoadStoreSDNode *MaskedOp,
37334                                          SelectionDAG &DAG, SDValue &Addr,
37335                                          SDValue &Index, unsigned &Alignment) {
37336   int TrueMaskElt = getOneTrueElt(MaskedOp->getMask());
37337   if (TrueMaskElt < 0)
37338     return false;
37339 
37340   // Get the address of the one scalar element that is specified by the mask
37341   // using the appropriate offset from the base pointer.
37342   EVT EltVT = MaskedOp->getMemoryVT().getVectorElementType();
37343   Addr = MaskedOp->getBasePtr();
37344   if (TrueMaskElt != 0) {
37345     unsigned Offset = TrueMaskElt * EltVT.getStoreSize();
37346     Addr = DAG.getMemBasePlusOffset(Addr, Offset, SDLoc(MaskedOp));
37347   }
37348 
37349   Index = DAG.getIntPtrConstant(TrueMaskElt, SDLoc(MaskedOp));
37350   Alignment = MinAlign(MaskedOp->getAlignment(), EltVT.getStoreSize());
37351   return true;
37352 }
37353 
37354 /// If exactly one element of the mask is set for a non-extending masked load,
37355 /// it is a scalar load and vector insert.
37356 /// Note: It is expected that the degenerate cases of an all-zeros or all-ones
37357 /// mask have already been optimized in IR, so we don't bother with those here.
37358 static SDValue
reduceMaskedLoadToScalarLoad(MaskedLoadSDNode * ML,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)37359 reduceMaskedLoadToScalarLoad(MaskedLoadSDNode *ML, SelectionDAG &DAG,
37360                              TargetLowering::DAGCombinerInfo &DCI) {
37361   // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
37362   // However, some target hooks may need to be added to know when the transform
37363   // is profitable. Endianness would also have to be considered.
37364 
37365   SDValue Addr, VecIndex;
37366   unsigned Alignment;
37367   if (!getParamsForOneTrueMaskedElt(ML, DAG, Addr, VecIndex, Alignment))
37368     return SDValue();
37369 
37370   // Load the one scalar element that is specified by the mask using the
37371   // appropriate offset from the base pointer.
37372   SDLoc DL(ML);
37373   EVT VT = ML->getValueType(0);
37374   EVT EltVT = VT.getVectorElementType();
37375   SDValue Load =
37376       DAG.getLoad(EltVT, DL, ML->getChain(), Addr, ML->getPointerInfo(),
37377                   Alignment, ML->getMemOperand()->getFlags());
37378 
37379   // Insert the loaded element into the appropriate place in the vector.
37380   SDValue Insert = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
37381                                ML->getPassThru(), Load, VecIndex);
37382   return DCI.CombineTo(ML, Insert, Load.getValue(1), true);
37383 }
37384 
37385 static SDValue
combineMaskedLoadConstantMask(MaskedLoadSDNode * ML,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)37386 combineMaskedLoadConstantMask(MaskedLoadSDNode *ML, SelectionDAG &DAG,
37387                               TargetLowering::DAGCombinerInfo &DCI) {
37388   if (!ISD::isBuildVectorOfConstantSDNodes(ML->getMask().getNode()))
37389     return SDValue();
37390 
37391   SDLoc DL(ML);
37392   EVT VT = ML->getValueType(0);
37393 
37394   // If we are loading the first and last elements of a vector, it is safe and
37395   // always faster to load the whole vector. Replace the masked load with a
37396   // vector load and select.
37397   unsigned NumElts = VT.getVectorNumElements();
37398   BuildVectorSDNode *MaskBV = cast<BuildVectorSDNode>(ML->getMask());
37399   bool LoadFirstElt = !isNullConstant(MaskBV->getOperand(0));
37400   bool LoadLastElt = !isNullConstant(MaskBV->getOperand(NumElts - 1));
37401   if (LoadFirstElt && LoadLastElt) {
37402     SDValue VecLd = DAG.getLoad(VT, DL, ML->getChain(), ML->getBasePtr(),
37403                                 ML->getMemOperand());
37404     SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), VecLd,
37405                                   ML->getPassThru());
37406     return DCI.CombineTo(ML, Blend, VecLd.getValue(1), true);
37407   }
37408 
37409   // Convert a masked load with a constant mask into a masked load and a select.
37410   // This allows the select operation to use a faster kind of select instruction
37411   // (for example, vblendvps -> vblendps).
37412 
37413   // Don't try this if the pass-through operand is already undefined. That would
37414   // cause an infinite loop because that's what we're about to create.
37415   if (ML->getPassThru().isUndef())
37416     return SDValue();
37417 
37418   // The new masked load has an undef pass-through operand. The select uses the
37419   // original pass-through operand.
37420   SDValue NewML = DAG.getMaskedLoad(VT, DL, ML->getChain(), ML->getBasePtr(),
37421                                     ML->getMask(), DAG.getUNDEF(VT),
37422                                     ML->getMemoryVT(), ML->getMemOperand(),
37423                                     ML->getExtensionType());
37424   SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), NewML,
37425                                 ML->getPassThru());
37426 
37427   return DCI.CombineTo(ML, Blend, NewML.getValue(1), true);
37428 }
37429 
combineMaskedLoad(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)37430 static SDValue combineMaskedLoad(SDNode *N, SelectionDAG &DAG,
37431                                  TargetLowering::DAGCombinerInfo &DCI,
37432                                  const X86Subtarget &Subtarget) {
37433   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
37434 
37435   // TODO: Expanding load with constant mask may be optimized as well.
37436   if (Mld->isExpandingLoad())
37437     return SDValue();
37438 
37439   if (Mld->getExtensionType() == ISD::NON_EXTLOAD) {
37440     if (SDValue ScalarLoad = reduceMaskedLoadToScalarLoad(Mld, DAG, DCI))
37441       return ScalarLoad;
37442     // TODO: Do some AVX512 subsets benefit from this transform?
37443     if (!Subtarget.hasAVX512())
37444       if (SDValue Blend = combineMaskedLoadConstantMask(Mld, DAG, DCI))
37445         return Blend;
37446   }
37447 
37448   if (Mld->getExtensionType() != ISD::SEXTLOAD)
37449     return SDValue();
37450 
37451   // Resolve extending loads.
37452   EVT VT = Mld->getValueType(0);
37453   unsigned NumElems = VT.getVectorNumElements();
37454   EVT LdVT = Mld->getMemoryVT();
37455   SDLoc dl(Mld);
37456 
37457   assert(LdVT != VT && "Cannot extend to the same type");
37458   unsigned ToSz = VT.getScalarSizeInBits();
37459   unsigned FromSz = LdVT.getScalarSizeInBits();
37460   // From/To sizes and ElemCount must be pow of two.
37461   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
37462     "Unexpected size for extending masked load");
37463 
37464   unsigned SizeRatio  = ToSz / FromSz;
37465   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
37466 
37467   // Create a type on which we perform the shuffle.
37468   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
37469           LdVT.getScalarType(), NumElems*SizeRatio);
37470   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
37471 
37472   // Convert PassThru value.
37473   SDValue WidePassThru = DAG.getBitcast(WideVecVT, Mld->getPassThru());
37474   if (!Mld->getPassThru().isUndef()) {
37475     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
37476     for (unsigned i = 0; i != NumElems; ++i)
37477       ShuffleVec[i] = i * SizeRatio;
37478 
37479     // Can't shuffle using an illegal type.
37480     assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
37481            "WideVecVT should be legal");
37482     WidePassThru = DAG.getVectorShuffle(WideVecVT, dl, WidePassThru,
37483                                     DAG.getUNDEF(WideVecVT), ShuffleVec);
37484   }
37485 
37486   // Prepare the new mask.
37487   SDValue NewMask;
37488   SDValue Mask = Mld->getMask();
37489   if (Mask.getValueType() == VT) {
37490     // Mask and original value have the same type.
37491     NewMask = DAG.getBitcast(WideVecVT, Mask);
37492     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
37493     for (unsigned i = 0; i != NumElems; ++i)
37494       ShuffleVec[i] = i * SizeRatio;
37495     for (unsigned i = NumElems; i != NumElems * SizeRatio; ++i)
37496       ShuffleVec[i] = NumElems * SizeRatio;
37497     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
37498                                    DAG.getConstant(0, dl, WideVecVT),
37499                                    ShuffleVec);
37500   } else {
37501     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
37502     unsigned WidenNumElts = NumElems*SizeRatio;
37503     unsigned MaskNumElts = VT.getVectorNumElements();
37504     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
37505                                      WidenNumElts);
37506 
37507     unsigned NumConcat = WidenNumElts / MaskNumElts;
37508     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
37509     SmallVector<SDValue, 16> Ops(NumConcat, ZeroVal);
37510     Ops[0] = Mask;
37511     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
37512   }
37513 
37514   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
37515                                      Mld->getBasePtr(), NewMask, WidePassThru,
37516                                      Mld->getMemoryVT(), Mld->getMemOperand(),
37517                                      ISD::NON_EXTLOAD);
37518   SDValue NewVec = getExtendInVec(/*Signed*/true, dl, VT, WideLd, DAG);
37519   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
37520 }
37521 
37522 /// If exactly one element of the mask is set for a non-truncating masked store,
37523 /// it is a vector extract and scalar store.
37524 /// Note: It is expected that the degenerate cases of an all-zeros or all-ones
37525 /// mask have already been optimized in IR, so we don't bother with those here.
reduceMaskedStoreToScalarStore(MaskedStoreSDNode * MS,SelectionDAG & DAG)37526 static SDValue reduceMaskedStoreToScalarStore(MaskedStoreSDNode *MS,
37527                                               SelectionDAG &DAG) {
37528   // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
37529   // However, some target hooks may need to be added to know when the transform
37530   // is profitable. Endianness would also have to be considered.
37531 
37532   SDValue Addr, VecIndex;
37533   unsigned Alignment;
37534   if (!getParamsForOneTrueMaskedElt(MS, DAG, Addr, VecIndex, Alignment))
37535     return SDValue();
37536 
37537   // Extract the one scalar element that is actually being stored.
37538   SDLoc DL(MS);
37539   EVT VT = MS->getValue().getValueType();
37540   EVT EltVT = VT.getVectorElementType();
37541   SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT,
37542                                 MS->getValue(), VecIndex);
37543 
37544   // Store that element at the appropriate offset from the base pointer.
37545   return DAG.getStore(MS->getChain(), DL, Extract, Addr, MS->getPointerInfo(),
37546                       Alignment, MS->getMemOperand()->getFlags());
37547 }
37548 
combineMaskedStore(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)37549 static SDValue combineMaskedStore(SDNode *N, SelectionDAG &DAG,
37550                                   TargetLowering::DAGCombinerInfo &DCI,
37551                                   const X86Subtarget &Subtarget) {
37552   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
37553   if (Mst->isCompressingStore())
37554     return SDValue();
37555 
37556   EVT VT = Mst->getValue().getValueType();
37557   if (!Mst->isTruncatingStore()) {
37558     if (SDValue ScalarStore = reduceMaskedStoreToScalarStore(Mst, DAG))
37559       return ScalarStore;
37560 
37561     // If the mask value has been legalized to a non-boolean vector, try to
37562     // simplify ops leading up to it. We only demand the MSB of each lane.
37563     SDValue Mask = Mst->getMask();
37564     if (Mask.getScalarValueSizeInBits() != 1) {
37565       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
37566       APInt DemandedMask(APInt::getSignMask(VT.getScalarSizeInBits()));
37567       if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI))
37568         return SDValue(N, 0);
37569     }
37570 
37571     // TODO: AVX512 targets should also be able to simplify something like the
37572     // pattern above, but that pattern will be different. It will either need to
37573     // match setcc more generally or match PCMPGTM later (in tablegen?).
37574 
37575     return SDValue();
37576   }
37577 
37578   // Resolve truncating stores.
37579   unsigned NumElems = VT.getVectorNumElements();
37580   EVT StVT = Mst->getMemoryVT();
37581   SDLoc dl(Mst);
37582 
37583   assert(StVT != VT && "Cannot truncate to the same type");
37584   unsigned FromSz = VT.getScalarSizeInBits();
37585   unsigned ToSz = StVT.getScalarSizeInBits();
37586 
37587   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
37588 
37589   // The truncating store is legal in some cases. For example
37590   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
37591   // are designated for truncate store.
37592   // In this case we don't need any further transformations.
37593   if (TLI.isTruncStoreLegal(VT, StVT))
37594     return SDValue();
37595 
37596   // From/To sizes and ElemCount must be pow of two.
37597   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
37598     "Unexpected size for truncating masked store");
37599   // We are going to use the original vector elt for storing.
37600   // Accumulated smaller vector elements must be a multiple of the store size.
37601   assert (((NumElems * FromSz) % ToSz) == 0 &&
37602           "Unexpected ratio for truncating masked store");
37603 
37604   unsigned SizeRatio  = FromSz / ToSz;
37605   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
37606 
37607   // Create a type on which we perform the shuffle.
37608   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
37609           StVT.getScalarType(), NumElems*SizeRatio);
37610 
37611   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
37612 
37613   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
37614   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
37615   for (unsigned i = 0; i != NumElems; ++i)
37616     ShuffleVec[i] = i * SizeRatio;
37617 
37618   // Can't shuffle using an illegal type.
37619   assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
37620          "WideVecVT should be legal");
37621 
37622   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
37623                                               DAG.getUNDEF(WideVecVT),
37624                                               ShuffleVec);
37625 
37626   SDValue NewMask;
37627   SDValue Mask = Mst->getMask();
37628   if (Mask.getValueType() == VT) {
37629     // Mask and original value have the same type.
37630     NewMask = DAG.getBitcast(WideVecVT, Mask);
37631     for (unsigned i = 0; i != NumElems; ++i)
37632       ShuffleVec[i] = i * SizeRatio;
37633     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
37634       ShuffleVec[i] = NumElems*SizeRatio;
37635     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
37636                                    DAG.getConstant(0, dl, WideVecVT),
37637                                    ShuffleVec);
37638   } else {
37639     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
37640     unsigned WidenNumElts = NumElems*SizeRatio;
37641     unsigned MaskNumElts = VT.getVectorNumElements();
37642     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
37643                                      WidenNumElts);
37644 
37645     unsigned NumConcat = WidenNumElts / MaskNumElts;
37646     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
37647     SmallVector<SDValue, 16> Ops(NumConcat, ZeroVal);
37648     Ops[0] = Mask;
37649     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
37650   }
37651 
37652   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal,
37653                             Mst->getBasePtr(), NewMask, StVT,
37654                             Mst->getMemOperand(), false);
37655 }
37656 
combineStore(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)37657 static SDValue combineStore(SDNode *N, SelectionDAG &DAG,
37658                             const X86Subtarget &Subtarget) {
37659   StoreSDNode *St = cast<StoreSDNode>(N);
37660   EVT VT = St->getValue().getValueType();
37661   EVT StVT = St->getMemoryVT();
37662   SDLoc dl(St);
37663   SDValue StoredVal = St->getOperand(1);
37664   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
37665 
37666   // Convert a store of vXi1 into a store of iX and a bitcast.
37667   if (!Subtarget.hasAVX512() && VT == StVT && VT.isVector() &&
37668       VT.getVectorElementType() == MVT::i1) {
37669 
37670     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), VT.getVectorNumElements());
37671     StoredVal = DAG.getBitcast(NewVT, StoredVal);
37672 
37673     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
37674                         St->getPointerInfo(), St->getAlignment(),
37675                         St->getMemOperand()->getFlags());
37676   }
37677 
37678   // If this is a store of a scalar_to_vector to v1i1, just use a scalar store.
37679   // This will avoid a copy to k-register.
37680   if (VT == MVT::v1i1 && VT == StVT && Subtarget.hasAVX512() &&
37681       StoredVal.getOpcode() == ISD::SCALAR_TO_VECTOR &&
37682       StoredVal.getOperand(0).getValueType() == MVT::i8) {
37683     return DAG.getStore(St->getChain(), dl, StoredVal.getOperand(0),
37684                         St->getBasePtr(), St->getPointerInfo(),
37685                         St->getAlignment(), St->getMemOperand()->getFlags());
37686   }
37687 
37688   // Widen v2i1/v4i1 stores to v8i1.
37689   if ((VT == MVT::v2i1 || VT == MVT::v4i1) && VT == StVT &&
37690       Subtarget.hasAVX512()) {
37691     unsigned NumConcats = 8 / VT.getVectorNumElements();
37692     SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(VT));
37693     Ops[0] = StoredVal;
37694     StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
37695     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
37696                         St->getPointerInfo(), St->getAlignment(),
37697                         St->getMemOperand()->getFlags());
37698   }
37699 
37700   // Turn vXi1 stores of constants into a scalar store.
37701   if ((VT == MVT::v8i1 || VT == MVT::v16i1 || VT == MVT::v32i1 ||
37702        VT == MVT::v64i1) && VT == StVT && TLI.isTypeLegal(VT) &&
37703       ISD::isBuildVectorOfConstantSDNodes(StoredVal.getNode())) {
37704     // If its a v64i1 store without 64-bit support, we need two stores.
37705     if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
37706       SDValue Lo = DAG.getBuildVector(MVT::v32i1, dl,
37707                                       StoredVal->ops().slice(0, 32));
37708       Lo = combinevXi1ConstantToInteger(Lo, DAG);
37709       SDValue Hi = DAG.getBuildVector(MVT::v32i1, dl,
37710                                       StoredVal->ops().slice(32, 32));
37711       Hi = combinevXi1ConstantToInteger(Hi, DAG);
37712 
37713       unsigned Alignment = St->getAlignment();
37714 
37715       SDValue Ptr0 = St->getBasePtr();
37716       SDValue Ptr1 = DAG.getMemBasePlusOffset(Ptr0, 4, dl);
37717 
37718       SDValue Ch0 =
37719           DAG.getStore(St->getChain(), dl, Lo, Ptr0, St->getPointerInfo(),
37720                        Alignment, St->getMemOperand()->getFlags());
37721       SDValue Ch1 =
37722           DAG.getStore(St->getChain(), dl, Hi, Ptr1,
37723                        St->getPointerInfo().getWithOffset(4),
37724                        MinAlign(Alignment, 4U),
37725                        St->getMemOperand()->getFlags());
37726       return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
37727     }
37728 
37729     StoredVal = combinevXi1ConstantToInteger(StoredVal, DAG);
37730     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
37731                         St->getPointerInfo(), St->getAlignment(),
37732                         St->getMemOperand()->getFlags());
37733   }
37734 
37735   // If we are saving a concatenation of two XMM registers and 32-byte stores
37736   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
37737   bool Fast;
37738   unsigned AddressSpace = St->getAddressSpace();
37739   unsigned Alignment = St->getAlignment();
37740   if (VT.is256BitVector() && StVT == VT &&
37741       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
37742                              AddressSpace, Alignment, &Fast) &&
37743       !Fast) {
37744     unsigned NumElems = VT.getVectorNumElements();
37745     if (NumElems < 2)
37746       return SDValue();
37747 
37748     SDValue Value0 = extract128BitVector(StoredVal, 0, DAG, dl);
37749     SDValue Value1 = extract128BitVector(StoredVal, NumElems / 2, DAG, dl);
37750 
37751     SDValue Ptr0 = St->getBasePtr();
37752     SDValue Ptr1 = DAG.getMemBasePlusOffset(Ptr0, 16, dl);
37753 
37754     SDValue Ch0 =
37755         DAG.getStore(St->getChain(), dl, Value0, Ptr0, St->getPointerInfo(),
37756                      Alignment, St->getMemOperand()->getFlags());
37757     SDValue Ch1 =
37758         DAG.getStore(St->getChain(), dl, Value1, Ptr1,
37759                      St->getPointerInfo().getWithOffset(16),
37760                      MinAlign(Alignment, 16U), St->getMemOperand()->getFlags());
37761     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
37762   }
37763 
37764   // Optimize trunc store (of multiple scalars) to shuffle and store.
37765   // First, pack all of the elements in one place. Next, store to memory
37766   // in fewer chunks.
37767   if (St->isTruncatingStore() && VT.isVector()) {
37768     // Check if we can detect an AVG pattern from the truncation. If yes,
37769     // replace the trunc store by a normal store with the result of X86ISD::AVG
37770     // instruction.
37771     if (SDValue Avg = detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG,
37772                                        Subtarget, dl))
37773       return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
37774                           St->getPointerInfo(), St->getAlignment(),
37775                           St->getMemOperand()->getFlags());
37776 
37777     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
37778     if (SDValue Val =
37779         detectAVX512SSatPattern(St->getValue(), St->getMemoryVT(), Subtarget,
37780                                 TLI))
37781       return EmitTruncSStore(true /* Signed saturation */, St->getChain(),
37782                              dl, Val, St->getBasePtr(),
37783                              St->getMemoryVT(), St->getMemOperand(), DAG);
37784     if (SDValue Val = detectAVX512USatPattern(St->getValue(), St->getMemoryVT(),
37785                                               DAG, dl, Subtarget, TLI))
37786       return EmitTruncSStore(false /* Unsigned saturation */, St->getChain(),
37787                              dl, Val, St->getBasePtr(),
37788                              St->getMemoryVT(), St->getMemOperand(), DAG);
37789 
37790     unsigned NumElems = VT.getVectorNumElements();
37791     assert(StVT != VT && "Cannot truncate to the same type");
37792     unsigned FromSz = VT.getScalarSizeInBits();
37793     unsigned ToSz = StVT.getScalarSizeInBits();
37794 
37795     // The truncating store is legal in some cases. For example
37796     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
37797     // are designated for truncate store.
37798     // In this case we don't need any further transformations.
37799     if (TLI.isTruncStoreLegalOrCustom(VT, StVT))
37800       return SDValue();
37801 
37802     // From, To sizes and ElemCount must be pow of two
37803     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
37804     // We are going to use the original vector elt for storing.
37805     // Accumulated smaller vector elements must be a multiple of the store size.
37806     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
37807 
37808     unsigned SizeRatio  = FromSz / ToSz;
37809 
37810     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
37811 
37812     // Create a type on which we perform the shuffle
37813     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
37814             StVT.getScalarType(), NumElems*SizeRatio);
37815 
37816     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
37817 
37818     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
37819     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
37820     for (unsigned i = 0; i != NumElems; ++i)
37821       ShuffleVec[i] = i * SizeRatio;
37822 
37823     // Can't shuffle using an illegal type.
37824     if (!TLI.isTypeLegal(WideVecVT))
37825       return SDValue();
37826 
37827     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
37828                                          DAG.getUNDEF(WideVecVT),
37829                                          ShuffleVec);
37830     // At this point all of the data is stored at the bottom of the
37831     // register. We now need to save it to mem.
37832 
37833     // Find the largest store unit
37834     MVT StoreType = MVT::i8;
37835     for (MVT Tp : MVT::integer_valuetypes()) {
37836       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
37837         StoreType = Tp;
37838     }
37839 
37840     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
37841     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
37842         (64 <= NumElems * ToSz))
37843       StoreType = MVT::f64;
37844 
37845     // Bitcast the original vector into a vector of store-size units
37846     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
37847             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
37848     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
37849     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
37850     SmallVector<SDValue, 8> Chains;
37851     SDValue Ptr = St->getBasePtr();
37852 
37853     // Perform one or more big stores into memory.
37854     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
37855       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
37856                                    StoreType, ShuffWide,
37857                                    DAG.getIntPtrConstant(i, dl));
37858       SDValue Ch =
37859           DAG.getStore(St->getChain(), dl, SubVec, Ptr, St->getPointerInfo(),
37860                        St->getAlignment(), St->getMemOperand()->getFlags());
37861       Ptr = DAG.getMemBasePlusOffset(Ptr, StoreType.getStoreSize(), dl);
37862       Chains.push_back(Ch);
37863     }
37864 
37865     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
37866   }
37867 
37868   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
37869   // the FP state in cases where an emms may be missing.
37870   // A preferable solution to the general problem is to figure out the right
37871   // places to insert EMMS.  This qualifies as a quick hack.
37872 
37873   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
37874   if (VT.getSizeInBits() != 64)
37875     return SDValue();
37876 
37877   const Function &F = DAG.getMachineFunction().getFunction();
37878   bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
37879   bool F64IsLegal =
37880       !Subtarget.useSoftFloat() && !NoImplicitFloatOps && Subtarget.hasSSE2();
37881   if ((VT.isVector() ||
37882        (VT == MVT::i64 && F64IsLegal && !Subtarget.is64Bit())) &&
37883       isa<LoadSDNode>(St->getValue()) &&
37884       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
37885       St->getChain().hasOneUse() && !St->isVolatile()) {
37886     LoadSDNode *Ld = cast<LoadSDNode>(St->getValue().getNode());
37887     SmallVector<SDValue, 8> Ops;
37888 
37889     if (!ISD::isNormalLoad(Ld))
37890       return SDValue();
37891 
37892     // If this is not the MMX case, i.e. we are just turning i64 load/store
37893     // into f64 load/store, avoid the transformation if there are multiple
37894     // uses of the loaded value.
37895     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
37896       return SDValue();
37897 
37898     SDLoc LdDL(Ld);
37899     SDLoc StDL(N);
37900     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
37901     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
37902     // pair instead.
37903     if (Subtarget.is64Bit() || F64IsLegal) {
37904       MVT LdVT = (Subtarget.is64Bit() &&
37905                   (!VT.isFloatingPoint() || !F64IsLegal)) ? MVT::i64 : MVT::f64;
37906       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
37907                                   Ld->getMemOperand());
37908 
37909       // Make sure new load is placed in same chain order.
37910       DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
37911       return DAG.getStore(St->getChain(), StDL, NewLd, St->getBasePtr(),
37912                           St->getMemOperand());
37913     }
37914 
37915     // Otherwise, lower to two pairs of 32-bit loads / stores.
37916     SDValue LoAddr = Ld->getBasePtr();
37917     SDValue HiAddr = DAG.getMemBasePlusOffset(LoAddr, 4, LdDL);
37918 
37919     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
37920                                Ld->getPointerInfo(), Ld->getAlignment(),
37921                                Ld->getMemOperand()->getFlags());
37922     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
37923                                Ld->getPointerInfo().getWithOffset(4),
37924                                MinAlign(Ld->getAlignment(), 4),
37925                                Ld->getMemOperand()->getFlags());
37926     // Make sure new loads are placed in same chain order.
37927     DAG.makeEquivalentMemoryOrdering(Ld, LoLd);
37928     DAG.makeEquivalentMemoryOrdering(Ld, HiLd);
37929 
37930     LoAddr = St->getBasePtr();
37931     HiAddr = DAG.getMemBasePlusOffset(LoAddr, 4, StDL);
37932 
37933     SDValue LoSt =
37934         DAG.getStore(St->getChain(), StDL, LoLd, LoAddr, St->getPointerInfo(),
37935                      St->getAlignment(), St->getMemOperand()->getFlags());
37936     SDValue HiSt = DAG.getStore(St->getChain(), StDL, HiLd, HiAddr,
37937                                 St->getPointerInfo().getWithOffset(4),
37938                                 MinAlign(St->getAlignment(), 4),
37939                                 St->getMemOperand()->getFlags());
37940     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
37941   }
37942 
37943   // This is similar to the above case, but here we handle a scalar 64-bit
37944   // integer store that is extracted from a vector on a 32-bit target.
37945   // If we have SSE2, then we can treat it like a floating-point double
37946   // to get past legalization. The execution dependencies fixup pass will
37947   // choose the optimal machine instruction for the store if this really is
37948   // an integer or v2f32 rather than an f64.
37949   if (VT == MVT::i64 && F64IsLegal && !Subtarget.is64Bit() &&
37950       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
37951     SDValue OldExtract = St->getOperand(1);
37952     SDValue ExtOp0 = OldExtract.getOperand(0);
37953     unsigned VecSize = ExtOp0.getValueSizeInBits();
37954     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
37955     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
37956     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
37957                                      BitCast, OldExtract.getOperand(1));
37958     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
37959                         St->getPointerInfo(), St->getAlignment(),
37960                         St->getMemOperand()->getFlags());
37961   }
37962 
37963   return SDValue();
37964 }
37965 
37966 /// Return 'true' if this vector operation is "horizontal"
37967 /// and return the operands for the horizontal operation in LHS and RHS.  A
37968 /// horizontal operation performs the binary operation on successive elements
37969 /// of its first operand, then on successive elements of its second operand,
37970 /// returning the resulting values in a vector.  For example, if
37971 ///   A = < float a0, float a1, float a2, float a3 >
37972 /// and
37973 ///   B = < float b0, float b1, float b2, float b3 >
37974 /// then the result of doing a horizontal operation on A and B is
37975 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
37976 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
37977 /// A horizontal-op B, for some already available A and B, and if so then LHS is
37978 /// set to A, RHS to B, and the routine returns 'true'.
isHorizontalBinOp(SDValue & LHS,SDValue & RHS,bool IsCommutative)37979 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
37980   // If either operand is undef, bail out. The binop should be simplified.
37981   if (LHS.isUndef() || RHS.isUndef())
37982     return false;
37983 
37984   // Look for the following pattern:
37985   //   A = < float a0, float a1, float a2, float a3 >
37986   //   B = < float b0, float b1, float b2, float b3 >
37987   // and
37988   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
37989   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
37990   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
37991   // which is A horizontal-op B.
37992 
37993   // At least one of the operands should be a vector shuffle.
37994   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
37995       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
37996     return false;
37997 
37998   MVT VT = LHS.getSimpleValueType();
37999   assert((VT.is128BitVector() || VT.is256BitVector()) &&
38000          "Unsupported vector type for horizontal add/sub");
38001 
38002   // View LHS in the form
38003   //   LHS = VECTOR_SHUFFLE A, B, LMask
38004   // If LHS is not a shuffle, then pretend it is the identity shuffle:
38005   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
38006   // NOTE: A default initialized SDValue represents an UNDEF of type VT.
38007   unsigned NumElts = VT.getVectorNumElements();
38008   SDValue A, B;
38009   SmallVector<int, 16> LMask(NumElts);
38010   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
38011     if (!LHS.getOperand(0).isUndef())
38012       A = LHS.getOperand(0);
38013     if (!LHS.getOperand(1).isUndef())
38014       B = LHS.getOperand(1);
38015     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
38016     llvm::copy(Mask, LMask.begin());
38017   } else {
38018     A = LHS;
38019     for (unsigned i = 0; i != NumElts; ++i)
38020       LMask[i] = i;
38021   }
38022 
38023   // Likewise, view RHS in the form
38024   //   RHS = VECTOR_SHUFFLE C, D, RMask
38025   SDValue C, D;
38026   SmallVector<int, 16> RMask(NumElts);
38027   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
38028     if (!RHS.getOperand(0).isUndef())
38029       C = RHS.getOperand(0);
38030     if (!RHS.getOperand(1).isUndef())
38031       D = RHS.getOperand(1);
38032     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
38033     llvm::copy(Mask, RMask.begin());
38034   } else {
38035     C = RHS;
38036     for (unsigned i = 0; i != NumElts; ++i)
38037       RMask[i] = i;
38038   }
38039 
38040   // If A and B occur in reverse order in RHS, then canonicalize by commuting
38041   // RHS operands and shuffle mask.
38042   if (A != C) {
38043     std::swap(C, D);
38044     ShuffleVectorSDNode::commuteMask(RMask);
38045   }
38046   // Check that the shuffles are both shuffling the same vectors.
38047   if (!(A == C && B == D))
38048     return false;
38049 
38050   // LHS and RHS are now:
38051   //   LHS = shuffle A, B, LMask
38052   //   RHS = shuffle A, B, RMask
38053   // Check that the masks correspond to performing a horizontal operation.
38054   // AVX defines horizontal add/sub to operate independently on 128-bit lanes,
38055   // so we just repeat the inner loop if this is a 256-bit op.
38056   unsigned Num128BitChunks = VT.getSizeInBits() / 128;
38057   unsigned NumEltsPer128BitChunk = NumElts / Num128BitChunks;
38058   assert((NumEltsPer128BitChunk % 2 == 0) &&
38059          "Vector type should have an even number of elements in each lane");
38060   for (unsigned j = 0; j != NumElts; j += NumEltsPer128BitChunk) {
38061     for (unsigned i = 0; i != NumEltsPer128BitChunk; ++i) {
38062       // Ignore undefined components.
38063       int LIdx = LMask[i + j], RIdx = RMask[i + j];
38064       if (LIdx < 0 || RIdx < 0 ||
38065           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
38066           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
38067         continue;
38068 
38069       // The  low half of the 128-bit result must choose from A.
38070       // The high half of the 128-bit result must choose from B,
38071       // unless B is undef. In that case, we are always choosing from A.
38072       unsigned NumEltsPer64BitChunk = NumEltsPer128BitChunk / 2;
38073       unsigned Src = B.getNode() ? i >= NumEltsPer64BitChunk : 0;
38074 
38075       // Check that successive elements are being operated on. If not, this is
38076       // not a horizontal operation.
38077       int Index = 2 * (i % NumEltsPer64BitChunk) + NumElts * Src + j;
38078       if (!(LIdx == Index && RIdx == Index + 1) &&
38079           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
38080         return false;
38081     }
38082   }
38083 
38084   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
38085   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
38086   return true;
38087 }
38088 
38089 /// Do target-specific dag combines on floating-point adds/subs.
combineFaddFsub(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)38090 static SDValue combineFaddFsub(SDNode *N, SelectionDAG &DAG,
38091                                const X86Subtarget &Subtarget) {
38092   EVT VT = N->getValueType(0);
38093   SDValue LHS = N->getOperand(0);
38094   SDValue RHS = N->getOperand(1);
38095   bool IsFadd = N->getOpcode() == ISD::FADD;
38096   auto HorizOpcode = IsFadd ? X86ISD::FHADD : X86ISD::FHSUB;
38097   assert((IsFadd || N->getOpcode() == ISD::FSUB) && "Wrong opcode");
38098 
38099   // Try to synthesize horizontal add/sub from adds/subs of shuffles.
38100   if (((Subtarget.hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
38101        (Subtarget.hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
38102       isHorizontalBinOp(LHS, RHS, IsFadd) &&
38103       shouldUseHorizontalOp(LHS == RHS, DAG, Subtarget))
38104     return DAG.getNode(HorizOpcode, SDLoc(N), VT, LHS, RHS);
38105 
38106   return SDValue();
38107 }
38108 
38109 /// Attempt to pre-truncate inputs to arithmetic ops if it will simplify
38110 /// the codegen.
38111 /// e.g. TRUNC( BINOP( X, Y ) ) --> BINOP( TRUNC( X ), TRUNC( Y ) )
38112 /// TODO: This overlaps with the generic combiner's visitTRUNCATE. Remove
38113 ///       anything that is guaranteed to be transformed by DAGCombiner.
combineTruncatedArithmetic(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & DL)38114 static SDValue combineTruncatedArithmetic(SDNode *N, SelectionDAG &DAG,
38115                                           const X86Subtarget &Subtarget,
38116                                           const SDLoc &DL) {
38117   assert(N->getOpcode() == ISD::TRUNCATE && "Wrong opcode");
38118   SDValue Src = N->getOperand(0);
38119   unsigned Opcode = Src.getOpcode();
38120   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
38121 
38122   EVT VT = N->getValueType(0);
38123   EVT SrcVT = Src.getValueType();
38124 
38125   auto IsFreeTruncation = [VT](SDValue Op) {
38126     unsigned TruncSizeInBits = VT.getScalarSizeInBits();
38127 
38128     // See if this has been extended from a smaller/equal size to
38129     // the truncation size, allowing a truncation to combine with the extend.
38130     unsigned Opcode = Op.getOpcode();
38131     if ((Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND ||
38132          Opcode == ISD::ZERO_EXTEND) &&
38133         Op.getOperand(0).getScalarValueSizeInBits() <= TruncSizeInBits)
38134       return true;
38135 
38136     // See if this is a single use constant which can be constant folded.
38137     // NOTE: We don't peek throught bitcasts here because there is currently
38138     // no support for constant folding truncate+bitcast+vector_of_constants. So
38139     // we'll just send up with a truncate on both operands which will
38140     // get turned back into (truncate (binop)) causing an infinite loop.
38141     return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
38142   };
38143 
38144   auto TruncateArithmetic = [&](SDValue N0, SDValue N1) {
38145     SDValue Trunc0 = DAG.getNode(ISD::TRUNCATE, DL, VT, N0);
38146     SDValue Trunc1 = DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
38147     return DAG.getNode(Opcode, DL, VT, Trunc0, Trunc1);
38148   };
38149 
38150   // Don't combine if the operation has other uses.
38151   if (!Src.hasOneUse())
38152     return SDValue();
38153 
38154   // Only support vector truncation for now.
38155   // TODO: i64 scalar math would benefit as well.
38156   if (!VT.isVector())
38157     return SDValue();
38158 
38159   // In most cases its only worth pre-truncating if we're only facing the cost
38160   // of one truncation.
38161   // i.e. if one of the inputs will constant fold or the input is repeated.
38162   switch (Opcode) {
38163   case ISD::AND:
38164   case ISD::XOR:
38165   case ISD::OR: {
38166     SDValue Op0 = Src.getOperand(0);
38167     SDValue Op1 = Src.getOperand(1);
38168     if (TLI.isOperationLegalOrPromote(Opcode, VT) &&
38169         (Op0 == Op1 || IsFreeTruncation(Op0) || IsFreeTruncation(Op1)))
38170       return TruncateArithmetic(Op0, Op1);
38171     break;
38172   }
38173 
38174   case ISD::MUL:
38175     // X86 is rubbish at scalar and vector i64 multiplies (until AVX512DQ) - its
38176     // better to truncate if we have the chance.
38177     if (SrcVT.getScalarType() == MVT::i64 && TLI.isOperationLegal(Opcode, VT) &&
38178         !TLI.isOperationLegal(Opcode, SrcVT))
38179       return TruncateArithmetic(Src.getOperand(0), Src.getOperand(1));
38180     LLVM_FALLTHROUGH;
38181   case ISD::ADD: {
38182     SDValue Op0 = Src.getOperand(0);
38183     SDValue Op1 = Src.getOperand(1);
38184     if (TLI.isOperationLegal(Opcode, VT) &&
38185         (Op0 == Op1 || IsFreeTruncation(Op0) || IsFreeTruncation(Op1)))
38186       return TruncateArithmetic(Op0, Op1);
38187     break;
38188   }
38189   case ISD::SUB: {
38190     // TODO: ISD::SUB We are conservative and require both sides to be freely
38191     // truncatable to avoid interfering with combineSubToSubus.
38192     SDValue Op0 = Src.getOperand(0);
38193     SDValue Op1 = Src.getOperand(1);
38194     if (TLI.isOperationLegal(Opcode, VT) &&
38195         (Op0 == Op1 || (IsFreeTruncation(Op0) && IsFreeTruncation(Op1))))
38196       return TruncateArithmetic(Op0, Op1);
38197     break;
38198   }
38199   }
38200 
38201   return SDValue();
38202 }
38203 
38204 /// Truncate using ISD::AND mask and X86ISD::PACKUS.
combineVectorTruncationWithPACKUS(SDNode * N,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)38205 static SDValue combineVectorTruncationWithPACKUS(SDNode *N, const SDLoc &DL,
38206                                                  const X86Subtarget &Subtarget,
38207                                                  SelectionDAG &DAG) {
38208   SDValue In = N->getOperand(0);
38209   EVT InVT = In.getValueType();
38210   EVT InSVT = InVT.getVectorElementType();
38211   EVT OutVT = N->getValueType(0);
38212   EVT OutSVT = OutVT.getVectorElementType();
38213 
38214   // Split a long vector into vectors of legal type and mask to unset all bits
38215   // that won't appear in the result to prevent saturation.
38216   // TODO - we should be doing this at the maximum legal size but this is
38217   // causing regressions where we're concatenating back to max width just to
38218   // perform the AND and then extracting back again.....
38219   unsigned NumSubRegs = InVT.getSizeInBits() / 128;
38220   unsigned NumSubRegElts = 128 / InSVT.getSizeInBits();
38221   EVT SubRegVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubRegElts);
38222   SmallVector<SDValue, 8> SubVecs(NumSubRegs);
38223 
38224   APInt Mask =
38225       APInt::getLowBitsSet(InSVT.getSizeInBits(), OutSVT.getSizeInBits());
38226   SDValue MaskVal = DAG.getConstant(Mask, DL, SubRegVT);
38227 
38228   for (unsigned i = 0; i < NumSubRegs; i++) {
38229     SDValue Sub = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubRegVT, In,
38230                               DAG.getIntPtrConstant(i * NumSubRegElts, DL));
38231     SubVecs[i] = DAG.getNode(ISD::AND, DL, SubRegVT, Sub, MaskVal);
38232   }
38233   In = DAG.getNode(ISD::CONCAT_VECTORS, DL, InVT, SubVecs);
38234 
38235   return truncateVectorWithPACK(X86ISD::PACKUS, OutVT, In, DL, DAG, Subtarget);
38236 }
38237 
38238 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
combineVectorTruncationWithPACKSS(SDNode * N,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)38239 static SDValue combineVectorTruncationWithPACKSS(SDNode *N, const SDLoc &DL,
38240                                                  const X86Subtarget &Subtarget,
38241                                                  SelectionDAG &DAG) {
38242   SDValue In = N->getOperand(0);
38243   EVT InVT = In.getValueType();
38244   EVT OutVT = N->getValueType(0);
38245   In = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, InVT, In,
38246                    DAG.getValueType(OutVT));
38247   return truncateVectorWithPACK(X86ISD::PACKSS, OutVT, In, DL, DAG, Subtarget);
38248 }
38249 
38250 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
38251 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
38252 /// legalization the truncation will be translated into a BUILD_VECTOR with each
38253 /// element that is extracted from a vector and then truncated, and it is
38254 /// difficult to do this optimization based on them.
combineVectorTruncation(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)38255 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
38256                                        const X86Subtarget &Subtarget) {
38257   EVT OutVT = N->getValueType(0);
38258   if (!OutVT.isVector())
38259     return SDValue();
38260 
38261   SDValue In = N->getOperand(0);
38262   if (!In.getValueType().isSimple())
38263     return SDValue();
38264 
38265   EVT InVT = In.getValueType();
38266   unsigned NumElems = OutVT.getVectorNumElements();
38267 
38268   // TODO: On AVX2, the behavior of X86ISD::PACKUS is different from that on
38269   // SSE2, and we need to take care of it specially.
38270   // AVX512 provides vpmovdb.
38271   if (!Subtarget.hasSSE2() || Subtarget.hasAVX2())
38272     return SDValue();
38273 
38274   EVT OutSVT = OutVT.getVectorElementType();
38275   EVT InSVT = InVT.getVectorElementType();
38276   if (!((InSVT == MVT::i32 || InSVT == MVT::i64) &&
38277         (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
38278         NumElems >= 8))
38279     return SDValue();
38280 
38281   // SSSE3's pshufb results in less instructions in the cases below.
38282   if (Subtarget.hasSSSE3() && NumElems == 8 &&
38283       ((OutSVT == MVT::i8 && InSVT != MVT::i64) ||
38284        (InSVT == MVT::i32 && OutSVT == MVT::i16)))
38285     return SDValue();
38286 
38287   SDLoc DL(N);
38288   // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PACKUS
38289   // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
38290   // truncate 2 x v4i32 to v8i16.
38291   if (Subtarget.hasSSE41() || OutSVT == MVT::i8)
38292     return combineVectorTruncationWithPACKUS(N, DL, Subtarget, DAG);
38293   if (InSVT == MVT::i32)
38294     return combineVectorTruncationWithPACKSS(N, DL, Subtarget, DAG);
38295 
38296   return SDValue();
38297 }
38298 
38299 /// This function transforms vector truncation of 'extended sign-bits' or
38300 /// 'extended zero-bits' values.
38301 /// vXi16/vXi32/vXi64 to vXi8/vXi16/vXi32 into X86ISD::PACKSS/PACKUS operations.
combineVectorSignBitsTruncation(SDNode * N,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)38302 static SDValue combineVectorSignBitsTruncation(SDNode *N, const SDLoc &DL,
38303                                                SelectionDAG &DAG,
38304                                                const X86Subtarget &Subtarget) {
38305   // Requires SSE2 but AVX512 has fast truncate.
38306   if (!Subtarget.hasSSE2() || Subtarget.hasAVX512())
38307     return SDValue();
38308 
38309   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple())
38310     return SDValue();
38311 
38312   SDValue In = N->getOperand(0);
38313   if (!In.getValueType().isSimple())
38314     return SDValue();
38315 
38316   MVT VT = N->getValueType(0).getSimpleVT();
38317   MVT SVT = VT.getScalarType();
38318 
38319   MVT InVT = In.getValueType().getSimpleVT();
38320   MVT InSVT = InVT.getScalarType();
38321 
38322   // Check we have a truncation suited for PACKSS/PACKUS.
38323   if (!VT.is128BitVector() && !VT.is256BitVector())
38324     return SDValue();
38325   if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32)
38326     return SDValue();
38327   if (InSVT != MVT::i16 && InSVT != MVT::i32 && InSVT != MVT::i64)
38328     return SDValue();
38329 
38330   unsigned NumPackedSignBits = std::min<unsigned>(SVT.getSizeInBits(), 16);
38331   unsigned NumPackedZeroBits = Subtarget.hasSSE41() ? NumPackedSignBits : 8;
38332 
38333   // Use PACKUS if the input has zero-bits that extend all the way to the
38334   // packed/truncated value. e.g. masks, zext_in_reg, etc.
38335   KnownBits Known = DAG.computeKnownBits(In);
38336   unsigned NumLeadingZeroBits = Known.countMinLeadingZeros();
38337   if (NumLeadingZeroBits >= (InSVT.getSizeInBits() - NumPackedZeroBits))
38338     return truncateVectorWithPACK(X86ISD::PACKUS, VT, In, DL, DAG, Subtarget);
38339 
38340   // Use PACKSS if the input has sign-bits that extend all the way to the
38341   // packed/truncated value. e.g. Comparison result, sext_in_reg, etc.
38342   unsigned NumSignBits = DAG.ComputeNumSignBits(In);
38343   if (NumSignBits > (InSVT.getSizeInBits() - NumPackedSignBits))
38344     return truncateVectorWithPACK(X86ISD::PACKSS, VT, In, DL, DAG, Subtarget);
38345 
38346   return SDValue();
38347 }
38348 
38349 // Try to form a MULHU or MULHS node by looking for
38350 // (trunc (srl (mul ext, ext), 16))
38351 // TODO: This is X86 specific because we want to be able to handle wide types
38352 // before type legalization. But we can only do it if the vector will be
38353 // legalized via widening/splitting. Type legalization can't handle promotion
38354 // of a MULHU/MULHS. There isn't a way to convey this to the generic DAG
38355 // combiner.
combinePMULH(SDValue Src,EVT VT,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)38356 static SDValue combinePMULH(SDValue Src, EVT VT, const SDLoc &DL,
38357                             SelectionDAG &DAG, const X86Subtarget &Subtarget) {
38358   // First instruction should be a right shift of a multiply.
38359   if (Src.getOpcode() != ISD::SRL ||
38360       Src.getOperand(0).getOpcode() != ISD::MUL)
38361     return SDValue();
38362 
38363   if (!Subtarget.hasSSE2())
38364     return SDValue();
38365 
38366   // Only handle vXi16 types that are at least 128-bits unless they will be
38367   // widened.
38368   if (!VT.isVector() || VT.getVectorElementType() != MVT::i16 ||
38369       (!ExperimentalVectorWideningLegalization &&
38370        VT.getVectorNumElements() < 8))
38371     return SDValue();
38372 
38373   // Input type should be vXi32.
38374   EVT InVT = Src.getValueType();
38375   if (InVT.getVectorElementType() != MVT::i32)
38376     return SDValue();
38377 
38378   // Need a shift by 16.
38379   APInt ShiftAmt;
38380   if (!ISD::isConstantSplatVector(Src.getOperand(1).getNode(), ShiftAmt) ||
38381       ShiftAmt != 16)
38382     return SDValue();
38383 
38384   SDValue LHS = Src.getOperand(0).getOperand(0);
38385   SDValue RHS = Src.getOperand(0).getOperand(1);
38386 
38387   unsigned ExtOpc = LHS.getOpcode();
38388   if ((ExtOpc != ISD::SIGN_EXTEND && ExtOpc != ISD::ZERO_EXTEND) ||
38389       RHS.getOpcode() != ExtOpc)
38390     return SDValue();
38391 
38392   // Peek through the extends.
38393   LHS = LHS.getOperand(0);
38394   RHS = RHS.getOperand(0);
38395 
38396   // Ensure the input types match.
38397   if (LHS.getValueType() != VT || RHS.getValueType() != VT)
38398     return SDValue();
38399 
38400   unsigned Opc = ExtOpc == ISD::SIGN_EXTEND ? ISD::MULHS : ISD::MULHU;
38401   return DAG.getNode(Opc, DL, VT, LHS, RHS);
38402 }
38403 
38404 // Attempt to match PMADDUBSW, which multiplies corresponding unsigned bytes
38405 // from one vector with signed bytes from another vector, adds together
38406 // adjacent pairs of 16-bit products, and saturates the result before
38407 // truncating to 16-bits.
38408 //
38409 // Which looks something like this:
38410 // (i16 (ssat (add (mul (zext (even elts (i8 A))), (sext (even elts (i8 B)))),
38411 //                 (mul (zext (odd elts (i8 A)), (sext (odd elts (i8 B))))))))
detectPMADDUBSW(SDValue In,EVT VT,SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & DL)38412 static SDValue detectPMADDUBSW(SDValue In, EVT VT, SelectionDAG &DAG,
38413                                const X86Subtarget &Subtarget,
38414                                const SDLoc &DL) {
38415   if (!VT.isVector() || !Subtarget.hasSSSE3())
38416     return SDValue();
38417 
38418   unsigned NumElems = VT.getVectorNumElements();
38419   EVT ScalarVT = VT.getVectorElementType();
38420   if (ScalarVT != MVT::i16 || NumElems < 8 || !isPowerOf2_32(NumElems))
38421     return SDValue();
38422 
38423   SDValue SSatVal = detectSSatPattern(In, VT);
38424   if (!SSatVal || SSatVal.getOpcode() != ISD::ADD)
38425     return SDValue();
38426 
38427   // Ok this is a signed saturation of an ADD. See if this ADD is adding pairs
38428   // of multiplies from even/odd elements.
38429   SDValue N0 = SSatVal.getOperand(0);
38430   SDValue N1 = SSatVal.getOperand(1);
38431 
38432   if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
38433     return SDValue();
38434 
38435   SDValue N00 = N0.getOperand(0);
38436   SDValue N01 = N0.getOperand(1);
38437   SDValue N10 = N1.getOperand(0);
38438   SDValue N11 = N1.getOperand(1);
38439 
38440   // TODO: Handle constant vectors and use knownbits/computenumsignbits?
38441   // Canonicalize zero_extend to LHS.
38442   if (N01.getOpcode() == ISD::ZERO_EXTEND)
38443     std::swap(N00, N01);
38444   if (N11.getOpcode() == ISD::ZERO_EXTEND)
38445     std::swap(N10, N11);
38446 
38447   // Ensure we have a zero_extend and a sign_extend.
38448   if (N00.getOpcode() != ISD::ZERO_EXTEND ||
38449       N01.getOpcode() != ISD::SIGN_EXTEND ||
38450       N10.getOpcode() != ISD::ZERO_EXTEND ||
38451       N11.getOpcode() != ISD::SIGN_EXTEND)
38452     return SDValue();
38453 
38454   // Peek through the extends.
38455   N00 = N00.getOperand(0);
38456   N01 = N01.getOperand(0);
38457   N10 = N10.getOperand(0);
38458   N11 = N11.getOperand(0);
38459 
38460   // Ensure the extend is from vXi8.
38461   if (N00.getValueType().getVectorElementType() != MVT::i8 ||
38462       N01.getValueType().getVectorElementType() != MVT::i8 ||
38463       N10.getValueType().getVectorElementType() != MVT::i8 ||
38464       N11.getValueType().getVectorElementType() != MVT::i8)
38465     return SDValue();
38466 
38467   // All inputs should be build_vectors.
38468   if (N00.getOpcode() != ISD::BUILD_VECTOR ||
38469       N01.getOpcode() != ISD::BUILD_VECTOR ||
38470       N10.getOpcode() != ISD::BUILD_VECTOR ||
38471       N11.getOpcode() != ISD::BUILD_VECTOR)
38472     return SDValue();
38473 
38474   // N00/N10 are zero extended. N01/N11 are sign extended.
38475 
38476   // For each element, we need to ensure we have an odd element from one vector
38477   // multiplied by the odd element of another vector and the even element from
38478   // one of the same vectors being multiplied by the even element from the
38479   // other vector. So we need to make sure for each element i, this operator
38480   // is being performed:
38481   //  A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
38482   SDValue ZExtIn, SExtIn;
38483   for (unsigned i = 0; i != NumElems; ++i) {
38484     SDValue N00Elt = N00.getOperand(i);
38485     SDValue N01Elt = N01.getOperand(i);
38486     SDValue N10Elt = N10.getOperand(i);
38487     SDValue N11Elt = N11.getOperand(i);
38488     // TODO: Be more tolerant to undefs.
38489     if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
38490         N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
38491         N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
38492         N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
38493       return SDValue();
38494     auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
38495     auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
38496     auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
38497     auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
38498     if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
38499       return SDValue();
38500     unsigned IdxN00 = ConstN00Elt->getZExtValue();
38501     unsigned IdxN01 = ConstN01Elt->getZExtValue();
38502     unsigned IdxN10 = ConstN10Elt->getZExtValue();
38503     unsigned IdxN11 = ConstN11Elt->getZExtValue();
38504     // Add is commutative so indices can be reordered.
38505     if (IdxN00 > IdxN10) {
38506       std::swap(IdxN00, IdxN10);
38507       std::swap(IdxN01, IdxN11);
38508     }
38509     // N0 indices be the even element. N1 indices must be the next odd element.
38510     if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
38511         IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
38512       return SDValue();
38513     SDValue N00In = N00Elt.getOperand(0);
38514     SDValue N01In = N01Elt.getOperand(0);
38515     SDValue N10In = N10Elt.getOperand(0);
38516     SDValue N11In = N11Elt.getOperand(0);
38517     // First time we find an input capture it.
38518     if (!ZExtIn) {
38519       ZExtIn = N00In;
38520       SExtIn = N01In;
38521     }
38522     if (ZExtIn != N00In || SExtIn != N01In ||
38523         ZExtIn != N10In || SExtIn != N11In)
38524       return SDValue();
38525   }
38526 
38527   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
38528                          ArrayRef<SDValue> Ops) {
38529     // Shrink by adding truncate nodes and let DAGCombine fold with the
38530     // sources.
38531     EVT InVT = Ops[0].getValueType();
38532     assert(InVT.getScalarType() == MVT::i8 &&
38533            "Unexpected scalar element type");
38534     assert(InVT == Ops[1].getValueType() && "Operands' types mismatch");
38535     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
38536                                  InVT.getVectorNumElements() / 2);
38537     return DAG.getNode(X86ISD::VPMADDUBSW, DL, ResVT, Ops[0], Ops[1]);
38538   };
38539   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { ZExtIn, SExtIn },
38540                           PMADDBuilder);
38541 }
38542 
combineTruncate(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)38543 static SDValue combineTruncate(SDNode *N, SelectionDAG &DAG,
38544                                const X86Subtarget &Subtarget) {
38545   EVT VT = N->getValueType(0);
38546   SDValue Src = N->getOperand(0);
38547   SDLoc DL(N);
38548 
38549   // Attempt to pre-truncate inputs to arithmetic ops instead.
38550   if (SDValue V = combineTruncatedArithmetic(N, DAG, Subtarget, DL))
38551     return V;
38552 
38553   // Try to detect AVG pattern first.
38554   if (SDValue Avg = detectAVGPattern(Src, VT, DAG, Subtarget, DL))
38555     return Avg;
38556 
38557   // Try to detect PMADD
38558   if (SDValue PMAdd = detectPMADDUBSW(Src, VT, DAG, Subtarget, DL))
38559     return PMAdd;
38560 
38561   // Try to combine truncation with signed/unsigned saturation.
38562   if (SDValue Val = combineTruncateWithSat(Src, VT, DL, DAG, Subtarget))
38563     return Val;
38564 
38565   // Try to combine PMULHUW/PMULHW for vXi16.
38566   if (SDValue V = combinePMULH(Src, VT, DL, DAG, Subtarget))
38567     return V;
38568 
38569   // The bitcast source is a direct mmx result.
38570   // Detect bitcasts between i32 to x86mmx
38571   if (Src.getOpcode() == ISD::BITCAST && VT == MVT::i32) {
38572     SDValue BCSrc = Src.getOperand(0);
38573     if (BCSrc.getValueType() == MVT::x86mmx)
38574       return DAG.getNode(X86ISD::MMX_MOVD2W, DL, MVT::i32, BCSrc);
38575   }
38576 
38577   // Try to truncate extended sign/zero bits with PACKSS/PACKUS.
38578   if (SDValue V = combineVectorSignBitsTruncation(N, DL, DAG, Subtarget))
38579     return V;
38580 
38581   return combineVectorTruncation(N, DAG, Subtarget);
38582 }
38583 
38584 /// Returns the negated value if the node \p N flips sign of FP value.
38585 ///
38586 /// FP-negation node may have different forms: FNEG(x), FXOR (x, 0x80000000)
38587 /// or FSUB(0, x)
38588 /// AVX512F does not have FXOR, so FNEG is lowered as
38589 /// (bitcast (xor (bitcast x), (bitcast ConstantFP(0x80000000)))).
38590 /// In this case we go though all bitcasts.
38591 /// This also recognizes splat of a negated value and returns the splat of that
38592 /// value.
isFNEG(SelectionDAG & DAG,SDNode * N)38593 static SDValue isFNEG(SelectionDAG &DAG, SDNode *N) {
38594   if (N->getOpcode() == ISD::FNEG)
38595     return N->getOperand(0);
38596 
38597   SDValue Op = peekThroughBitcasts(SDValue(N, 0));
38598   auto VT = Op->getValueType(0);
38599   if (auto SVOp = dyn_cast<ShuffleVectorSDNode>(Op.getNode())) {
38600     // For a VECTOR_SHUFFLE(VEC1, VEC2), if the VEC2 is undef, then the negate
38601     // of this is VECTOR_SHUFFLE(-VEC1, UNDEF).  The mask can be anything here.
38602     if (!SVOp->getOperand(1).isUndef())
38603       return SDValue();
38604     if (SDValue NegOp0 = isFNEG(DAG, SVOp->getOperand(0).getNode()))
38605       return DAG.getVectorShuffle(VT, SDLoc(SVOp), NegOp0, DAG.getUNDEF(VT),
38606                                   SVOp->getMask());
38607     return SDValue();
38608   }
38609   unsigned Opc = Op.getOpcode();
38610   if (Opc == ISD::INSERT_VECTOR_ELT) {
38611     // Negate of INSERT_VECTOR_ELT(UNDEF, V, INDEX) is INSERT_VECTOR_ELT(UNDEF,
38612     // -V, INDEX).
38613     SDValue InsVector = Op.getOperand(0);
38614     SDValue InsVal = Op.getOperand(1);
38615     if (!InsVector.isUndef())
38616       return SDValue();
38617     if (SDValue NegInsVal = isFNEG(DAG, InsVal.getNode()))
38618       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Op), VT, InsVector,
38619                          NegInsVal, Op.getOperand(2));
38620     return SDValue();
38621   }
38622 
38623   if (Opc != X86ISD::FXOR && Opc != ISD::XOR && Opc != ISD::FSUB)
38624     return SDValue();
38625 
38626   SDValue Op1 = peekThroughBitcasts(Op.getOperand(1));
38627   if (!Op1.getValueType().isFloatingPoint())
38628     return SDValue();
38629 
38630   SDValue Op0 = peekThroughBitcasts(Op.getOperand(0));
38631 
38632   // For XOR and FXOR, we want to check if constant bits of Op1 are sign bit
38633   // masks. For FSUB, we have to check if constant bits of Op0 are sign bit
38634   // masks and hence we swap the operands.
38635   if (Opc == ISD::FSUB)
38636     std::swap(Op0, Op1);
38637 
38638   APInt UndefElts;
38639   SmallVector<APInt, 16> EltBits;
38640   // Extract constant bits and see if they are all sign bit masks. Ignore the
38641   // undef elements.
38642   if (getTargetConstantBitsFromNode(Op1, Op1.getScalarValueSizeInBits(),
38643                                     UndefElts, EltBits,
38644                                     /* AllowWholeUndefs */ true,
38645                                     /* AllowPartialUndefs */ false)) {
38646     for (unsigned I = 0, E = EltBits.size(); I < E; I++)
38647       if (!UndefElts[I] && !EltBits[I].isSignMask())
38648         return SDValue();
38649 
38650     return peekThroughBitcasts(Op0);
38651   }
38652 
38653   return SDValue();
38654 }
38655 
38656 /// Do target-specific dag combines on floating point negations.
combineFneg(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)38657 static SDValue combineFneg(SDNode *N, SelectionDAG &DAG,
38658                            const X86Subtarget &Subtarget) {
38659   EVT OrigVT = N->getValueType(0);
38660   SDValue Arg = isFNEG(DAG, N);
38661   if (!Arg)
38662     return SDValue();
38663 
38664   EVT VT = Arg.getValueType();
38665   EVT SVT = VT.getScalarType();
38666   SDLoc DL(N);
38667 
38668   // Let legalize expand this if it isn't a legal type yet.
38669   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
38670     return SDValue();
38671 
38672   // If we're negating a FMUL node on a target with FMA, then we can avoid the
38673   // use of a constant by performing (-0 - A*B) instead.
38674   // FIXME: Check rounding control flags as well once it becomes available.
38675   if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
38676       Arg->getFlags().hasNoSignedZeros() && Subtarget.hasAnyFMA()) {
38677     SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
38678     SDValue NewNode = DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
38679                                   Arg.getOperand(1), Zero);
38680     return DAG.getBitcast(OrigVT, NewNode);
38681   }
38682 
38683   // If we're negating an FMA node, then we can adjust the
38684   // instruction to include the extra negation.
38685   unsigned NewOpcode = 0;
38686   if (Arg.hasOneUse() && Subtarget.hasAnyFMA()) {
38687     switch (Arg.getOpcode()) {
38688     case ISD::FMA:             NewOpcode = X86ISD::FNMSUB;       break;
38689     case X86ISD::FMSUB:        NewOpcode = X86ISD::FNMADD;       break;
38690     case X86ISD::FNMADD:       NewOpcode = X86ISD::FMSUB;        break;
38691     case X86ISD::FNMSUB:       NewOpcode = ISD::FMA;             break;
38692     case X86ISD::FMADD_RND:    NewOpcode = X86ISD::FNMSUB_RND;   break;
38693     case X86ISD::FMSUB_RND:    NewOpcode = X86ISD::FNMADD_RND;   break;
38694     case X86ISD::FNMADD_RND:   NewOpcode = X86ISD::FMSUB_RND;    break;
38695     case X86ISD::FNMSUB_RND:   NewOpcode = X86ISD::FMADD_RND;    break;
38696     // We can't handle scalar intrinsic node here because it would only
38697     // invert one element and not the whole vector. But we could try to handle
38698     // a negation of the lower element only.
38699     }
38700   }
38701   if (NewOpcode)
38702     return DAG.getBitcast(OrigVT, DAG.getNode(NewOpcode, DL, VT,
38703                                               Arg.getNode()->ops()));
38704 
38705   return SDValue();
38706 }
38707 
lowerX86FPLogicOp(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)38708 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
38709                                  const X86Subtarget &Subtarget) {
38710   MVT VT = N->getSimpleValueType(0);
38711   // If we have integer vector types available, use the integer opcodes.
38712   if (!VT.isVector() || !Subtarget.hasSSE2())
38713     return SDValue();
38714 
38715   SDLoc dl(N);
38716 
38717   unsigned IntBits = VT.getScalarSizeInBits();
38718   MVT IntSVT = MVT::getIntegerVT(IntBits);
38719   MVT IntVT = MVT::getVectorVT(IntSVT, VT.getSizeInBits() / IntBits);
38720 
38721   SDValue Op0 = DAG.getBitcast(IntVT, N->getOperand(0));
38722   SDValue Op1 = DAG.getBitcast(IntVT, N->getOperand(1));
38723   unsigned IntOpcode;
38724   switch (N->getOpcode()) {
38725   default: llvm_unreachable("Unexpected FP logic op");
38726   case X86ISD::FOR:   IntOpcode = ISD::OR; break;
38727   case X86ISD::FXOR:  IntOpcode = ISD::XOR; break;
38728   case X86ISD::FAND:  IntOpcode = ISD::AND; break;
38729   case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
38730   }
38731   SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
38732   return DAG.getBitcast(VT, IntOp);
38733 }
38734 
38735 
38736 /// Fold a xor(setcc cond, val), 1 --> setcc (inverted(cond), val)
foldXor1SetCC(SDNode * N,SelectionDAG & DAG)38737 static SDValue foldXor1SetCC(SDNode *N, SelectionDAG &DAG) {
38738   if (N->getOpcode() != ISD::XOR)
38739     return SDValue();
38740 
38741   SDValue LHS = N->getOperand(0);
38742   auto *RHSC = dyn_cast<ConstantSDNode>(N->getOperand(1));
38743   if (!RHSC || RHSC->getZExtValue() != 1 || LHS->getOpcode() != X86ISD::SETCC)
38744     return SDValue();
38745 
38746   X86::CondCode NewCC = X86::GetOppositeBranchCondition(
38747       X86::CondCode(LHS->getConstantOperandVal(0)));
38748   SDLoc DL(N);
38749   return getSETCC(NewCC, LHS->getOperand(1), DL, DAG);
38750 }
38751 
combineXor(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)38752 static SDValue combineXor(SDNode *N, SelectionDAG &DAG,
38753                           TargetLowering::DAGCombinerInfo &DCI,
38754                           const X86Subtarget &Subtarget) {
38755   // If this is SSE1 only convert to FXOR to avoid scalarization.
38756   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() &&
38757       N->getValueType(0) == MVT::v4i32) {
38758     return DAG.getBitcast(
38759         MVT::v4i32, DAG.getNode(X86ISD::FXOR, SDLoc(N), MVT::v4f32,
38760                                 DAG.getBitcast(MVT::v4f32, N->getOperand(0)),
38761                                 DAG.getBitcast(MVT::v4f32, N->getOperand(1))));
38762   }
38763 
38764   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
38765     return Cmp;
38766 
38767   if (DCI.isBeforeLegalizeOps())
38768     return SDValue();
38769 
38770   if (SDValue SetCC = foldXor1SetCC(N, DAG))
38771     return SetCC;
38772 
38773   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
38774     return RV;
38775 
38776   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
38777     return FPLogic;
38778 
38779   return combineFneg(N, DAG, Subtarget);
38780 }
38781 
combineBEXTR(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)38782 static SDValue combineBEXTR(SDNode *N, SelectionDAG &DAG,
38783                             TargetLowering::DAGCombinerInfo &DCI,
38784                             const X86Subtarget &Subtarget) {
38785   SDValue Op0 = N->getOperand(0);
38786   SDValue Op1 = N->getOperand(1);
38787   EVT VT = N->getValueType(0);
38788   unsigned NumBits = VT.getSizeInBits();
38789 
38790   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
38791 
38792   // TODO - Constant Folding.
38793   if (auto *Cst1 = dyn_cast<ConstantSDNode>(Op1)) {
38794     // Reduce Cst1 to the bottom 16-bits.
38795     // NOTE: SimplifyDemandedBits won't do this for constants.
38796     const APInt &Val1 = Cst1->getAPIntValue();
38797     APInt MaskedVal1 = Val1 & 0xFFFF;
38798     if (MaskedVal1 != Val1)
38799       return DAG.getNode(X86ISD::BEXTR, SDLoc(N), VT, Op0,
38800                          DAG.getConstant(MaskedVal1, SDLoc(N), VT));
38801   }
38802 
38803   // Only bottom 16-bits of the control bits are required.
38804   APInt DemandedMask(APInt::getLowBitsSet(NumBits, 16));
38805   if (TLI.SimplifyDemandedBits(Op1, DemandedMask, DCI))
38806     return SDValue(N, 0);
38807 
38808   return SDValue();
38809 }
38810 
isNullFPScalarOrVectorConst(SDValue V)38811 static bool isNullFPScalarOrVectorConst(SDValue V) {
38812   return isNullFPConstant(V) || ISD::isBuildVectorAllZeros(V.getNode());
38813 }
38814 
38815 /// If a value is a scalar FP zero or a vector FP zero (potentially including
38816 /// undefined elements), return a zero constant that may be used to fold away
38817 /// that value. In the case of a vector, the returned constant will not contain
38818 /// undefined elements even if the input parameter does. This makes it suitable
38819 /// to be used as a replacement operand with operations (eg, bitwise-and) where
38820 /// an undef should not propagate.
getNullFPConstForNullVal(SDValue V,SelectionDAG & DAG,const X86Subtarget & Subtarget)38821 static SDValue getNullFPConstForNullVal(SDValue V, SelectionDAG &DAG,
38822                                         const X86Subtarget &Subtarget) {
38823   if (!isNullFPScalarOrVectorConst(V))
38824     return SDValue();
38825 
38826   if (V.getValueType().isVector())
38827     return getZeroVector(V.getSimpleValueType(), Subtarget, DAG, SDLoc(V));
38828 
38829   return V;
38830 }
38831 
combineFAndFNotToFAndn(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)38832 static SDValue combineFAndFNotToFAndn(SDNode *N, SelectionDAG &DAG,
38833                                       const X86Subtarget &Subtarget) {
38834   SDValue N0 = N->getOperand(0);
38835   SDValue N1 = N->getOperand(1);
38836   EVT VT = N->getValueType(0);
38837   SDLoc DL(N);
38838 
38839   // Vector types are handled in combineANDXORWithAllOnesIntoANDNP().
38840   if (!((VT == MVT::f32 && Subtarget.hasSSE1()) ||
38841         (VT == MVT::f64 && Subtarget.hasSSE2()) ||
38842         (VT == MVT::v4f32 && Subtarget.hasSSE1() && !Subtarget.hasSSE2())))
38843     return SDValue();
38844 
38845   auto isAllOnesConstantFP = [](SDValue V) {
38846     if (V.getSimpleValueType().isVector())
38847       return ISD::isBuildVectorAllOnes(V.getNode());
38848     auto *C = dyn_cast<ConstantFPSDNode>(V);
38849     return C && C->getConstantFPValue()->isAllOnesValue();
38850   };
38851 
38852   // fand (fxor X, -1), Y --> fandn X, Y
38853   if (N0.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N0.getOperand(1)))
38854     return DAG.getNode(X86ISD::FANDN, DL, VT, N0.getOperand(0), N1);
38855 
38856   // fand X, (fxor Y, -1) --> fandn Y, X
38857   if (N1.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N1.getOperand(1)))
38858     return DAG.getNode(X86ISD::FANDN, DL, VT, N1.getOperand(0), N0);
38859 
38860   return SDValue();
38861 }
38862 
38863 /// Do target-specific dag combines on X86ISD::FAND nodes.
combineFAnd(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)38864 static SDValue combineFAnd(SDNode *N, SelectionDAG &DAG,
38865                            const X86Subtarget &Subtarget) {
38866   // FAND(0.0, x) -> 0.0
38867   if (SDValue V = getNullFPConstForNullVal(N->getOperand(0), DAG, Subtarget))
38868     return V;
38869 
38870   // FAND(x, 0.0) -> 0.0
38871   if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
38872     return V;
38873 
38874   if (SDValue V = combineFAndFNotToFAndn(N, DAG, Subtarget))
38875     return V;
38876 
38877   return lowerX86FPLogicOp(N, DAG, Subtarget);
38878 }
38879 
38880 /// Do target-specific dag combines on X86ISD::FANDN nodes.
combineFAndn(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)38881 static SDValue combineFAndn(SDNode *N, SelectionDAG &DAG,
38882                             const X86Subtarget &Subtarget) {
38883   // FANDN(0.0, x) -> x
38884   if (isNullFPScalarOrVectorConst(N->getOperand(0)))
38885     return N->getOperand(1);
38886 
38887   // FANDN(x, 0.0) -> 0.0
38888   if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
38889     return V;
38890 
38891   return lowerX86FPLogicOp(N, DAG, Subtarget);
38892 }
38893 
38894 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
combineFOr(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)38895 static SDValue combineFOr(SDNode *N, SelectionDAG &DAG,
38896                           const X86Subtarget &Subtarget) {
38897   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
38898 
38899   // F[X]OR(0.0, x) -> x
38900   if (isNullFPScalarOrVectorConst(N->getOperand(0)))
38901     return N->getOperand(1);
38902 
38903   // F[X]OR(x, 0.0) -> x
38904   if (isNullFPScalarOrVectorConst(N->getOperand(1)))
38905     return N->getOperand(0);
38906 
38907   if (SDValue NewVal = combineFneg(N, DAG, Subtarget))
38908     return NewVal;
38909 
38910   return lowerX86FPLogicOp(N, DAG, Subtarget);
38911 }
38912 
38913 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
combineFMinFMax(SDNode * N,SelectionDAG & DAG)38914 static SDValue combineFMinFMax(SDNode *N, SelectionDAG &DAG) {
38915   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
38916 
38917   // Only perform optimizations if UnsafeMath is used.
38918   if (!DAG.getTarget().Options.UnsafeFPMath)
38919     return SDValue();
38920 
38921   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
38922   // into FMINC and FMAXC, which are Commutative operations.
38923   unsigned NewOp = 0;
38924   switch (N->getOpcode()) {
38925     default: llvm_unreachable("unknown opcode");
38926     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
38927     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
38928   }
38929 
38930   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
38931                      N->getOperand(0), N->getOperand(1));
38932 }
38933 
combineFMinNumFMaxNum(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)38934 static SDValue combineFMinNumFMaxNum(SDNode *N, SelectionDAG &DAG,
38935                                      const X86Subtarget &Subtarget) {
38936   if (Subtarget.useSoftFloat())
38937     return SDValue();
38938 
38939   // TODO: If an operand is already known to be a NaN or not a NaN, this
38940   //       should be an optional swap and FMAX/FMIN.
38941 
38942   EVT VT = N->getValueType(0);
38943   if (!((Subtarget.hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
38944         (Subtarget.hasSSE2() && (VT == MVT::f64 || VT == MVT::v2f64)) ||
38945         (Subtarget.hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))))
38946     return SDValue();
38947 
38948   SDValue Op0 = N->getOperand(0);
38949   SDValue Op1 = N->getOperand(1);
38950   SDLoc DL(N);
38951   auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
38952 
38953   // If we don't have to respect NaN inputs, this is a direct translation to x86
38954   // min/max instructions.
38955   if (DAG.getTarget().Options.NoNaNsFPMath || N->getFlags().hasNoNaNs())
38956     return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
38957 
38958   // If we have to respect NaN inputs, this takes at least 3 instructions.
38959   // Favor a library call when operating on a scalar and minimizing code size.
38960   if (!VT.isVector() && DAG.getMachineFunction().getFunction().optForMinSize())
38961     return SDValue();
38962 
38963   EVT SetCCType = DAG.getTargetLoweringInfo().getSetCCResultType(
38964       DAG.getDataLayout(), *DAG.getContext(), VT);
38965 
38966   // There are 4 possibilities involving NaN inputs, and these are the required
38967   // outputs:
38968   //                   Op1
38969   //               Num     NaN
38970   //            ----------------
38971   //       Num  |  Max  |  Op0 |
38972   // Op0        ----------------
38973   //       NaN  |  Op1  |  NaN |
38974   //            ----------------
38975   //
38976   // The SSE FP max/min instructions were not designed for this case, but rather
38977   // to implement:
38978   //   Min = Op1 < Op0 ? Op1 : Op0
38979   //   Max = Op1 > Op0 ? Op1 : Op0
38980   //
38981   // So they always return Op0 if either input is a NaN. However, we can still
38982   // use those instructions for fmaxnum by selecting away a NaN input.
38983 
38984   // If either operand is NaN, the 2nd source operand (Op0) is passed through.
38985   SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
38986   SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType, Op0, Op0, ISD::SETUO);
38987 
38988   // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
38989   // are NaN, the NaN value of Op1 is the result.
38990   return DAG.getSelect(DL, VT, IsOp0Nan, Op1, MinOrMax);
38991 }
38992 
combineX86INT_TO_FP(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)38993 static SDValue combineX86INT_TO_FP(SDNode *N, SelectionDAG &DAG,
38994                                    TargetLowering::DAGCombinerInfo &DCI) {
38995   EVT VT = N->getValueType(0);
38996   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
38997 
38998   APInt KnownUndef, KnownZero;
38999   APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
39000   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, KnownUndef,
39001                                      KnownZero, DCI))
39002     return SDValue(N, 0);
39003 
39004   return SDValue();
39005 }
39006 
39007 /// Do target-specific dag combines on X86ISD::ANDNP nodes.
combineAndnp(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)39008 static SDValue combineAndnp(SDNode *N, SelectionDAG &DAG,
39009                             TargetLowering::DAGCombinerInfo &DCI,
39010                             const X86Subtarget &Subtarget) {
39011   MVT VT = N->getSimpleValueType(0);
39012 
39013   // ANDNP(0, x) -> x
39014   if (ISD::isBuildVectorAllZeros(N->getOperand(0).getNode()))
39015     return N->getOperand(1);
39016 
39017   // ANDNP(x, 0) -> 0
39018   if (ISD::isBuildVectorAllZeros(N->getOperand(1).getNode()))
39019     return DAG.getConstant(0, SDLoc(N), VT);
39020 
39021   // Turn ANDNP back to AND if input is inverted.
39022   if (VT.isVector() && N->getOperand(0).getOpcode() == ISD::XOR &&
39023       ISD::isBuildVectorAllOnes(N->getOperand(0).getOperand(1).getNode())) {
39024     return DAG.getNode(ISD::AND, SDLoc(N), VT,
39025                        N->getOperand(0).getOperand(0), N->getOperand(1));
39026   }
39027 
39028   // Attempt to recursively combine a bitmask ANDNP with shuffles.
39029   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
39030     SDValue Op(N, 0);
39031     if (SDValue Res = combineX86ShufflesRecursively(
39032             {Op}, 0, Op, {0}, {}, /*Depth*/ 1,
39033             /*HasVarMask*/ false, /*AllowVarMask*/ true, DAG, Subtarget))
39034       return Res;
39035   }
39036 
39037   return SDValue();
39038 }
39039 
combineBT(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)39040 static SDValue combineBT(SDNode *N, SelectionDAG &DAG,
39041                          TargetLowering::DAGCombinerInfo &DCI) {
39042   SDValue N0 = N->getOperand(0);
39043   SDValue N1 = N->getOperand(1);
39044 
39045   // BT ignores high bits in the bit index operand.
39046   unsigned BitWidth = N1.getValueSizeInBits();
39047   APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
39048   if (SDValue DemandedN1 = DAG.GetDemandedBits(N1, DemandedMask))
39049     return DAG.getNode(X86ISD::BT, SDLoc(N), MVT::i32, N0, DemandedN1);
39050 
39051   return SDValue();
39052 }
39053 
39054 // Try to combine sext_in_reg of a cmov of constants by extending the constants.
combineSextInRegCmov(SDNode * N,SelectionDAG & DAG)39055 static SDValue combineSextInRegCmov(SDNode *N, SelectionDAG &DAG) {
39056   EVT VT = N->getValueType(0);
39057 
39058   SDValue N0 = N->getOperand(0);
39059   SDValue N1 = N->getOperand(1);
39060   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
39061 
39062   if (ExtraVT != MVT::i16)
39063     return SDValue();
39064 
39065   // Look through single use any_extends.
39066   if (N0.getOpcode() == ISD::ANY_EXTEND && N0.hasOneUse())
39067     N0 = N0.getOperand(0);
39068 
39069   // See if we have a single use cmov.
39070   if (N0.getOpcode() != X86ISD::CMOV || !N0.hasOneUse())
39071     return SDValue();
39072 
39073   SDValue CMovOp0 = N0.getOperand(0);
39074   SDValue CMovOp1 = N0.getOperand(1);
39075 
39076   // Make sure both operands are constants.
39077   if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
39078       !isa<ConstantSDNode>(CMovOp1.getNode()))
39079     return SDValue();
39080 
39081   SDLoc DL(N);
39082 
39083   // If we looked through an any_extend above, add one to the constants.
39084   if (N0.getValueType() != VT) {
39085     CMovOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, VT, CMovOp0);
39086     CMovOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, VT, CMovOp1);
39087   }
39088 
39089   CMovOp0 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, CMovOp0, N1);
39090   CMovOp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, CMovOp1, N1);
39091 
39092   return DAG.getNode(X86ISD::CMOV, DL, VT, CMovOp0, CMovOp1,
39093                      N0.getOperand(2), N0.getOperand(3));
39094 }
39095 
combineSignExtendInReg(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)39096 static SDValue combineSignExtendInReg(SDNode *N, SelectionDAG &DAG,
39097                                       const X86Subtarget &Subtarget) {
39098   if (SDValue V = combineSextInRegCmov(N, DAG))
39099     return V;
39100 
39101   EVT VT = N->getValueType(0);
39102   SDValue N0 = N->getOperand(0);
39103   SDValue N1 = N->getOperand(1);
39104   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
39105   SDLoc dl(N);
39106 
39107   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
39108   // both SSE and AVX2 since there is no sign-extended shift right
39109   // operation on a vector with 64-bit elements.
39110   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
39111   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
39112   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
39113       N0.getOpcode() == ISD::SIGN_EXTEND)) {
39114     SDValue N00 = N0.getOperand(0);
39115 
39116     // EXTLOAD has a better solution on AVX2,
39117     // it may be replaced with X86ISD::VSEXT node.
39118     if (N00.getOpcode() == ISD::LOAD && Subtarget.hasInt256())
39119       if (!ISD::isNormalLoad(N00.getNode()))
39120         return SDValue();
39121 
39122     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
39123         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
39124                                   N00, N1);
39125       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
39126     }
39127   }
39128   return SDValue();
39129 }
39130 
39131 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
39132 /// zext(add_nuw(x, C)) --> add(zext(x), C_zext)
39133 /// Promoting a sign/zero extension ahead of a no overflow 'add' exposes
39134 /// opportunities to combine math ops, use an LEA, or use a complex addressing
39135 /// mode. This can eliminate extend, add, and shift instructions.
promoteExtBeforeAdd(SDNode * Ext,SelectionDAG & DAG,const X86Subtarget & Subtarget)39136 static SDValue promoteExtBeforeAdd(SDNode *Ext, SelectionDAG &DAG,
39137                                    const X86Subtarget &Subtarget) {
39138   if (Ext->getOpcode() != ISD::SIGN_EXTEND &&
39139       Ext->getOpcode() != ISD::ZERO_EXTEND)
39140     return SDValue();
39141 
39142   // TODO: This should be valid for other integer types.
39143   EVT VT = Ext->getValueType(0);
39144   if (VT != MVT::i64)
39145     return SDValue();
39146 
39147   SDValue Add = Ext->getOperand(0);
39148   if (Add.getOpcode() != ISD::ADD)
39149     return SDValue();
39150 
39151   bool Sext = Ext->getOpcode() == ISD::SIGN_EXTEND;
39152   bool NSW = Add->getFlags().hasNoSignedWrap();
39153   bool NUW = Add->getFlags().hasNoUnsignedWrap();
39154 
39155   // We need an 'add nsw' feeding into the 'sext' or 'add nuw' feeding
39156   // into the 'zext'
39157   if ((Sext && !NSW) || (!Sext && !NUW))
39158     return SDValue();
39159 
39160   // Having a constant operand to the 'add' ensures that we are not increasing
39161   // the instruction count because the constant is extended for free below.
39162   // A constant operand can also become the displacement field of an LEA.
39163   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
39164   if (!AddOp1)
39165     return SDValue();
39166 
39167   // Don't make the 'add' bigger if there's no hope of combining it with some
39168   // other 'add' or 'shl' instruction.
39169   // TODO: It may be profitable to generate simpler LEA instructions in place
39170   // of single 'add' instructions, but the cost model for selecting an LEA
39171   // currently has a high threshold.
39172   bool HasLEAPotential = false;
39173   for (auto *User : Ext->uses()) {
39174     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
39175       HasLEAPotential = true;
39176       break;
39177     }
39178   }
39179   if (!HasLEAPotential)
39180     return SDValue();
39181 
39182   // Everything looks good, so pull the '{s|z}ext' ahead of the 'add'.
39183   int64_t AddConstant = Sext ? AddOp1->getSExtValue() : AddOp1->getZExtValue();
39184   SDValue AddOp0 = Add.getOperand(0);
39185   SDValue NewExt = DAG.getNode(Ext->getOpcode(), SDLoc(Ext), VT, AddOp0);
39186   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
39187 
39188   // The wider add is guaranteed to not wrap because both operands are
39189   // sign-extended.
39190   SDNodeFlags Flags;
39191   Flags.setNoSignedWrap(NSW);
39192   Flags.setNoUnsignedWrap(NUW);
39193   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewExt, NewConstant, Flags);
39194 }
39195 
39196 // If we face {ANY,SIGN,ZERO}_EXTEND that is applied to a CMOV with constant
39197 // operands and the result of CMOV is not used anywhere else - promote CMOV
39198 // itself instead of promoting its result. This could be beneficial, because:
39199 //     1) X86TargetLowering::EmitLoweredSelect later can do merging of two
39200 //        (or more) pseudo-CMOVs only when they go one-after-another and
39201 //        getting rid of result extension code after CMOV will help that.
39202 //     2) Promotion of constant CMOV arguments is free, hence the
39203 //        {ANY,SIGN,ZERO}_EXTEND will just be deleted.
39204 //     3) 16-bit CMOV encoding is 4 bytes, 32-bit CMOV is 3-byte, so this
39205 //        promotion is also good in terms of code-size.
39206 //        (64-bit CMOV is 4-bytes, that's why we don't do 32-bit => 64-bit
39207 //         promotion).
combineToExtendCMOV(SDNode * Extend,SelectionDAG & DAG)39208 static SDValue combineToExtendCMOV(SDNode *Extend, SelectionDAG &DAG) {
39209   SDValue CMovN = Extend->getOperand(0);
39210   if (CMovN.getOpcode() != X86ISD::CMOV || !CMovN.hasOneUse())
39211     return SDValue();
39212 
39213   EVT TargetVT = Extend->getValueType(0);
39214   unsigned ExtendOpcode = Extend->getOpcode();
39215   SDLoc DL(Extend);
39216 
39217   EVT VT = CMovN.getValueType();
39218   SDValue CMovOp0 = CMovN.getOperand(0);
39219   SDValue CMovOp1 = CMovN.getOperand(1);
39220 
39221   if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
39222       !isa<ConstantSDNode>(CMovOp1.getNode()))
39223     return SDValue();
39224 
39225   // Only extend to i32 or i64.
39226   if (TargetVT != MVT::i32 && TargetVT != MVT::i64)
39227     return SDValue();
39228 
39229   // Only extend from i16 unless its a sign_extend from i32. Zext/aext from i32
39230   // are free.
39231   if (VT != MVT::i16 && !(ExtendOpcode == ISD::SIGN_EXTEND && VT == MVT::i32))
39232     return SDValue();
39233 
39234   // If this a zero extend to i64, we should only extend to i32 and use a free
39235   // zero extend to finish.
39236   EVT ExtendVT = TargetVT;
39237   if (TargetVT == MVT::i64 && ExtendOpcode != ISD::SIGN_EXTEND)
39238     ExtendVT = MVT::i32;
39239 
39240   CMovOp0 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp0);
39241   CMovOp1 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp1);
39242 
39243   SDValue Res = DAG.getNode(X86ISD::CMOV, DL, ExtendVT, CMovOp0, CMovOp1,
39244                             CMovN.getOperand(2), CMovN.getOperand(3));
39245 
39246   // Finish extending if needed.
39247   if (ExtendVT != TargetVT)
39248     Res = DAG.getNode(ExtendOpcode, DL, TargetVT, Res);
39249 
39250   return Res;
39251 }
39252 
39253 // Convert (vXiY *ext(vXi1 bitcast(iX))) to extend_in_reg(broadcast(iX)).
39254 // This is more or less the reverse of combineBitcastvxi1.
39255 static SDValue
combineToExtendBoolVectorInReg(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)39256 combineToExtendBoolVectorInReg(SDNode *N, SelectionDAG &DAG,
39257                                TargetLowering::DAGCombinerInfo &DCI,
39258                                const X86Subtarget &Subtarget) {
39259   unsigned Opcode = N->getOpcode();
39260   if (Opcode != ISD::SIGN_EXTEND && Opcode != ISD::ZERO_EXTEND &&
39261       Opcode != ISD::ANY_EXTEND)
39262     return SDValue();
39263   if (!DCI.isBeforeLegalizeOps())
39264     return SDValue();
39265   if (!Subtarget.hasSSE2() || Subtarget.hasAVX512())
39266     return SDValue();
39267 
39268   SDValue N0 = N->getOperand(0);
39269   EVT VT = N->getValueType(0);
39270   EVT SVT = VT.getScalarType();
39271   EVT InSVT = N0.getValueType().getScalarType();
39272   unsigned EltSizeInBits = SVT.getSizeInBits();
39273 
39274   // Input type must be extending a bool vector (bit-casted from a scalar
39275   // integer) to legal integer types.
39276   if (!VT.isVector())
39277     return SDValue();
39278   if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16 && SVT != MVT::i8)
39279     return SDValue();
39280   if (InSVT != MVT::i1 || N0.getOpcode() != ISD::BITCAST)
39281     return SDValue();
39282 
39283   SDValue N00 = N0.getOperand(0);
39284   EVT SclVT = N0.getOperand(0).getValueType();
39285   if (!SclVT.isScalarInteger())
39286     return SDValue();
39287 
39288   SDLoc DL(N);
39289   SDValue Vec;
39290   SmallVector<int, 32> ShuffleMask;
39291   unsigned NumElts = VT.getVectorNumElements();
39292   assert(NumElts == SclVT.getSizeInBits() && "Unexpected bool vector size");
39293 
39294   // Broadcast the scalar integer to the vector elements.
39295   if (NumElts > EltSizeInBits) {
39296     // If the scalar integer is greater than the vector element size, then we
39297     // must split it down into sub-sections for broadcasting. For example:
39298     //   i16 -> v16i8 (i16 -> v8i16 -> v16i8) with 2 sub-sections.
39299     //   i32 -> v32i8 (i32 -> v8i32 -> v32i8) with 4 sub-sections.
39300     assert((NumElts % EltSizeInBits) == 0 && "Unexpected integer scale");
39301     unsigned Scale = NumElts / EltSizeInBits;
39302     EVT BroadcastVT =
39303         EVT::getVectorVT(*DAG.getContext(), SclVT, EltSizeInBits);
39304     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, BroadcastVT, N00);
39305     Vec = DAG.getBitcast(VT, Vec);
39306 
39307     for (unsigned i = 0; i != Scale; ++i)
39308       ShuffleMask.append(EltSizeInBits, i);
39309   } else {
39310     // For smaller scalar integers, we can simply any-extend it to the vector
39311     // element size (we don't care about the upper bits) and broadcast it to all
39312     // elements.
39313     SDValue Scl = DAG.getAnyExtOrTrunc(N00, DL, SVT);
39314     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
39315     ShuffleMask.append(NumElts, 0);
39316   }
39317   Vec = DAG.getVectorShuffle(VT, DL, Vec, Vec, ShuffleMask);
39318 
39319   // Now, mask the relevant bit in each element.
39320   SmallVector<SDValue, 32> Bits;
39321   for (unsigned i = 0; i != NumElts; ++i) {
39322     int BitIdx = (i % EltSizeInBits);
39323     APInt Bit = APInt::getBitsSet(EltSizeInBits, BitIdx, BitIdx + 1);
39324     Bits.push_back(DAG.getConstant(Bit, DL, SVT));
39325   }
39326   SDValue BitMask = DAG.getBuildVector(VT, DL, Bits);
39327   Vec = DAG.getNode(ISD::AND, DL, VT, Vec, BitMask);
39328 
39329   // Compare against the bitmask and extend the result.
39330   EVT CCVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumElts);
39331   Vec = DAG.getSetCC(DL, CCVT, Vec, BitMask, ISD::SETEQ);
39332   Vec = DAG.getSExtOrTrunc(Vec, DL, VT);
39333 
39334   // For SEXT, this is now done, otherwise shift the result down for
39335   // zero-extension.
39336   if (Opcode == ISD::SIGN_EXTEND)
39337     return Vec;
39338   return DAG.getNode(ISD::SRL, DL, VT, Vec,
39339                      DAG.getConstant(EltSizeInBits - 1, DL, VT));
39340 }
39341 
39342 /// Convert a SEXT or ZEXT of a vector to a SIGN_EXTEND_VECTOR_INREG or
39343 /// ZERO_EXTEND_VECTOR_INREG, this requires the splitting (or concatenating
39344 /// with UNDEFs) of the input to vectors of the same size as the target type
39345 /// which then extends the lowest elements.
combineToExtendVectorInReg(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)39346 static SDValue combineToExtendVectorInReg(SDNode *N, SelectionDAG &DAG,
39347                                           TargetLowering::DAGCombinerInfo &DCI,
39348                                           const X86Subtarget &Subtarget) {
39349   if (ExperimentalVectorWideningLegalization)
39350     return SDValue();
39351 
39352   unsigned Opcode = N->getOpcode();
39353   if (Opcode != ISD::SIGN_EXTEND && Opcode != ISD::ZERO_EXTEND)
39354     return SDValue();
39355   if (!DCI.isBeforeLegalizeOps())
39356     return SDValue();
39357   if (!Subtarget.hasSSE2())
39358     return SDValue();
39359 
39360   SDValue N0 = N->getOperand(0);
39361   EVT VT = N->getValueType(0);
39362   EVT SVT = VT.getScalarType();
39363   EVT InVT = N0.getValueType();
39364   EVT InSVT = InVT.getScalarType();
39365 
39366   // FIXME: Generic DAGCombiner previously had a bug that would cause a
39367   // sign_extend of setcc to sometimes return the original node and tricked it
39368   // into thinking CombineTo was used which prevented the target combines from
39369   // running.
39370   // Earlying out here to avoid regressions like this
39371   //  (v4i32 (sext (v4i1 (setcc (v4i16)))))
39372   // Becomes
39373   //  (v4i32 (sext_invec (v8i16 (concat (v4i16 (setcc (v4i16))), undef))))
39374   // Type legalized to
39375   //  (v4i32 (sext_invec (v8i16 (trunc_invec (v4i32 (setcc (v4i32)))))))
39376   // Leading to a packssdw+pmovsxwd
39377   // We could write a DAG combine to fix this, but really we shouldn't be
39378   // creating sext_invec that's forcing v8i16 into the DAG.
39379   if (N0.getOpcode() == ISD::SETCC)
39380     return SDValue();
39381 
39382   // Input type must be a vector and we must be extending legal integer types.
39383   if (!VT.isVector() || VT.getVectorNumElements() < 2)
39384     return SDValue();
39385   if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16)
39386     return SDValue();
39387   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
39388     return SDValue();
39389 
39390   // If the input/output types are both legal then we have at least AVX1 and
39391   // we will be able to use SIGN_EXTEND/ZERO_EXTEND directly.
39392   if (DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
39393       DAG.getTargetLoweringInfo().isTypeLegal(InVT))
39394     return SDValue();
39395 
39396   SDLoc DL(N);
39397 
39398   auto ExtendVecSize = [&DAG](const SDLoc &DL, SDValue N, unsigned Size) {
39399     EVT InVT = N.getValueType();
39400     EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
39401                                  Size / InVT.getScalarSizeInBits());
39402     SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
39403                                   DAG.getUNDEF(InVT));
39404     Opnds[0] = N;
39405     return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
39406   };
39407 
39408   // If target-size is less than 128-bits, extend to a type that would extend
39409   // to 128 bits, extend that and extract the original target vector.
39410   if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits())) {
39411     unsigned Scale = 128 / VT.getSizeInBits();
39412     EVT ExVT =
39413         EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
39414     SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
39415     SDValue SExt = DAG.getNode(Opcode, DL, ExVT, Ex);
39416     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
39417                        DAG.getIntPtrConstant(0, DL));
39418   }
39419 
39420   // If target-size is 128-bits (or 256-bits on AVX target), then convert to
39421   // ISD::*_EXTEND_VECTOR_INREG which ensures lowering to X86ISD::V*EXT.
39422   // Also use this if we don't have SSE41 to allow the legalizer do its job.
39423   if (!Subtarget.hasSSE41() || VT.is128BitVector() ||
39424       (VT.is256BitVector() && Subtarget.hasAVX()) ||
39425       (VT.is512BitVector() && Subtarget.useAVX512Regs())) {
39426     SDValue ExOp = ExtendVecSize(DL, N0, VT.getSizeInBits());
39427     Opcode = Opcode == ISD::SIGN_EXTEND ? ISD::SIGN_EXTEND_VECTOR_INREG
39428                                         : ISD::ZERO_EXTEND_VECTOR_INREG;
39429     return DAG.getNode(Opcode, DL, VT, ExOp);
39430   }
39431 
39432   auto SplitAndExtendInReg = [&](unsigned SplitSize) {
39433     unsigned NumVecs = VT.getSizeInBits() / SplitSize;
39434     unsigned NumSubElts = SplitSize / SVT.getSizeInBits();
39435     EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
39436     EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
39437 
39438     unsigned IROpc = Opcode == ISD::SIGN_EXTEND ? ISD::SIGN_EXTEND_VECTOR_INREG
39439                                                 : ISD::ZERO_EXTEND_VECTOR_INREG;
39440 
39441     SmallVector<SDValue, 8> Opnds;
39442     for (unsigned i = 0, Offset = 0; i != NumVecs; ++i, Offset += NumSubElts) {
39443       SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
39444                                    DAG.getIntPtrConstant(Offset, DL));
39445       SrcVec = ExtendVecSize(DL, SrcVec, SplitSize);
39446       SrcVec = DAG.getNode(IROpc, DL, SubVT, SrcVec);
39447       Opnds.push_back(SrcVec);
39448     }
39449     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
39450   };
39451 
39452   // On pre-AVX targets, split into 128-bit nodes of
39453   // ISD::*_EXTEND_VECTOR_INREG.
39454   if (!Subtarget.hasAVX() && !(VT.getSizeInBits() % 128))
39455     return SplitAndExtendInReg(128);
39456 
39457   // On pre-AVX512 targets, split into 256-bit nodes of
39458   // ISD::*_EXTEND_VECTOR_INREG.
39459   if (!Subtarget.useAVX512Regs() && !(VT.getSizeInBits() % 256))
39460     return SplitAndExtendInReg(256);
39461 
39462   return SDValue();
39463 }
39464 
39465 // Attempt to combine a (sext/zext (setcc)) to a setcc with a xmm/ymm/zmm
39466 // result type.
combineExtSetcc(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)39467 static SDValue combineExtSetcc(SDNode *N, SelectionDAG &DAG,
39468                                const X86Subtarget &Subtarget) {
39469   SDValue N0 = N->getOperand(0);
39470   EVT VT = N->getValueType(0);
39471   SDLoc dl(N);
39472 
39473   // Only do this combine with AVX512 for vector extends.
39474   if (!Subtarget.hasAVX512() || !VT.isVector() || N0->getOpcode() != ISD::SETCC)
39475     return SDValue();
39476 
39477   // Only combine legal element types.
39478   EVT SVT = VT.getVectorElementType();
39479   if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32 &&
39480       SVT != MVT::i64 && SVT != MVT::f32 && SVT != MVT::f64)
39481     return SDValue();
39482 
39483   // We can only do this if the vector size in 256 bits or less.
39484   unsigned Size = VT.getSizeInBits();
39485   if (Size > 256)
39486     return SDValue();
39487 
39488   // Don't fold if the condition code can't be handled by PCMPEQ/PCMPGT since
39489   // that's the only integer compares with we have.
39490   ISD::CondCode CC = cast<CondCodeSDNode>(N0->getOperand(2))->get();
39491   if (ISD::isUnsignedIntSetCC(CC))
39492     return SDValue();
39493 
39494   // Only do this combine if the extension will be fully consumed by the setcc.
39495   EVT N00VT = N0.getOperand(0).getValueType();
39496   EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
39497   if (Size != MatchingVecType.getSizeInBits())
39498     return SDValue();
39499 
39500   SDValue Res = DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
39501 
39502   if (N->getOpcode() == ISD::ZERO_EXTEND)
39503     Res = DAG.getZeroExtendInReg(Res, dl, N0.getValueType().getScalarType());
39504 
39505   return Res;
39506 }
39507 
combineSext(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)39508 static SDValue combineSext(SDNode *N, SelectionDAG &DAG,
39509                            TargetLowering::DAGCombinerInfo &DCI,
39510                            const X86Subtarget &Subtarget) {
39511   SDValue N0 = N->getOperand(0);
39512   EVT VT = N->getValueType(0);
39513   EVT InVT = N0.getValueType();
39514   SDLoc DL(N);
39515 
39516   if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
39517     return NewCMov;
39518 
39519   if (!DCI.isBeforeLegalizeOps())
39520     return SDValue();
39521 
39522   if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
39523     return V;
39524 
39525   if (InVT == MVT::i1 && N0.getOpcode() == ISD::XOR &&
39526       isAllOnesConstant(N0.getOperand(1)) && N0.hasOneUse()) {
39527     // Invert and sign-extend a boolean is the same as zero-extend and subtract
39528     // 1 because 0 becomes -1 and 1 becomes 0. The subtract is efficiently
39529     // lowered with an LEA or a DEC. This is the same as: select Bool, 0, -1.
39530     // sext (xor Bool, -1) --> sub (zext Bool), 1
39531     SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
39532     return DAG.getNode(ISD::SUB, DL, VT, Zext, DAG.getConstant(1, DL, VT));
39533   }
39534 
39535   if (SDValue V = combineToExtendVectorInReg(N, DAG, DCI, Subtarget))
39536     return V;
39537 
39538   if (SDValue V = combineToExtendBoolVectorInReg(N, DAG, DCI, Subtarget))
39539     return V;
39540 
39541   if (VT.isVector())
39542     if (SDValue R = PromoteMaskArithmetic(N, DAG, Subtarget))
39543       return R;
39544 
39545   if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
39546     return NewAdd;
39547 
39548   return SDValue();
39549 }
39550 
negateFMAOpcode(unsigned Opcode,bool NegMul,bool NegAcc)39551 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc) {
39552   if (NegMul) {
39553     switch (Opcode) {
39554     default: llvm_unreachable("Unexpected opcode");
39555     case ISD::FMA:             Opcode = X86ISD::FNMADD;       break;
39556     case X86ISD::FMADD_RND:    Opcode = X86ISD::FNMADD_RND;   break;
39557     case X86ISD::FMSUB:        Opcode = X86ISD::FNMSUB;       break;
39558     case X86ISD::FMSUB_RND:    Opcode = X86ISD::FNMSUB_RND;   break;
39559     case X86ISD::FNMADD:       Opcode = ISD::FMA;             break;
39560     case X86ISD::FNMADD_RND:   Opcode = X86ISD::FMADD_RND;    break;
39561     case X86ISD::FNMSUB:       Opcode = X86ISD::FMSUB;        break;
39562     case X86ISD::FNMSUB_RND:   Opcode = X86ISD::FMSUB_RND;    break;
39563     }
39564   }
39565 
39566   if (NegAcc) {
39567     switch (Opcode) {
39568     default: llvm_unreachable("Unexpected opcode");
39569     case ISD::FMA:             Opcode = X86ISD::FMSUB;        break;
39570     case X86ISD::FMADD_RND:    Opcode = X86ISD::FMSUB_RND;    break;
39571     case X86ISD::FMSUB:        Opcode = ISD::FMA;             break;
39572     case X86ISD::FMSUB_RND:    Opcode = X86ISD::FMADD_RND;    break;
39573     case X86ISD::FNMADD:       Opcode = X86ISD::FNMSUB;       break;
39574     case X86ISD::FNMADD_RND:   Opcode = X86ISD::FNMSUB_RND;   break;
39575     case X86ISD::FNMSUB:       Opcode = X86ISD::FNMADD;       break;
39576     case X86ISD::FNMSUB_RND:   Opcode = X86ISD::FNMADD_RND;   break;
39577     }
39578   }
39579 
39580   return Opcode;
39581 }
39582 
combineFMA(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)39583 static SDValue combineFMA(SDNode *N, SelectionDAG &DAG,
39584                           const X86Subtarget &Subtarget) {
39585   SDLoc dl(N);
39586   EVT VT = N->getValueType(0);
39587 
39588   // Let legalize expand this if it isn't a legal type yet.
39589   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
39590     return SDValue();
39591 
39592   EVT ScalarVT = VT.getScalarType();
39593   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget.hasAnyFMA())
39594     return SDValue();
39595 
39596   SDValue A = N->getOperand(0);
39597   SDValue B = N->getOperand(1);
39598   SDValue C = N->getOperand(2);
39599 
39600   auto invertIfNegative = [&DAG](SDValue &V) {
39601     if (SDValue NegVal = isFNEG(DAG, V.getNode())) {
39602       V = DAG.getBitcast(V.getValueType(), NegVal);
39603       return true;
39604     }
39605     // Look through extract_vector_elts. If it comes from an FNEG, create a
39606     // new extract from the FNEG input.
39607     if (V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
39608         isNullConstant(V.getOperand(1))) {
39609       if (SDValue NegVal = isFNEG(DAG, V.getOperand(0).getNode())) {
39610         NegVal = DAG.getBitcast(V.getOperand(0).getValueType(), NegVal);
39611         V = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), V.getValueType(),
39612                         NegVal, V.getOperand(1));
39613         return true;
39614       }
39615     }
39616 
39617     return false;
39618   };
39619 
39620   // Do not convert the passthru input of scalar intrinsics.
39621   // FIXME: We could allow negations of the lower element only.
39622   bool NegA = invertIfNegative(A);
39623   bool NegB = invertIfNegative(B);
39624   bool NegC = invertIfNegative(C);
39625 
39626   if (!NegA && !NegB && !NegC)
39627     return SDValue();
39628 
39629   unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC);
39630 
39631   if (N->getNumOperands() == 4)
39632     return DAG.getNode(NewOpcode, dl, VT, A, B, C, N->getOperand(3));
39633   return DAG.getNode(NewOpcode, dl, VT, A, B, C);
39634 }
39635 
39636 // Combine FMADDSUB(A, B, FNEG(C)) -> FMSUBADD(A, B, C)
combineFMADDSUB(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)39637 static SDValue combineFMADDSUB(SDNode *N, SelectionDAG &DAG,
39638                                const X86Subtarget &Subtarget) {
39639   SDLoc dl(N);
39640   EVT VT = N->getValueType(0);
39641 
39642   SDValue NegVal = isFNEG(DAG, N->getOperand(2).getNode());
39643   if (!NegVal)
39644     return SDValue();
39645 
39646   unsigned NewOpcode;
39647   switch (N->getOpcode()) {
39648   default: llvm_unreachable("Unexpected opcode!");
39649   case X86ISD::FMADDSUB:     NewOpcode = X86ISD::FMSUBADD;     break;
39650   case X86ISD::FMADDSUB_RND: NewOpcode = X86ISD::FMSUBADD_RND; break;
39651   case X86ISD::FMSUBADD:     NewOpcode = X86ISD::FMADDSUB;     break;
39652   case X86ISD::FMSUBADD_RND: NewOpcode = X86ISD::FMADDSUB_RND; break;
39653   }
39654 
39655   if (N->getNumOperands() == 4)
39656     return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
39657                        NegVal, N->getOperand(3));
39658   return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
39659                      NegVal);
39660 }
39661 
combineZext(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)39662 static SDValue combineZext(SDNode *N, SelectionDAG &DAG,
39663                            TargetLowering::DAGCombinerInfo &DCI,
39664                            const X86Subtarget &Subtarget) {
39665   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
39666   //           (and (i32 x86isd::setcc_carry), 1)
39667   // This eliminates the zext. This transformation is necessary because
39668   // ISD::SETCC is always legalized to i8.
39669   SDLoc dl(N);
39670   SDValue N0 = N->getOperand(0);
39671   EVT VT = N->getValueType(0);
39672 
39673   if (N0.getOpcode() == ISD::AND &&
39674       N0.hasOneUse() &&
39675       N0.getOperand(0).hasOneUse()) {
39676     SDValue N00 = N0.getOperand(0);
39677     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
39678       if (!isOneConstant(N0.getOperand(1)))
39679         return SDValue();
39680       return DAG.getNode(ISD::AND, dl, VT,
39681                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
39682                                      N00.getOperand(0), N00.getOperand(1)),
39683                          DAG.getConstant(1, dl, VT));
39684     }
39685   }
39686 
39687   if (N0.getOpcode() == ISD::TRUNCATE &&
39688       N0.hasOneUse() &&
39689       N0.getOperand(0).hasOneUse()) {
39690     SDValue N00 = N0.getOperand(0);
39691     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
39692       return DAG.getNode(ISD::AND, dl, VT,
39693                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
39694                                      N00.getOperand(0), N00.getOperand(1)),
39695                          DAG.getConstant(1, dl, VT));
39696     }
39697   }
39698 
39699   if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
39700     return NewCMov;
39701 
39702   if (DCI.isBeforeLegalizeOps())
39703     if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
39704       return V;
39705 
39706   if (SDValue V = combineToExtendVectorInReg(N, DAG, DCI, Subtarget))
39707     return V;
39708 
39709   if (SDValue V = combineToExtendBoolVectorInReg(N, DAG, DCI, Subtarget))
39710     return V;
39711 
39712   if (VT.isVector())
39713     if (SDValue R = PromoteMaskArithmetic(N, DAG, Subtarget))
39714       return R;
39715 
39716   if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
39717     return NewAdd;
39718 
39719   if (SDValue R = combineOrCmpEqZeroToCtlzSrl(N, DAG, DCI, Subtarget))
39720     return R;
39721 
39722   return SDValue();
39723 }
39724 
39725 /// Try to map a 128-bit or larger integer comparison to vector instructions
39726 /// before type legalization splits it up into chunks.
combineVectorSizedSetCCEquality(SDNode * SetCC,SelectionDAG & DAG,const X86Subtarget & Subtarget)39727 static SDValue combineVectorSizedSetCCEquality(SDNode *SetCC, SelectionDAG &DAG,
39728                                                const X86Subtarget &Subtarget) {
39729   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
39730   assert((CC == ISD::SETNE || CC == ISD::SETEQ) && "Bad comparison predicate");
39731 
39732   // We're looking for an oversized integer equality comparison.
39733   SDValue X = SetCC->getOperand(0);
39734   SDValue Y = SetCC->getOperand(1);
39735   EVT OpVT = X.getValueType();
39736   unsigned OpSize = OpVT.getSizeInBits();
39737   if (!OpVT.isScalarInteger() || OpSize < 128)
39738     return SDValue();
39739 
39740   // Ignore a comparison with zero because that gets special treatment in
39741   // EmitTest(). But make an exception for the special case of a pair of
39742   // logically-combined vector-sized operands compared to zero. This pattern may
39743   // be generated by the memcmp expansion pass with oversized integer compares
39744   // (see PR33325).
39745   bool IsOrXorXorCCZero = isNullConstant(Y) && X.getOpcode() == ISD::OR &&
39746                           X.getOperand(0).getOpcode() == ISD::XOR &&
39747                           X.getOperand(1).getOpcode() == ISD::XOR;
39748   if (isNullConstant(Y) && !IsOrXorXorCCZero)
39749     return SDValue();
39750 
39751   // Bail out if we know that this is not really just an oversized integer.
39752   if (peekThroughBitcasts(X).getValueType() == MVT::f128 ||
39753       peekThroughBitcasts(Y).getValueType() == MVT::f128)
39754     return SDValue();
39755 
39756   // TODO: Use PXOR + PTEST for SSE4.1 or later?
39757   EVT VT = SetCC->getValueType(0);
39758   SDLoc DL(SetCC);
39759   if ((OpSize == 128 && Subtarget.hasSSE2()) ||
39760       (OpSize == 256 && Subtarget.hasAVX2()) ||
39761       (OpSize == 512 && Subtarget.useAVX512Regs())) {
39762     EVT VecVT = OpSize == 512 ? MVT::v16i32 :
39763                 OpSize == 256 ? MVT::v32i8 :
39764                                 MVT::v16i8;
39765     EVT CmpVT = OpSize == 512 ? MVT::v16i1 : VecVT;
39766     SDValue Cmp;
39767     if (IsOrXorXorCCZero) {
39768       // This is a bitwise-combined equality comparison of 2 pairs of vectors:
39769       // setcc i128 (or (xor A, B), (xor C, D)), 0, eq|ne
39770       // Use 2 vector equality compares and 'and' the results before doing a
39771       // MOVMSK.
39772       SDValue A = DAG.getBitcast(VecVT, X.getOperand(0).getOperand(0));
39773       SDValue B = DAG.getBitcast(VecVT, X.getOperand(0).getOperand(1));
39774       SDValue C = DAG.getBitcast(VecVT, X.getOperand(1).getOperand(0));
39775       SDValue D = DAG.getBitcast(VecVT, X.getOperand(1).getOperand(1));
39776       SDValue Cmp1 = DAG.getSetCC(DL, CmpVT, A, B, ISD::SETEQ);
39777       SDValue Cmp2 = DAG.getSetCC(DL, CmpVT, C, D, ISD::SETEQ);
39778       Cmp = DAG.getNode(ISD::AND, DL, CmpVT, Cmp1, Cmp2);
39779     } else {
39780       SDValue VecX = DAG.getBitcast(VecVT, X);
39781       SDValue VecY = DAG.getBitcast(VecVT, Y);
39782       Cmp = DAG.getSetCC(DL, CmpVT, VecX, VecY, ISD::SETEQ);
39783     }
39784     // For 512-bits we want to emit a setcc that will lower to kortest.
39785     if (OpSize == 512)
39786       return DAG.getSetCC(DL, VT, DAG.getBitcast(MVT::i16, Cmp),
39787                           DAG.getConstant(0xFFFF, DL, MVT::i16), CC);
39788     // If all bytes match (bitmask is 0x(FFFF)FFFF), that's equality.
39789     // setcc i128 X, Y, eq --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, eq
39790     // setcc i128 X, Y, ne --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, ne
39791     // setcc i256 X, Y, eq --> setcc (vpmovmskb (vpcmpeqb X, Y)), 0xFFFFFFFF, eq
39792     // setcc i256 X, Y, ne --> setcc (vpmovmskb (vpcmpeqb X, Y)), 0xFFFFFFFF, ne
39793     SDValue MovMsk = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Cmp);
39794     SDValue FFFFs = DAG.getConstant(OpSize == 128 ? 0xFFFF : 0xFFFFFFFF, DL,
39795                                     MVT::i32);
39796     return DAG.getSetCC(DL, VT, MovMsk, FFFFs, CC);
39797   }
39798 
39799   return SDValue();
39800 }
39801 
combineSetCC(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)39802 static SDValue combineSetCC(SDNode *N, SelectionDAG &DAG,
39803                             const X86Subtarget &Subtarget) {
39804   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
39805   SDValue LHS = N->getOperand(0);
39806   SDValue RHS = N->getOperand(1);
39807   EVT VT = N->getValueType(0);
39808   EVT OpVT = LHS.getValueType();
39809   SDLoc DL(N);
39810 
39811   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
39812     // 0-x == y --> x+y == 0
39813     // 0-x != y --> x+y != 0
39814     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
39815         LHS.hasOneUse()) {
39816       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, RHS, LHS.getOperand(1));
39817       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
39818     }
39819     // x == 0-y --> x+y == 0
39820     // x != 0-y --> x+y != 0
39821     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
39822         RHS.hasOneUse()) {
39823       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
39824       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
39825     }
39826 
39827     if (SDValue V = combineVectorSizedSetCCEquality(N, DAG, Subtarget))
39828       return V;
39829   }
39830 
39831   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
39832       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
39833     // Put build_vectors on the right.
39834     if (LHS.getOpcode() == ISD::BUILD_VECTOR) {
39835       std::swap(LHS, RHS);
39836       CC = ISD::getSetCCSwappedOperands(CC);
39837     }
39838 
39839     bool IsSEXT0 =
39840         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
39841         (LHS.getOperand(0).getValueType().getVectorElementType() == MVT::i1);
39842     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
39843 
39844     if (IsSEXT0 && IsVZero1) {
39845       assert(VT == LHS.getOperand(0).getValueType() &&
39846              "Uexpected operand type");
39847       if (CC == ISD::SETGT)
39848         return DAG.getConstant(0, DL, VT);
39849       if (CC == ISD::SETLE)
39850         return DAG.getConstant(1, DL, VT);
39851       if (CC == ISD::SETEQ || CC == ISD::SETGE)
39852         return DAG.getNOT(DL, LHS.getOperand(0), VT);
39853 
39854       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
39855              "Unexpected condition code!");
39856       return LHS.getOperand(0);
39857     }
39858   }
39859 
39860   // If we have AVX512, but not BWI and this is a vXi16/vXi8 setcc, just
39861   // pre-promote its result type since vXi1 vectors don't get promoted
39862   // during type legalization.
39863   // NOTE: The element count check is to ignore operand types that need to
39864   // go through type promotion to a 128-bit vector.
39865   if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && VT.isVector() &&
39866       VT.getVectorElementType() == MVT::i1 &&
39867       (ExperimentalVectorWideningLegalization ||
39868        VT.getVectorNumElements() > 4) &&
39869       (OpVT.getVectorElementType() == MVT::i8 ||
39870        OpVT.getVectorElementType() == MVT::i16)) {
39871     SDValue Setcc = DAG.getNode(ISD::SETCC, DL, OpVT, LHS, RHS,
39872                                 N->getOperand(2));
39873     return DAG.getNode(ISD::TRUNCATE, DL, VT, Setcc);
39874   }
39875 
39876   // For an SSE1-only target, lower a comparison of v4f32 to X86ISD::CMPP early
39877   // to avoid scalarization via legalization because v4i32 is not a legal type.
39878   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32 &&
39879       LHS.getValueType() == MVT::v4f32)
39880     return LowerVSETCC(SDValue(N, 0), Subtarget, DAG);
39881 
39882   return SDValue();
39883 }
39884 
combineMOVMSK(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)39885 static SDValue combineMOVMSK(SDNode *N, SelectionDAG &DAG,
39886                              TargetLowering::DAGCombinerInfo &DCI) {
39887   SDValue Src = N->getOperand(0);
39888   MVT SrcVT = Src.getSimpleValueType();
39889   MVT VT = N->getSimpleValueType(0);
39890 
39891   // Perform constant folding.
39892   if (ISD::isBuildVectorOfConstantSDNodes(Src.getNode())) {
39893     assert(VT== MVT::i32 && "Unexpected result type");
39894     APInt Imm(32, 0);
39895     for (unsigned Idx = 0, e = Src.getNumOperands(); Idx < e; ++Idx) {
39896       SDValue In = Src.getOperand(Idx);
39897       if (!In.isUndef() &&
39898           cast<ConstantSDNode>(In)->getAPIntValue().isNegative())
39899         Imm.setBit(Idx);
39900     }
39901     return DAG.getConstant(Imm, SDLoc(N), VT);
39902   }
39903 
39904   // Look through int->fp bitcasts that don't change the element width.
39905   if (Src.getOpcode() == ISD::BITCAST && Src.hasOneUse() &&
39906       SrcVT.isFloatingPoint() &&
39907       Src.getOperand(0).getValueType() ==
39908         EVT(SrcVT).changeVectorElementTypeToInteger())
39909     Src = Src.getOperand(0);
39910 
39911   // Simplify the inputs.
39912   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39913   APInt DemandedMask(APInt::getAllOnesValue(VT.getScalarSizeInBits()));
39914   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
39915     return SDValue(N, 0);
39916 
39917   // Combine (movmsk (setne (and X, (1 << C)), 0)) -> (movmsk (X << C)).
39918   // Only do this when the setcc input and output types are the same and the
39919   // setcc and the 'and' node have a single use.
39920   // FIXME: Support 256-bits with AVX1. The movmsk is split, but the and isn't.
39921   APInt SplatVal;
39922   if (Src.getOpcode() == ISD::SETCC && Src.hasOneUse() &&
39923       Src.getOperand(0).getValueType() == Src.getValueType() &&
39924       cast<CondCodeSDNode>(Src.getOperand(2))->get() == ISD::SETNE &&
39925       ISD::isBuildVectorAllZeros(Src.getOperand(1).getNode()) &&
39926       Src.getOperand(0).getOpcode() == ISD::AND) {
39927     SDValue And = Src.getOperand(0);
39928     if (And.hasOneUse() &&
39929         ISD::isConstantSplatVector(And.getOperand(1).getNode(), SplatVal) &&
39930         SplatVal.isPowerOf2()) {
39931       MVT VT = Src.getSimpleValueType();
39932       unsigned BitWidth = VT.getScalarSizeInBits();
39933       unsigned ShAmt = BitWidth - SplatVal.logBase2() - 1;
39934       SDLoc DL(And);
39935       SDValue X = And.getOperand(0);
39936       // If the element type is i8, we need to bitcast to i16 to use a legal
39937       // shift. If we wait until lowering we end up with an extra and to bits
39938       // from crossing the 8-bit elements, but we don't care about that here.
39939       if (VT.getVectorElementType() == MVT::i8) {
39940         VT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
39941         X = DAG.getBitcast(VT, X);
39942       }
39943       SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, X,
39944                                 DAG.getConstant(ShAmt, DL, VT));
39945       SDValue Cast = DAG.getBitcast(SrcVT, Shl);
39946       return DAG.getNode(X86ISD::MOVMSK, SDLoc(N), N->getValueType(0), Cast);
39947     }
39948   }
39949 
39950   return SDValue();
39951 }
39952 
combineGatherScatter(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)39953 static SDValue combineGatherScatter(SDNode *N, SelectionDAG &DAG,
39954                                     TargetLowering::DAGCombinerInfo &DCI,
39955                                     const X86Subtarget &Subtarget) {
39956   SDLoc DL(N);
39957 
39958   if (DCI.isBeforeLegalizeOps()) {
39959     SDValue Index = N->getOperand(4);
39960     // Remove any sign extends from 32 or smaller to larger than 32.
39961     // Only do this before LegalizeOps in case we need the sign extend for
39962     // legalization.
39963     if (Index.getOpcode() == ISD::SIGN_EXTEND) {
39964       if (Index.getScalarValueSizeInBits() > 32 &&
39965           Index.getOperand(0).getScalarValueSizeInBits() <= 32) {
39966         SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
39967         NewOps[4] = Index.getOperand(0);
39968         SDNode *Res = DAG.UpdateNodeOperands(N, NewOps);
39969         if (Res == N) {
39970           // The original sign extend has less users, add back to worklist in
39971           // case it needs to be removed
39972           DCI.AddToWorklist(Index.getNode());
39973           DCI.AddToWorklist(N);
39974         }
39975         return SDValue(Res, 0);
39976       }
39977     }
39978 
39979     // Make sure the index is either i32 or i64
39980     unsigned ScalarSize = Index.getScalarValueSizeInBits();
39981     if (ScalarSize != 32 && ScalarSize != 64) {
39982       MVT EltVT = ScalarSize > 32 ? MVT::i64 : MVT::i32;
39983       EVT IndexVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
39984                                    Index.getValueType().getVectorNumElements());
39985       Index = DAG.getSExtOrTrunc(Index, DL, IndexVT);
39986       SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
39987       NewOps[4] = Index;
39988       SDNode *Res = DAG.UpdateNodeOperands(N, NewOps);
39989       if (Res == N)
39990         DCI.AddToWorklist(N);
39991       return SDValue(Res, 0);
39992     }
39993 
39994     // Try to remove zero extends from 32->64 if we know the sign bit of
39995     // the input is zero.
39996     if (Index.getOpcode() == ISD::ZERO_EXTEND &&
39997         Index.getScalarValueSizeInBits() == 64 &&
39998         Index.getOperand(0).getScalarValueSizeInBits() == 32) {
39999       if (DAG.SignBitIsZero(Index.getOperand(0))) {
40000         SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
40001         NewOps[4] = Index.getOperand(0);
40002         SDNode *Res = DAG.UpdateNodeOperands(N, NewOps);
40003         if (Res == N) {
40004           // The original sign extend has less users, add back to worklist in
40005           // case it needs to be removed
40006           DCI.AddToWorklist(Index.getNode());
40007           DCI.AddToWorklist(N);
40008         }
40009         return SDValue(Res, 0);
40010       }
40011     }
40012   }
40013 
40014   // With AVX2 we only demand the upper bit of the mask.
40015   if (!Subtarget.hasAVX512()) {
40016     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40017     SDValue Mask = N->getOperand(2);
40018     APInt DemandedMask(APInt::getSignMask(Mask.getScalarValueSizeInBits()));
40019     if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI))
40020       return SDValue(N, 0);
40021   }
40022 
40023   return SDValue();
40024 }
40025 
40026 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
combineX86SetCC(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)40027 static SDValue combineX86SetCC(SDNode *N, SelectionDAG &DAG,
40028                                const X86Subtarget &Subtarget) {
40029   SDLoc DL(N);
40030   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
40031   SDValue EFLAGS = N->getOperand(1);
40032 
40033   // Try to simplify the EFLAGS and condition code operands.
40034   if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget))
40035     return getSETCC(CC, Flags, DL, DAG);
40036 
40037   return SDValue();
40038 }
40039 
40040 /// Optimize branch condition evaluation.
combineBrCond(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)40041 static SDValue combineBrCond(SDNode *N, SelectionDAG &DAG,
40042                              const X86Subtarget &Subtarget) {
40043   SDLoc DL(N);
40044   SDValue EFLAGS = N->getOperand(3);
40045   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
40046 
40047   // Try to simplify the EFLAGS and condition code operands.
40048   // Make sure to not keep references to operands, as combineSetCCEFLAGS can
40049   // RAUW them under us.
40050   if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget)) {
40051     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
40052     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), N->getOperand(0),
40053                        N->getOperand(1), Cond, Flags);
40054   }
40055 
40056   return SDValue();
40057 }
40058 
combineVectorCompareAndMaskUnaryOp(SDNode * N,SelectionDAG & DAG)40059 static SDValue combineVectorCompareAndMaskUnaryOp(SDNode *N,
40060                                                   SelectionDAG &DAG) {
40061   // Take advantage of vector comparisons producing 0 or -1 in each lane to
40062   // optimize away operation when it's from a constant.
40063   //
40064   // The general transformation is:
40065   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
40066   //       AND(VECTOR_CMP(x,y), constant2)
40067   //    constant2 = UNARYOP(constant)
40068 
40069   // Early exit if this isn't a vector operation, the operand of the
40070   // unary operation isn't a bitwise AND, or if the sizes of the operations
40071   // aren't the same.
40072   EVT VT = N->getValueType(0);
40073   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
40074       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
40075       VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
40076     return SDValue();
40077 
40078   // Now check that the other operand of the AND is a constant. We could
40079   // make the transformation for non-constant splats as well, but it's unclear
40080   // that would be a benefit as it would not eliminate any operations, just
40081   // perform one more step in scalar code before moving to the vector unit.
40082   if (BuildVectorSDNode *BV =
40083           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
40084     // Bail out if the vector isn't a constant.
40085     if (!BV->isConstant())
40086       return SDValue();
40087 
40088     // Everything checks out. Build up the new and improved node.
40089     SDLoc DL(N);
40090     EVT IntVT = BV->getValueType(0);
40091     // Create a new constant of the appropriate type for the transformed
40092     // DAG.
40093     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
40094     // The AND node needs bitcasts to/from an integer vector type around it.
40095     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
40096     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
40097                                  N->getOperand(0)->getOperand(0), MaskConst);
40098     SDValue Res = DAG.getBitcast(VT, NewAnd);
40099     return Res;
40100   }
40101 
40102   return SDValue();
40103 }
40104 
combineUIntToFP(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)40105 static SDValue combineUIntToFP(SDNode *N, SelectionDAG &DAG,
40106                                const X86Subtarget &Subtarget) {
40107   SDValue Op0 = N->getOperand(0);
40108   EVT VT = N->getValueType(0);
40109   EVT InVT = Op0.getValueType();
40110 
40111   // UINT_TO_FP(vXi1) -> SINT_TO_FP(ZEXT(vXi1 to vXi32))
40112   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
40113   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
40114   if (InVT.isVector() && InVT.getScalarSizeInBits() < 32) {
40115     SDLoc dl(N);
40116     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
40117                                  InVT.getVectorNumElements());
40118     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
40119 
40120     // UINT_TO_FP isn't legal without AVX512 so use SINT_TO_FP.
40121     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
40122   }
40123 
40124   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
40125   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
40126   // the optimization here.
40127   if (DAG.SignBitIsZero(Op0))
40128     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, Op0);
40129 
40130   return SDValue();
40131 }
40132 
combineSIntToFP(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)40133 static SDValue combineSIntToFP(SDNode *N, SelectionDAG &DAG,
40134                                const X86Subtarget &Subtarget) {
40135   // First try to optimize away the conversion entirely when it's
40136   // conditionally from a constant. Vectors only.
40137   if (SDValue Res = combineVectorCompareAndMaskUnaryOp(N, DAG))
40138     return Res;
40139 
40140   // Now move on to more general possibilities.
40141   SDValue Op0 = N->getOperand(0);
40142   EVT VT = N->getValueType(0);
40143   EVT InVT = Op0.getValueType();
40144 
40145   // SINT_TO_FP(vXi1) -> SINT_TO_FP(SEXT(vXi1 to vXi32))
40146   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
40147   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
40148   if (InVT.isVector() && InVT.getScalarSizeInBits() < 32) {
40149     SDLoc dl(N);
40150     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
40151                                  InVT.getVectorNumElements());
40152     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
40153     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
40154   }
40155 
40156   // Without AVX512DQ we only support i64 to float scalar conversion. For both
40157   // vectors and scalars, see if we know that the upper bits are all the sign
40158   // bit, in which case we can truncate the input to i32 and convert from that.
40159   if (InVT.getScalarSizeInBits() > 32 && !Subtarget.hasDQI()) {
40160     unsigned BitWidth = InVT.getScalarSizeInBits();
40161     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0);
40162     if (NumSignBits >= (BitWidth - 31)) {
40163       EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), 32);
40164       if (InVT.isVector())
40165         TruncVT = EVT::getVectorVT(*DAG.getContext(), TruncVT,
40166                                    InVT.getVectorNumElements());
40167       SDLoc dl(N);
40168       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Op0);
40169       return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Trunc);
40170     }
40171   }
40172 
40173   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
40174   // a 32-bit target where SSE doesn't support i64->FP operations.
40175   if (!Subtarget.useSoftFloat() && Subtarget.hasX87() &&
40176       Op0.getOpcode() == ISD::LOAD) {
40177     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
40178     EVT LdVT = Ld->getValueType(0);
40179 
40180     // This transformation is not supported if the result type is f16 or f128.
40181     if (VT == MVT::f16 || VT == MVT::f128)
40182       return SDValue();
40183 
40184     // If we have AVX512DQ we can use packed conversion instructions unless
40185     // the VT is f80.
40186     if (Subtarget.hasDQI() && VT != MVT::f80)
40187       return SDValue();
40188 
40189     if (!Ld->isVolatile() && !VT.isVector() &&
40190         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
40191         !Subtarget.is64Bit() && LdVT == MVT::i64) {
40192       SDValue FILDChain = Subtarget.getTargetLowering()->BuildFILD(
40193           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
40194       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
40195       return FILDChain;
40196     }
40197   }
40198   return SDValue();
40199 }
40200 
needCarryOrOverflowFlag(SDValue Flags)40201 static bool needCarryOrOverflowFlag(SDValue Flags) {
40202   assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!");
40203 
40204   for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
40205          UI != UE; ++UI) {
40206     SDNode *User = *UI;
40207 
40208     X86::CondCode CC;
40209     switch (User->getOpcode()) {
40210     default:
40211       // Be conservative.
40212       return true;
40213     case X86ISD::SETCC:
40214     case X86ISD::SETCC_CARRY:
40215       CC = (X86::CondCode)User->getConstantOperandVal(0);
40216       break;
40217     case X86ISD::BRCOND:
40218       CC = (X86::CondCode)User->getConstantOperandVal(2);
40219       break;
40220     case X86ISD::CMOV:
40221       CC = (X86::CondCode)User->getConstantOperandVal(2);
40222       break;
40223     }
40224 
40225     switch (CC) {
40226     default: break;
40227     case X86::COND_A: case X86::COND_AE:
40228     case X86::COND_B: case X86::COND_BE:
40229     case X86::COND_O: case X86::COND_NO:
40230     case X86::COND_G: case X86::COND_GE:
40231     case X86::COND_L: case X86::COND_LE:
40232       return true;
40233     }
40234   }
40235 
40236   return false;
40237 }
40238 
onlyZeroFlagUsed(SDValue Flags)40239 static bool onlyZeroFlagUsed(SDValue Flags) {
40240   assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!");
40241 
40242   for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
40243          UI != UE; ++UI) {
40244     SDNode *User = *UI;
40245 
40246     unsigned CCOpNo;
40247     switch (User->getOpcode()) {
40248     default:
40249       // Be conservative.
40250       return false;
40251     case X86ISD::SETCC:       CCOpNo = 0; break;
40252     case X86ISD::SETCC_CARRY: CCOpNo = 0; break;
40253     case X86ISD::BRCOND:      CCOpNo = 2; break;
40254     case X86ISD::CMOV:        CCOpNo = 2; break;
40255     }
40256 
40257     X86::CondCode CC = (X86::CondCode)User->getConstantOperandVal(CCOpNo);
40258     if (CC != X86::COND_E && CC != X86::COND_NE)
40259       return false;
40260   }
40261 
40262   return true;
40263 }
40264 
combineCMP(SDNode * N,SelectionDAG & DAG)40265 static SDValue combineCMP(SDNode *N, SelectionDAG &DAG) {
40266   // Only handle test patterns.
40267   if (!isNullConstant(N->getOperand(1)))
40268     return SDValue();
40269 
40270   // If we have a CMP of a truncated binop, see if we can make a smaller binop
40271   // and use its flags directly.
40272   // TODO: Maybe we should try promoting compares that only use the zero flag
40273   // first if we can prove the upper bits with computeKnownBits?
40274   SDLoc dl(N);
40275   SDValue Op = N->getOperand(0);
40276   EVT VT = Op.getValueType();
40277 
40278   // If we have a constant logical shift that's only used in a comparison
40279   // against zero turn it into an equivalent AND. This allows turning it into
40280   // a TEST instruction later.
40281   if ((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) &&
40282       Op.hasOneUse() && isa<ConstantSDNode>(Op.getOperand(1)) &&
40283       onlyZeroFlagUsed(SDValue(N, 0))) {
40284     EVT VT = Op.getValueType();
40285     unsigned BitWidth = VT.getSizeInBits();
40286     unsigned ShAmt = Op.getConstantOperandVal(1);
40287     if (ShAmt < BitWidth) { // Avoid undefined shifts.
40288       APInt Mask = Op.getOpcode() == ISD::SRL
40289                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
40290                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
40291       if (Mask.isSignedIntN(32)) {
40292         Op = DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0),
40293                          DAG.getConstant(Mask, dl, VT));
40294         return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
40295                            DAG.getConstant(0, dl, VT));
40296       }
40297     }
40298   }
40299 
40300 
40301   // Look for a truncate with a single use.
40302   if (Op.getOpcode() != ISD::TRUNCATE || !Op.hasOneUse())
40303     return SDValue();
40304 
40305   Op = Op.getOperand(0);
40306 
40307   // Arithmetic op can only have one use.
40308   if (!Op.hasOneUse())
40309     return SDValue();
40310 
40311   unsigned NewOpc;
40312   switch (Op.getOpcode()) {
40313   default: return SDValue();
40314   case ISD::AND:
40315     // Skip and with constant. We have special handling for and with immediate
40316     // during isel to generate test instructions.
40317     if (isa<ConstantSDNode>(Op.getOperand(1)))
40318       return SDValue();
40319     NewOpc = X86ISD::AND;
40320     break;
40321   case ISD::OR:  NewOpc = X86ISD::OR;  break;
40322   case ISD::XOR: NewOpc = X86ISD::XOR; break;
40323   case ISD::ADD:
40324     // If the carry or overflow flag is used, we can't truncate.
40325     if (needCarryOrOverflowFlag(SDValue(N, 0)))
40326       return SDValue();
40327     NewOpc = X86ISD::ADD;
40328     break;
40329   case ISD::SUB:
40330     // If the carry or overflow flag is used, we can't truncate.
40331     if (needCarryOrOverflowFlag(SDValue(N, 0)))
40332       return SDValue();
40333     NewOpc = X86ISD::SUB;
40334     break;
40335   }
40336 
40337   // We found an op we can narrow. Truncate its inputs.
40338   SDValue Op0 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(0));
40339   SDValue Op1 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(1));
40340 
40341   // Use a X86 specific opcode to avoid DAG combine messing with it.
40342   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
40343   Op = DAG.getNode(NewOpc, dl, VTs, Op0, Op1);
40344 
40345   // For AND, keep a CMP so that we can match the test pattern.
40346   if (NewOpc == X86ISD::AND)
40347     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
40348                        DAG.getConstant(0, dl, VT));
40349 
40350   // Return the flags.
40351   return Op.getValue(1);
40352 }
40353 
combineSBB(SDNode * N,SelectionDAG & DAG)40354 static SDValue combineSBB(SDNode *N, SelectionDAG &DAG) {
40355   if (SDValue Flags = combineCarryThroughADD(N->getOperand(2))) {
40356     MVT VT = N->getSimpleValueType(0);
40357     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
40358     return DAG.getNode(X86ISD::SBB, SDLoc(N), VTs,
40359                        N->getOperand(0), N->getOperand(1),
40360                        Flags);
40361   }
40362 
40363   return SDValue();
40364 }
40365 
40366 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
combineADC(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)40367 static SDValue combineADC(SDNode *N, SelectionDAG &DAG,
40368                           TargetLowering::DAGCombinerInfo &DCI) {
40369   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
40370   // the result is either zero or one (depending on the input carry bit).
40371   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
40372   if (X86::isZeroNode(N->getOperand(0)) &&
40373       X86::isZeroNode(N->getOperand(1)) &&
40374       // We don't have a good way to replace an EFLAGS use, so only do this when
40375       // dead right now.
40376       SDValue(N, 1).use_empty()) {
40377     SDLoc DL(N);
40378     EVT VT = N->getValueType(0);
40379     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
40380     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
40381                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
40382                                            DAG.getConstant(X86::COND_B, DL,
40383                                                            MVT::i8),
40384                                            N->getOperand(2)),
40385                                DAG.getConstant(1, DL, VT));
40386     return DCI.CombineTo(N, Res1, CarryOut);
40387   }
40388 
40389   if (SDValue Flags = combineCarryThroughADD(N->getOperand(2))) {
40390     MVT VT = N->getSimpleValueType(0);
40391     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
40392     return DAG.getNode(X86ISD::ADC, SDLoc(N), VTs,
40393                        N->getOperand(0), N->getOperand(1),
40394                        Flags);
40395   }
40396 
40397   return SDValue();
40398 }
40399 
40400 /// If this is an add or subtract where one operand is produced by a cmp+setcc,
40401 /// then try to convert it to an ADC or SBB. This replaces TEST+SET+{ADD/SUB}
40402 /// with CMP+{ADC, SBB}.
combineAddOrSubToADCOrSBB(SDNode * N,SelectionDAG & DAG)40403 static SDValue combineAddOrSubToADCOrSBB(SDNode *N, SelectionDAG &DAG) {
40404   bool IsSub = N->getOpcode() == ISD::SUB;
40405   SDValue X = N->getOperand(0);
40406   SDValue Y = N->getOperand(1);
40407 
40408   // If this is an add, canonicalize a zext operand to the RHS.
40409   // TODO: Incomplete? What if both sides are zexts?
40410   if (!IsSub && X.getOpcode() == ISD::ZERO_EXTEND &&
40411       Y.getOpcode() != ISD::ZERO_EXTEND)
40412     std::swap(X, Y);
40413 
40414   // Look through a one-use zext.
40415   bool PeekedThroughZext = false;
40416   if (Y.getOpcode() == ISD::ZERO_EXTEND && Y.hasOneUse()) {
40417     Y = Y.getOperand(0);
40418     PeekedThroughZext = true;
40419   }
40420 
40421   // If this is an add, canonicalize a setcc operand to the RHS.
40422   // TODO: Incomplete? What if both sides are setcc?
40423   // TODO: Should we allow peeking through a zext of the other operand?
40424   if (!IsSub && !PeekedThroughZext && X.getOpcode() == X86ISD::SETCC &&
40425       Y.getOpcode() != X86ISD::SETCC)
40426     std::swap(X, Y);
40427 
40428   if (Y.getOpcode() != X86ISD::SETCC || !Y.hasOneUse())
40429     return SDValue();
40430 
40431   SDLoc DL(N);
40432   EVT VT = N->getValueType(0);
40433   X86::CondCode CC = (X86::CondCode)Y.getConstantOperandVal(0);
40434 
40435   // If X is -1 or 0, then we have an opportunity to avoid constants required in
40436   // the general case below.
40437   auto *ConstantX = dyn_cast<ConstantSDNode>(X);
40438   if (ConstantX) {
40439     if ((!IsSub && CC == X86::COND_AE && ConstantX->isAllOnesValue()) ||
40440         (IsSub && CC == X86::COND_B && ConstantX->isNullValue())) {
40441       // This is a complicated way to get -1 or 0 from the carry flag:
40442       // -1 + SETAE --> -1 + (!CF) --> CF ? -1 : 0 --> SBB %eax, %eax
40443       //  0 - SETB  -->  0 -  (CF) --> CF ? -1 : 0 --> SBB %eax, %eax
40444       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
40445                          DAG.getConstant(X86::COND_B, DL, MVT::i8),
40446                          Y.getOperand(1));
40447     }
40448 
40449     if ((!IsSub && CC == X86::COND_BE && ConstantX->isAllOnesValue()) ||
40450         (IsSub && CC == X86::COND_A && ConstantX->isNullValue())) {
40451       SDValue EFLAGS = Y->getOperand(1);
40452       if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
40453           EFLAGS.getValueType().isInteger() &&
40454           !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
40455         // Swap the operands of a SUB, and we have the same pattern as above.
40456         // -1 + SETBE (SUB A, B) --> -1 + SETAE (SUB B, A) --> SUB + SBB
40457         //  0 - SETA  (SUB A, B) -->  0 - SETB  (SUB B, A) --> SUB + SBB
40458         SDValue NewSub = DAG.getNode(
40459             X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
40460             EFLAGS.getOperand(1), EFLAGS.getOperand(0));
40461         SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
40462         return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
40463                            DAG.getConstant(X86::COND_B, DL, MVT::i8),
40464                            NewEFLAGS);
40465       }
40466     }
40467   }
40468 
40469   if (CC == X86::COND_B) {
40470     // X + SETB Z --> adc X, 0
40471     // X - SETB Z --> sbb X, 0
40472     return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
40473                        DAG.getVTList(VT, MVT::i32), X,
40474                        DAG.getConstant(0, DL, VT), Y.getOperand(1));
40475   }
40476 
40477   if (CC == X86::COND_A) {
40478     SDValue EFLAGS = Y->getOperand(1);
40479     // Try to convert COND_A into COND_B in an attempt to facilitate
40480     // materializing "setb reg".
40481     //
40482     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
40483     // cannot take an immediate as its first operand.
40484     //
40485     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
40486         EFLAGS.getValueType().isInteger() &&
40487         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
40488       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
40489                                    EFLAGS.getNode()->getVTList(),
40490                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
40491       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
40492       return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
40493                          DAG.getVTList(VT, MVT::i32), X,
40494                          DAG.getConstant(0, DL, VT), NewEFLAGS);
40495     }
40496   }
40497 
40498   if (CC != X86::COND_E && CC != X86::COND_NE)
40499     return SDValue();
40500 
40501   SDValue Cmp = Y.getOperand(1);
40502   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
40503       !X86::isZeroNode(Cmp.getOperand(1)) ||
40504       !Cmp.getOperand(0).getValueType().isInteger())
40505     return SDValue();
40506 
40507   SDValue Z = Cmp.getOperand(0);
40508   EVT ZVT = Z.getValueType();
40509 
40510   // If X is -1 or 0, then we have an opportunity to avoid constants required in
40511   // the general case below.
40512   if (ConstantX) {
40513     // 'neg' sets the carry flag when Z != 0, so create 0 or -1 using 'sbb' with
40514     // fake operands:
40515     //  0 - (Z != 0) --> sbb %eax, %eax, (neg Z)
40516     // -1 + (Z == 0) --> sbb %eax, %eax, (neg Z)
40517     if ((IsSub && CC == X86::COND_NE && ConstantX->isNullValue()) ||
40518         (!IsSub && CC == X86::COND_E && ConstantX->isAllOnesValue())) {
40519       SDValue Zero = DAG.getConstant(0, DL, ZVT);
40520       SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
40521       SDValue Neg = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Zero, Z);
40522       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
40523                          DAG.getConstant(X86::COND_B, DL, MVT::i8),
40524                          SDValue(Neg.getNode(), 1));
40525     }
40526 
40527     // cmp with 1 sets the carry flag when Z == 0, so create 0 or -1 using 'sbb'
40528     // with fake operands:
40529     //  0 - (Z == 0) --> sbb %eax, %eax, (cmp Z, 1)
40530     // -1 + (Z != 0) --> sbb %eax, %eax, (cmp Z, 1)
40531     if ((IsSub && CC == X86::COND_E && ConstantX->isNullValue()) ||
40532         (!IsSub && CC == X86::COND_NE && ConstantX->isAllOnesValue())) {
40533       SDValue One = DAG.getConstant(1, DL, ZVT);
40534       SDValue Cmp1 = DAG.getNode(X86ISD::CMP, DL, MVT::i32, Z, One);
40535       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
40536                          DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp1);
40537     }
40538   }
40539 
40540   // (cmp Z, 1) sets the carry flag if Z is 0.
40541   SDValue One = DAG.getConstant(1, DL, ZVT);
40542   SDValue Cmp1 = DAG.getNode(X86ISD::CMP, DL, MVT::i32, Z, One);
40543 
40544   // Add the flags type for ADC/SBB nodes.
40545   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
40546 
40547   // X - (Z != 0) --> sub X, (zext(setne Z, 0)) --> adc X, -1, (cmp Z, 1)
40548   // X + (Z != 0) --> add X, (zext(setne Z, 0)) --> sbb X, -1, (cmp Z, 1)
40549   if (CC == X86::COND_NE)
40550     return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL, VTs, X,
40551                        DAG.getConstant(-1ULL, DL, VT), Cmp1);
40552 
40553   // X - (Z == 0) --> sub X, (zext(sete  Z, 0)) --> sbb X, 0, (cmp Z, 1)
40554   // X + (Z == 0) --> add X, (zext(sete  Z, 0)) --> adc X, 0, (cmp Z, 1)
40555   return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL, VTs, X,
40556                      DAG.getConstant(0, DL, VT), Cmp1);
40557 }
40558 
combineLoopMAddPattern(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)40559 static SDValue combineLoopMAddPattern(SDNode *N, SelectionDAG &DAG,
40560                                       const X86Subtarget &Subtarget) {
40561   if (!Subtarget.hasSSE2())
40562     return SDValue();
40563 
40564   SDValue Op0 = N->getOperand(0);
40565   SDValue Op1 = N->getOperand(1);
40566 
40567   EVT VT = N->getValueType(0);
40568 
40569   // If the vector size is less than 128, or greater than the supported RegSize,
40570   // do not use PMADD.
40571   if (!VT.isVector() || VT.getVectorNumElements() < 8)
40572     return SDValue();
40573 
40574   if (Op0.getOpcode() != ISD::MUL)
40575     std::swap(Op0, Op1);
40576   if (Op0.getOpcode() != ISD::MUL)
40577     return SDValue();
40578 
40579   ShrinkMode Mode;
40580   if (!canReduceVMulWidth(Op0.getNode(), DAG, Mode) || Mode == MULU16)
40581     return SDValue();
40582 
40583   SDLoc DL(N);
40584   EVT ReducedVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
40585                                    VT.getVectorNumElements());
40586   EVT MAddVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
40587                                 VT.getVectorNumElements() / 2);
40588 
40589   // Madd vector size is half of the original vector size
40590   auto PMADDWDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
40591                            ArrayRef<SDValue> Ops) {
40592     MVT VT = MVT::getVectorVT(MVT::i32, Ops[0].getValueSizeInBits() / 32);
40593     return DAG.getNode(X86ISD::VPMADDWD, DL, VT, Ops);
40594   };
40595 
40596   auto BuildPMADDWD = [&](SDValue Mul) {
40597     // Shrink the operands of mul.
40598     SDValue N0 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, Mul.getOperand(0));
40599     SDValue N1 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, Mul.getOperand(1));
40600 
40601     SDValue Madd = SplitOpsAndApply(DAG, Subtarget, DL, MAddVT, { N0, N1 },
40602                                    PMADDWDBuilder);
40603     // Fill the rest of the output with 0
40604     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Madd,
40605                        DAG.getConstant(0, DL, MAddVT));
40606   };
40607 
40608   Op0 = BuildPMADDWD(Op0);
40609 
40610   // It's possible that Op1 is also a mul we can reduce.
40611   if (Op1.getOpcode() == ISD::MUL &&
40612       canReduceVMulWidth(Op1.getNode(), DAG, Mode) && Mode != MULU16) {
40613     Op1 = BuildPMADDWD(Op1);
40614   }
40615 
40616   return DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
40617 }
40618 
combineLoopSADPattern(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)40619 static SDValue combineLoopSADPattern(SDNode *N, SelectionDAG &DAG,
40620                                      const X86Subtarget &Subtarget) {
40621   if (!Subtarget.hasSSE2())
40622     return SDValue();
40623 
40624   SDLoc DL(N);
40625   EVT VT = N->getValueType(0);
40626   SDValue Op0 = N->getOperand(0);
40627   SDValue Op1 = N->getOperand(1);
40628 
40629   // TODO: There's nothing special about i32, any integer type above i16 should
40630   // work just as well.
40631   if (!VT.isVector() || !VT.isSimple() ||
40632       !(VT.getVectorElementType() == MVT::i32))
40633     return SDValue();
40634 
40635   unsigned RegSize = 128;
40636   if (Subtarget.useBWIRegs())
40637     RegSize = 512;
40638   else if (Subtarget.hasAVX())
40639     RegSize = 256;
40640 
40641   // We only handle v16i32 for SSE2 / v32i32 for AVX / v64i32 for AVX512.
40642   // TODO: We should be able to handle larger vectors by splitting them before
40643   // feeding them into several SADs, and then reducing over those.
40644   if (VT.getSizeInBits() / 4 > RegSize)
40645     return SDValue();
40646 
40647   // We know N is a reduction add, which means one of its operands is a phi.
40648   // To match SAD, we need the other operand to be a vector select.
40649   if (Op0.getOpcode() != ISD::VSELECT)
40650     std::swap(Op0, Op1);
40651   if (Op0.getOpcode() != ISD::VSELECT)
40652     return SDValue();
40653 
40654   auto BuildPSADBW = [&](SDValue Op0, SDValue Op1) {
40655     // SAD pattern detected. Now build a SAD instruction and an addition for
40656     // reduction. Note that the number of elements of the result of SAD is less
40657     // than the number of elements of its input. Therefore, we could only update
40658     // part of elements in the reduction vector.
40659     SDValue Sad = createPSADBW(DAG, Op0, Op1, DL, Subtarget);
40660 
40661     // The output of PSADBW is a vector of i64.
40662     // We need to turn the vector of i64 into a vector of i32.
40663     // If the reduction vector is at least as wide as the psadbw result, just
40664     // bitcast. If it's narrower, truncate - the high i32 of each i64 is zero
40665     // anyway.
40666     MVT ResVT = MVT::getVectorVT(MVT::i32, Sad.getValueSizeInBits() / 32);
40667     if (VT.getSizeInBits() >= ResVT.getSizeInBits())
40668       Sad = DAG.getNode(ISD::BITCAST, DL, ResVT, Sad);
40669     else
40670       Sad = DAG.getNode(ISD::TRUNCATE, DL, VT, Sad);
40671 
40672     if (VT.getSizeInBits() > ResVT.getSizeInBits()) {
40673       // Fill the upper elements with zero to match the add width.
40674       SDValue Zero = DAG.getConstant(0, DL, VT);
40675       Sad = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Zero, Sad,
40676                         DAG.getIntPtrConstant(0, DL));
40677     }
40678 
40679     return Sad;
40680   };
40681 
40682   // Check whether we have an abs-diff pattern feeding into the select.
40683   SDValue SadOp0, SadOp1;
40684   if (!detectZextAbsDiff(Op0, SadOp0, SadOp1))
40685     return SDValue();
40686 
40687   Op0 = BuildPSADBW(SadOp0, SadOp1);
40688 
40689   // It's possible we have a sad on the other side too.
40690   if (Op1.getOpcode() == ISD::VSELECT &&
40691       detectZextAbsDiff(Op1, SadOp0, SadOp1)) {
40692     Op1 = BuildPSADBW(SadOp0, SadOp1);
40693   }
40694 
40695   return DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
40696 }
40697 
40698 /// Convert vector increment or decrement to sub/add with an all-ones constant:
40699 /// add X, <1, 1...> --> sub X, <-1, -1...>
40700 /// sub X, <1, 1...> --> add X, <-1, -1...>
40701 /// The all-ones vector constant can be materialized using a pcmpeq instruction
40702 /// that is commonly recognized as an idiom (has no register dependency), so
40703 /// that's better/smaller than loading a splat 1 constant.
combineIncDecVector(SDNode * N,SelectionDAG & DAG)40704 static SDValue combineIncDecVector(SDNode *N, SelectionDAG &DAG) {
40705   assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
40706          "Unexpected opcode for increment/decrement transform");
40707 
40708   // Pseudo-legality check: getOnesVector() expects one of these types, so bail
40709   // out and wait for legalization if we have an unsupported vector length.
40710   EVT VT = N->getValueType(0);
40711   if (!VT.is128BitVector() && !VT.is256BitVector() && !VT.is512BitVector())
40712     return SDValue();
40713 
40714   APInt SplatVal;
40715   if (!isConstantSplat(N->getOperand(1), SplatVal) || !SplatVal.isOneValue())
40716     return SDValue();
40717 
40718   SDValue AllOnesVec = getOnesVector(VT, DAG, SDLoc(N));
40719   unsigned NewOpcode = N->getOpcode() == ISD::ADD ? ISD::SUB : ISD::ADD;
40720   return DAG.getNode(NewOpcode, SDLoc(N), VT, N->getOperand(0), AllOnesVec);
40721 }
40722 
matchPMADDWD(SelectionDAG & DAG,SDValue Op0,SDValue Op1,const SDLoc & DL,EVT VT,const X86Subtarget & Subtarget)40723 static SDValue matchPMADDWD(SelectionDAG &DAG, SDValue Op0, SDValue Op1,
40724                             const SDLoc &DL, EVT VT,
40725                             const X86Subtarget &Subtarget) {
40726   // Example of pattern we try to detect:
40727   // t := (v8i32 mul (sext (v8i16 x0), (sext (v8i16 x1))))
40728   //(add (build_vector (extract_elt t, 0),
40729   //                   (extract_elt t, 2),
40730   //                   (extract_elt t, 4),
40731   //                   (extract_elt t, 6)),
40732   //     (build_vector (extract_elt t, 1),
40733   //                   (extract_elt t, 3),
40734   //                   (extract_elt t, 5),
40735   //                   (extract_elt t, 7)))
40736 
40737   if (!Subtarget.hasSSE2())
40738     return SDValue();
40739 
40740   if (Op0.getOpcode() != ISD::BUILD_VECTOR ||
40741       Op1.getOpcode() != ISD::BUILD_VECTOR)
40742     return SDValue();
40743 
40744   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
40745       VT.getVectorNumElements() < 4 ||
40746       !isPowerOf2_32(VT.getVectorNumElements()))
40747     return SDValue();
40748 
40749   // Check if one of Op0,Op1 is of the form:
40750   // (build_vector (extract_elt Mul, 0),
40751   //               (extract_elt Mul, 2),
40752   //               (extract_elt Mul, 4),
40753   //                   ...
40754   // the other is of the form:
40755   // (build_vector (extract_elt Mul, 1),
40756   //               (extract_elt Mul, 3),
40757   //               (extract_elt Mul, 5),
40758   //                   ...
40759   // and identify Mul.
40760   SDValue Mul;
40761   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; i += 2) {
40762     SDValue Op0L = Op0->getOperand(i), Op1L = Op1->getOperand(i),
40763             Op0H = Op0->getOperand(i + 1), Op1H = Op1->getOperand(i + 1);
40764     // TODO: Be more tolerant to undefs.
40765     if (Op0L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
40766         Op1L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
40767         Op0H.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
40768         Op1H.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
40769       return SDValue();
40770     auto *Const0L = dyn_cast<ConstantSDNode>(Op0L->getOperand(1));
40771     auto *Const1L = dyn_cast<ConstantSDNode>(Op1L->getOperand(1));
40772     auto *Const0H = dyn_cast<ConstantSDNode>(Op0H->getOperand(1));
40773     auto *Const1H = dyn_cast<ConstantSDNode>(Op1H->getOperand(1));
40774     if (!Const0L || !Const1L || !Const0H || !Const1H)
40775       return SDValue();
40776     unsigned Idx0L = Const0L->getZExtValue(), Idx1L = Const1L->getZExtValue(),
40777              Idx0H = Const0H->getZExtValue(), Idx1H = Const1H->getZExtValue();
40778     // Commutativity of mul allows factors of a product to reorder.
40779     if (Idx0L > Idx1L)
40780       std::swap(Idx0L, Idx1L);
40781     if (Idx0H > Idx1H)
40782       std::swap(Idx0H, Idx1H);
40783     // Commutativity of add allows pairs of factors to reorder.
40784     if (Idx0L > Idx0H) {
40785       std::swap(Idx0L, Idx0H);
40786       std::swap(Idx1L, Idx1H);
40787     }
40788     if (Idx0L != 2 * i || Idx1L != 2 * i + 1 || Idx0H != 2 * i + 2 ||
40789         Idx1H != 2 * i + 3)
40790       return SDValue();
40791     if (!Mul) {
40792       // First time an extract_elt's source vector is visited. Must be a MUL
40793       // with 2X number of vector elements than the BUILD_VECTOR.
40794       // Both extracts must be from same MUL.
40795       Mul = Op0L->getOperand(0);
40796       if (Mul->getOpcode() != ISD::MUL ||
40797           Mul.getValueType().getVectorNumElements() != 2 * e)
40798         return SDValue();
40799     }
40800     // Check that the extract is from the same MUL previously seen.
40801     if (Mul != Op0L->getOperand(0) || Mul != Op1L->getOperand(0) ||
40802         Mul != Op0H->getOperand(0) || Mul != Op1H->getOperand(0))
40803       return SDValue();
40804   }
40805 
40806   // Check if the Mul source can be safely shrunk.
40807   ShrinkMode Mode;
40808   if (!canReduceVMulWidth(Mul.getNode(), DAG, Mode) || Mode == MULU16)
40809     return SDValue();
40810 
40811   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
40812                          ArrayRef<SDValue> Ops) {
40813     // Shrink by adding truncate nodes and let DAGCombine fold with the
40814     // sources.
40815     EVT InVT = Ops[0].getValueType();
40816     assert(InVT.getScalarType() == MVT::i32 &&
40817            "Unexpected scalar element type");
40818     assert(InVT == Ops[1].getValueType() && "Operands' types mismatch");
40819     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
40820                                  InVT.getVectorNumElements() / 2);
40821     EVT TruncVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
40822                                    InVT.getVectorNumElements());
40823     return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT,
40824                        DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Ops[0]),
40825                        DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Ops[1]));
40826   };
40827   return SplitOpsAndApply(DAG, Subtarget, DL, VT,
40828                           { Mul.getOperand(0), Mul.getOperand(1) },
40829                           PMADDBuilder);
40830 }
40831 
40832 // Try to turn (add (umax X, C), -C) into (psubus X, C)
combineAddToSUBUS(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)40833 static SDValue combineAddToSUBUS(SDNode *N, SelectionDAG &DAG,
40834                                  const X86Subtarget &Subtarget) {
40835   if (!Subtarget.hasSSE2())
40836     return SDValue();
40837 
40838   EVT VT = N->getValueType(0);
40839 
40840   // psubus is available in SSE2 for i8 and i16 vectors.
40841   if (!VT.isVector() || VT.getVectorNumElements() < 2 ||
40842       !isPowerOf2_32(VT.getVectorNumElements()) ||
40843       !(VT.getVectorElementType() == MVT::i8 ||
40844         VT.getVectorElementType() == MVT::i16))
40845     return SDValue();
40846 
40847   SDValue Op0 = N->getOperand(0);
40848   SDValue Op1 = N->getOperand(1);
40849   if (Op0.getOpcode() != ISD::UMAX)
40850     return SDValue();
40851 
40852   // The add should have a constant that is the negative of the max.
40853   // TODO: Handle build_vectors with undef elements.
40854   auto MatchUSUBSAT = [](ConstantSDNode *Max, ConstantSDNode *Op) {
40855     return Max->getAPIntValue() == (-Op->getAPIntValue());
40856   };
40857   if (!ISD::matchBinaryPredicate(Op0.getOperand(1), Op1, MatchUSUBSAT))
40858     return SDValue();
40859 
40860   SDLoc DL(N);
40861   return DAG.getNode(ISD::USUBSAT, DL, VT, Op0.getOperand(0),
40862                      Op0.getOperand(1));
40863 }
40864 
40865 // Attempt to turn this pattern into PMADDWD.
40866 // (mul (add (zext (build_vector)), (zext (build_vector))),
40867 //      (add (zext (build_vector)), (zext (build_vector)))
matchPMADDWD_2(SelectionDAG & DAG,SDValue N0,SDValue N1,const SDLoc & DL,EVT VT,const X86Subtarget & Subtarget)40868 static SDValue matchPMADDWD_2(SelectionDAG &DAG, SDValue N0, SDValue N1,
40869                               const SDLoc &DL, EVT VT,
40870                               const X86Subtarget &Subtarget) {
40871   if (!Subtarget.hasSSE2())
40872     return SDValue();
40873 
40874   if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
40875     return SDValue();
40876 
40877   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
40878       VT.getVectorNumElements() < 4 ||
40879       !isPowerOf2_32(VT.getVectorNumElements()))
40880     return SDValue();
40881 
40882   SDValue N00 = N0.getOperand(0);
40883   SDValue N01 = N0.getOperand(1);
40884   SDValue N10 = N1.getOperand(0);
40885   SDValue N11 = N1.getOperand(1);
40886 
40887   // All inputs need to be sign extends.
40888   // TODO: Support ZERO_EXTEND from known positive?
40889   if (N00.getOpcode() != ISD::SIGN_EXTEND ||
40890       N01.getOpcode() != ISD::SIGN_EXTEND ||
40891       N10.getOpcode() != ISD::SIGN_EXTEND ||
40892       N11.getOpcode() != ISD::SIGN_EXTEND)
40893     return SDValue();
40894 
40895   // Peek through the extends.
40896   N00 = N00.getOperand(0);
40897   N01 = N01.getOperand(0);
40898   N10 = N10.getOperand(0);
40899   N11 = N11.getOperand(0);
40900 
40901   // Must be extending from vXi16.
40902   EVT InVT = N00.getValueType();
40903   if (InVT.getVectorElementType() != MVT::i16 || N01.getValueType() != InVT ||
40904       N10.getValueType() != InVT || N11.getValueType() != InVT)
40905     return SDValue();
40906 
40907   // All inputs should be build_vectors.
40908   if (N00.getOpcode() != ISD::BUILD_VECTOR ||
40909       N01.getOpcode() != ISD::BUILD_VECTOR ||
40910       N10.getOpcode() != ISD::BUILD_VECTOR ||
40911       N11.getOpcode() != ISD::BUILD_VECTOR)
40912     return SDValue();
40913 
40914   // For each element, we need to ensure we have an odd element from one vector
40915   // multiplied by the odd element of another vector and the even element from
40916   // one of the same vectors being multiplied by the even element from the
40917   // other vector. So we need to make sure for each element i, this operator
40918   // is being performed:
40919   //  A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
40920   SDValue In0, In1;
40921   for (unsigned i = 0; i != N00.getNumOperands(); ++i) {
40922     SDValue N00Elt = N00.getOperand(i);
40923     SDValue N01Elt = N01.getOperand(i);
40924     SDValue N10Elt = N10.getOperand(i);
40925     SDValue N11Elt = N11.getOperand(i);
40926     // TODO: Be more tolerant to undefs.
40927     if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
40928         N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
40929         N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
40930         N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
40931       return SDValue();
40932     auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
40933     auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
40934     auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
40935     auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
40936     if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
40937       return SDValue();
40938     unsigned IdxN00 = ConstN00Elt->getZExtValue();
40939     unsigned IdxN01 = ConstN01Elt->getZExtValue();
40940     unsigned IdxN10 = ConstN10Elt->getZExtValue();
40941     unsigned IdxN11 = ConstN11Elt->getZExtValue();
40942     // Add is commutative so indices can be reordered.
40943     if (IdxN00 > IdxN10) {
40944       std::swap(IdxN00, IdxN10);
40945       std::swap(IdxN01, IdxN11);
40946     }
40947     // N0 indices be the even element. N1 indices must be the next odd element.
40948     if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
40949         IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
40950       return SDValue();
40951     SDValue N00In = N00Elt.getOperand(0);
40952     SDValue N01In = N01Elt.getOperand(0);
40953     SDValue N10In = N10Elt.getOperand(0);
40954     SDValue N11In = N11Elt.getOperand(0);
40955     // First time we find an input capture it.
40956     if (!In0) {
40957       In0 = N00In;
40958       In1 = N01In;
40959     }
40960     // Mul is commutative so the input vectors can be in any order.
40961     // Canonicalize to make the compares easier.
40962     if (In0 != N00In)
40963       std::swap(N00In, N01In);
40964     if (In0 != N10In)
40965       std::swap(N10In, N11In);
40966     if (In0 != N00In || In1 != N01In || In0 != N10In || In1 != N11In)
40967       return SDValue();
40968   }
40969 
40970   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
40971                          ArrayRef<SDValue> Ops) {
40972     // Shrink by adding truncate nodes and let DAGCombine fold with the
40973     // sources.
40974     EVT InVT = Ops[0].getValueType();
40975     assert(InVT.getScalarType() == MVT::i16 &&
40976            "Unexpected scalar element type");
40977     assert(InVT == Ops[1].getValueType() && "Operands' types mismatch");
40978     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
40979                                  InVT.getVectorNumElements() / 2);
40980     return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT, Ops[0], Ops[1]);
40981   };
40982   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { In0, In1 },
40983                           PMADDBuilder);
40984 }
40985 
combineAdd(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)40986 static SDValue combineAdd(SDNode *N, SelectionDAG &DAG,
40987                           const X86Subtarget &Subtarget) {
40988   const SDNodeFlags Flags = N->getFlags();
40989   if (Flags.hasVectorReduction()) {
40990     if (SDValue Sad = combineLoopSADPattern(N, DAG, Subtarget))
40991       return Sad;
40992     if (SDValue MAdd = combineLoopMAddPattern(N, DAG, Subtarget))
40993       return MAdd;
40994   }
40995   EVT VT = N->getValueType(0);
40996   SDValue Op0 = N->getOperand(0);
40997   SDValue Op1 = N->getOperand(1);
40998 
40999   if (SDValue MAdd = matchPMADDWD(DAG, Op0, Op1, SDLoc(N), VT, Subtarget))
41000     return MAdd;
41001   if (SDValue MAdd = matchPMADDWD_2(DAG, Op0, Op1, SDLoc(N), VT, Subtarget))
41002     return MAdd;
41003 
41004   // Try to synthesize horizontal adds from adds of shuffles.
41005   if ((VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v16i16 ||
41006        VT == MVT::v8i32) &&
41007       Subtarget.hasSSSE3() && isHorizontalBinOp(Op0, Op1, true) &&
41008       shouldUseHorizontalOp(Op0 == Op1, DAG, Subtarget)) {
41009     auto HADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
41010                           ArrayRef<SDValue> Ops) {
41011       return DAG.getNode(X86ISD::HADD, DL, Ops[0].getValueType(), Ops);
41012     };
41013     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, {Op0, Op1},
41014                             HADDBuilder);
41015   }
41016 
41017   if (SDValue V = combineIncDecVector(N, DAG))
41018     return V;
41019 
41020   if (SDValue V = combineAddToSUBUS(N, DAG, Subtarget))
41021     return V;
41022 
41023   return combineAddOrSubToADCOrSBB(N, DAG);
41024 }
41025 
combineSubToSubus(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)41026 static SDValue combineSubToSubus(SDNode *N, SelectionDAG &DAG,
41027                                  const X86Subtarget &Subtarget) {
41028   SDValue Op0 = N->getOperand(0);
41029   SDValue Op1 = N->getOperand(1);
41030   EVT VT = N->getValueType(0);
41031 
41032   // PSUBUS is supported, starting from SSE2, but truncation for v8i32
41033   // is only worth it with SSSE3 (PSHUFB).
41034   if (!(Subtarget.hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) &&
41035       !(Subtarget.hasSSSE3() && (VT == MVT::v8i32 || VT == MVT::v8i64)) &&
41036       !(Subtarget.hasAVX() && (VT == MVT::v32i8 || VT == MVT::v16i16)) &&
41037       !(Subtarget.useBWIRegs() && (VT == MVT::v64i8 || VT == MVT::v32i16 ||
41038                                    VT == MVT::v16i32 || VT == MVT::v8i64)))
41039     return SDValue();
41040 
41041   SDValue SubusLHS, SubusRHS;
41042   // Try to find umax(a,b) - b or a - umin(a,b) patterns
41043   // they may be converted to subus(a,b).
41044   // TODO: Need to add IR canonicalization for this code.
41045   if (Op0.getOpcode() == ISD::UMAX) {
41046     SubusRHS = Op1;
41047     SDValue MaxLHS = Op0.getOperand(0);
41048     SDValue MaxRHS = Op0.getOperand(1);
41049     if (MaxLHS == Op1)
41050       SubusLHS = MaxRHS;
41051     else if (MaxRHS == Op1)
41052       SubusLHS = MaxLHS;
41053     else
41054       return SDValue();
41055   } else if (Op1.getOpcode() == ISD::UMIN) {
41056     SubusLHS = Op0;
41057     SDValue MinLHS = Op1.getOperand(0);
41058     SDValue MinRHS = Op1.getOperand(1);
41059     if (MinLHS == Op0)
41060       SubusRHS = MinRHS;
41061     else if (MinRHS == Op0)
41062       SubusRHS = MinLHS;
41063     else
41064       return SDValue();
41065   } else
41066     return SDValue();
41067 
41068   auto USUBSATBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
41069                            ArrayRef<SDValue> Ops) {
41070     return DAG.getNode(ISD::USUBSAT, DL, Ops[0].getValueType(), Ops);
41071   };
41072 
41073   // PSUBUS doesn't support v8i32/v8i64/v16i32, but it can be enabled with
41074   // special preprocessing in some cases.
41075   if (VT != MVT::v8i32 && VT != MVT::v16i32 && VT != MVT::v8i64)
41076     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT,
41077                             { SubusLHS, SubusRHS }, USUBSATBuilder);
41078 
41079   // Special preprocessing case can be only applied
41080   // if the value was zero extended from 16 bit,
41081   // so we require first 16 bits to be zeros for 32 bit
41082   // values, or first 48 bits for 64 bit values.
41083   KnownBits Known = DAG.computeKnownBits(SubusLHS);
41084   unsigned NumZeros = Known.countMinLeadingZeros();
41085   if ((VT == MVT::v8i64 && NumZeros < 48) || NumZeros < 16)
41086     return SDValue();
41087 
41088   EVT ExtType = SubusLHS.getValueType();
41089   EVT ShrinkedType;
41090   if (VT == MVT::v8i32 || VT == MVT::v8i64)
41091     ShrinkedType = MVT::v8i16;
41092   else
41093     ShrinkedType = NumZeros >= 24 ? MVT::v16i8 : MVT::v16i16;
41094 
41095   // If SubusLHS is zeroextended - truncate SubusRHS to it's
41096   // size SubusRHS = umin(0xFFF.., SubusRHS).
41097   SDValue SaturationConst =
41098       DAG.getConstant(APInt::getLowBitsSet(ExtType.getScalarSizeInBits(),
41099                                            ShrinkedType.getScalarSizeInBits()),
41100                       SDLoc(SubusLHS), ExtType);
41101   SDValue UMin = DAG.getNode(ISD::UMIN, SDLoc(SubusLHS), ExtType, SubusRHS,
41102                              SaturationConst);
41103   SDValue NewSubusLHS =
41104       DAG.getZExtOrTrunc(SubusLHS, SDLoc(SubusLHS), ShrinkedType);
41105   SDValue NewSubusRHS = DAG.getZExtOrTrunc(UMin, SDLoc(SubusRHS), ShrinkedType);
41106   SDValue Psubus =
41107       SplitOpsAndApply(DAG, Subtarget, SDLoc(N), ShrinkedType,
41108                        { NewSubusLHS, NewSubusRHS }, USUBSATBuilder);
41109   // Zero extend the result, it may be used somewhere as 32 bit,
41110   // if not zext and following trunc will shrink.
41111   return DAG.getZExtOrTrunc(Psubus, SDLoc(N), ExtType);
41112 }
41113 
combineSub(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)41114 static SDValue combineSub(SDNode *N, SelectionDAG &DAG,
41115                           const X86Subtarget &Subtarget) {
41116   SDValue Op0 = N->getOperand(0);
41117   SDValue Op1 = N->getOperand(1);
41118 
41119   // X86 can't encode an immediate LHS of a sub. See if we can push the
41120   // negation into a preceding instruction.
41121   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
41122     // If the RHS of the sub is a XOR with one use and a constant, invert the
41123     // immediate. Then add one to the LHS of the sub so we can turn
41124     // X-Y -> X+~Y+1, saving one register.
41125     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
41126         isa<ConstantSDNode>(Op1.getOperand(1))) {
41127       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
41128       EVT VT = Op0.getValueType();
41129       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
41130                                    Op1.getOperand(0),
41131                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
41132       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
41133                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
41134     }
41135   }
41136 
41137   // Try to synthesize horizontal subs from subs of shuffles.
41138   EVT VT = N->getValueType(0);
41139   if ((VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v16i16 ||
41140        VT == MVT::v8i32) &&
41141       Subtarget.hasSSSE3() && isHorizontalBinOp(Op0, Op1, false) &&
41142       shouldUseHorizontalOp(Op0 == Op1, DAG, Subtarget)) {
41143     auto HSUBBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
41144                           ArrayRef<SDValue> Ops) {
41145       return DAG.getNode(X86ISD::HSUB, DL, Ops[0].getValueType(), Ops);
41146     };
41147     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, {Op0, Op1},
41148                             HSUBBuilder);
41149   }
41150 
41151   if (SDValue V = combineIncDecVector(N, DAG))
41152     return V;
41153 
41154   // Try to create PSUBUS if SUB's argument is max/min
41155   if (SDValue V = combineSubToSubus(N, DAG, Subtarget))
41156     return V;
41157 
41158   return combineAddOrSubToADCOrSBB(N, DAG);
41159 }
41160 
combineVectorCompare(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)41161 static SDValue combineVectorCompare(SDNode *N, SelectionDAG &DAG,
41162                                     const X86Subtarget &Subtarget) {
41163   MVT VT = N->getSimpleValueType(0);
41164   SDLoc DL(N);
41165 
41166   if (N->getOperand(0) == N->getOperand(1)) {
41167     if (N->getOpcode() == X86ISD::PCMPEQ)
41168       return DAG.getConstant(-1, DL, VT);
41169     if (N->getOpcode() == X86ISD::PCMPGT)
41170       return DAG.getConstant(0, DL, VT);
41171   }
41172 
41173   return SDValue();
41174 }
41175 
combineInsertSubvector(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)41176 static SDValue combineInsertSubvector(SDNode *N, SelectionDAG &DAG,
41177                                       TargetLowering::DAGCombinerInfo &DCI,
41178                                       const X86Subtarget &Subtarget) {
41179   if (DCI.isBeforeLegalizeOps())
41180     return SDValue();
41181 
41182   MVT OpVT = N->getSimpleValueType(0);
41183 
41184   bool IsI1Vector = OpVT.getVectorElementType() == MVT::i1;
41185 
41186   SDLoc dl(N);
41187   SDValue Vec = N->getOperand(0);
41188   SDValue SubVec = N->getOperand(1);
41189 
41190   unsigned IdxVal = N->getConstantOperandVal(2);
41191   MVT SubVecVT = SubVec.getSimpleValueType();
41192 
41193   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
41194     // Inserting zeros into zeros is a nop.
41195     if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
41196       return getZeroVector(OpVT, Subtarget, DAG, dl);
41197 
41198     // If we're inserting into a zero vector and then into a larger zero vector,
41199     // just insert into the larger zero vector directly.
41200     if (SubVec.getOpcode() == ISD::INSERT_SUBVECTOR &&
41201         ISD::isBuildVectorAllZeros(SubVec.getOperand(0).getNode())) {
41202       unsigned Idx2Val = SubVec.getConstantOperandVal(2);
41203       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
41204                          getZeroVector(OpVT, Subtarget, DAG, dl),
41205                          SubVec.getOperand(1),
41206                          DAG.getIntPtrConstant(IdxVal + Idx2Val, dl));
41207     }
41208 
41209     // If we're inserting into a zero vector and our input was extracted from an
41210     // insert into a zero vector of the same type and the extraction was at
41211     // least as large as the original insertion. Just insert the original
41212     // subvector into a zero vector.
41213     if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR && IdxVal == 0 &&
41214         SubVec.getConstantOperandVal(1) == 0 &&
41215         SubVec.getOperand(0).getOpcode() == ISD::INSERT_SUBVECTOR) {
41216       SDValue Ins = SubVec.getOperand(0);
41217       if (Ins.getConstantOperandVal(2) == 0 &&
41218           ISD::isBuildVectorAllZeros(Ins.getOperand(0).getNode()) &&
41219           Ins.getOperand(1).getValueSizeInBits() <= SubVecVT.getSizeInBits())
41220         return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
41221                            getZeroVector(OpVT, Subtarget, DAG, dl),
41222                            Ins.getOperand(1), N->getOperand(2));
41223     }
41224 
41225     // If we're inserting a bitcast into zeros, rewrite the insert and move the
41226     // bitcast to the other side. This helps with detecting zero extending
41227     // during isel.
41228     // TODO: Is this useful for other indices than 0?
41229     if (!IsI1Vector && SubVec.getOpcode() == ISD::BITCAST && IdxVal == 0) {
41230       MVT CastVT = SubVec.getOperand(0).getSimpleValueType();
41231       unsigned NumElems = OpVT.getSizeInBits() / CastVT.getScalarSizeInBits();
41232       MVT NewVT = MVT::getVectorVT(CastVT.getVectorElementType(), NumElems);
41233       SDValue Insert = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
41234                                    DAG.getBitcast(NewVT, Vec),
41235                                    SubVec.getOperand(0), N->getOperand(2));
41236       return DAG.getBitcast(OpVT, Insert);
41237     }
41238   }
41239 
41240   // Stop here if this is an i1 vector.
41241   if (IsI1Vector)
41242     return SDValue();
41243 
41244   // If this is an insert of an extract, combine to a shuffle. Don't do this
41245   // if the insert or extract can be represented with a subregister operation.
41246   if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
41247       SubVec.getOperand(0).getSimpleValueType() == OpVT &&
41248       (IdxVal != 0 || !Vec.isUndef())) {
41249     int ExtIdxVal = SubVec.getConstantOperandVal(1);
41250     if (ExtIdxVal != 0) {
41251       int VecNumElts = OpVT.getVectorNumElements();
41252       int SubVecNumElts = SubVecVT.getVectorNumElements();
41253       SmallVector<int, 64> Mask(VecNumElts);
41254       // First create an identity shuffle mask.
41255       for (int i = 0; i != VecNumElts; ++i)
41256         Mask[i] = i;
41257       // Now insert the extracted portion.
41258       for (int i = 0; i != SubVecNumElts; ++i)
41259         Mask[i + IdxVal] = i + ExtIdxVal + VecNumElts;
41260 
41261       return DAG.getVectorShuffle(OpVT, dl, Vec, SubVec.getOperand(0), Mask);
41262     }
41263   }
41264 
41265   // Fold two 16-byte or 32-byte subvector loads into one 32-byte or 64-byte
41266   // load:
41267   // (insert_subvector (insert_subvector undef, (load16 addr), 0),
41268   //                   (load16 addr + 16), Elts/2)
41269   // --> load32 addr
41270   // or:
41271   // (insert_subvector (insert_subvector undef, (load32 addr), 0),
41272   //                   (load32 addr + 32), Elts/2)
41273   // --> load64 addr
41274   // or a 16-byte or 32-byte broadcast:
41275   // (insert_subvector (insert_subvector undef, (load16 addr), 0),
41276   //                   (load16 addr), Elts/2)
41277   // --> X86SubVBroadcast(load16 addr)
41278   // or:
41279   // (insert_subvector (insert_subvector undef, (load32 addr), 0),
41280   //                   (load32 addr), Elts/2)
41281   // --> X86SubVBroadcast(load32 addr)
41282   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
41283       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
41284       OpVT.getSizeInBits() == SubVecVT.getSizeInBits() * 2) {
41285     if (isNullConstant(Vec.getOperand(2))) {
41286       SDValue SubVec2 = Vec.getOperand(1);
41287       // If needed, look through bitcasts to get to the load.
41288       if (auto *FirstLd = dyn_cast<LoadSDNode>(peekThroughBitcasts(SubVec2))) {
41289         bool Fast;
41290         unsigned Alignment = FirstLd->getAlignment();
41291         unsigned AS = FirstLd->getAddressSpace();
41292         const X86TargetLowering *TLI = Subtarget.getTargetLowering();
41293         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
41294                                     OpVT, AS, Alignment, &Fast) && Fast) {
41295           SDValue Ops[] = {SubVec2, SubVec};
41296           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG,
41297                                                     Subtarget, false))
41298             return Ld;
41299         }
41300       }
41301       // If lower/upper loads are the same and there's no other use of the lower
41302       // load, then splat the loaded value with a broadcast.
41303       if (auto *Ld = dyn_cast<LoadSDNode>(peekThroughOneUseBitcasts(SubVec2)))
41304         if (SubVec2 == SubVec && ISD::isNormalLoad(Ld) && Vec.hasOneUse())
41305           return DAG.getNode(X86ISD::SUBV_BROADCAST, dl, OpVT, SubVec);
41306 
41307       // If this is subv_broadcast insert into both halves, use a larger
41308       // subv_broadcast.
41309       if (SubVec.getOpcode() == X86ISD::SUBV_BROADCAST && SubVec == SubVec2)
41310         return DAG.getNode(X86ISD::SUBV_BROADCAST, dl, OpVT,
41311                            SubVec.getOperand(0));
41312 
41313       // If we're inserting all zeros into the upper half, change this to
41314       // an insert into an all zeros vector. We will match this to a move
41315       // with implicit upper bit zeroing during isel.
41316       if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
41317         return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
41318                            getZeroVector(OpVT, Subtarget, DAG, dl), SubVec2,
41319                            Vec.getOperand(2));
41320 
41321       // If we are inserting into both halves of the vector, the starting
41322       // vector should be undef. If it isn't, make it so. Only do this if the
41323       // the early insert has no other uses.
41324       // TODO: Should this be a generic DAG combine?
41325       if (!Vec.getOperand(0).isUndef() && Vec.hasOneUse()) {
41326         Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, DAG.getUNDEF(OpVT),
41327                           SubVec2, Vec.getOperand(2));
41328         return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Vec, SubVec,
41329                            N->getOperand(2));
41330 
41331       }
41332     }
41333   }
41334 
41335   return SDValue();
41336 }
41337 
combineExtractSubvector(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)41338 static SDValue combineExtractSubvector(SDNode *N, SelectionDAG &DAG,
41339                                        TargetLowering::DAGCombinerInfo &DCI,
41340                                        const X86Subtarget &Subtarget) {
41341   // For AVX1 only, if we are extracting from a 256-bit and+not (which will
41342   // eventually get combined/lowered into ANDNP) with a concatenated operand,
41343   // split the 'and' into 128-bit ops to avoid the concatenate and extract.
41344   // We let generic combining take over from there to simplify the
41345   // insert/extract and 'not'.
41346   // This pattern emerges during AVX1 legalization. We handle it before lowering
41347   // to avoid complications like splitting constant vector loads.
41348 
41349   // Capture the original wide type in the likely case that we need to bitcast
41350   // back to this type.
41351   EVT VT = N->getValueType(0);
41352   EVT WideVecVT = N->getOperand(0).getValueType();
41353   SDValue WideVec = peekThroughBitcasts(N->getOperand(0));
41354   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41355   if (Subtarget.hasAVX() && !Subtarget.hasAVX2() &&
41356       TLI.isTypeLegal(WideVecVT) &&
41357       WideVecVT.getSizeInBits() == 256 && WideVec.getOpcode() == ISD::AND) {
41358     auto isConcatenatedNot = [] (SDValue V) {
41359       V = peekThroughBitcasts(V);
41360       if (!isBitwiseNot(V))
41361         return false;
41362       SDValue NotOp = V->getOperand(0);
41363       return peekThroughBitcasts(NotOp).getOpcode() == ISD::CONCAT_VECTORS;
41364     };
41365     if (isConcatenatedNot(WideVec.getOperand(0)) ||
41366         isConcatenatedNot(WideVec.getOperand(1))) {
41367       // extract (and v4i64 X, (not (concat Y1, Y2))), n -> andnp v2i64 X(n), Y1
41368       SDValue Concat = split256IntArith(WideVec, DAG);
41369       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), VT,
41370                          DAG.getBitcast(WideVecVT, Concat), N->getOperand(1));
41371     }
41372   }
41373 
41374   if (DCI.isBeforeLegalizeOps())
41375     return SDValue();
41376 
41377   MVT OpVT = N->getSimpleValueType(0);
41378   SDValue InVec = N->getOperand(0);
41379   unsigned IdxVal = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
41380 
41381   if (ISD::isBuildVectorAllZeros(InVec.getNode()))
41382     return getZeroVector(OpVT, Subtarget, DAG, SDLoc(N));
41383 
41384   if (ISD::isBuildVectorAllOnes(InVec.getNode())) {
41385     if (OpVT.getScalarType() == MVT::i1)
41386       return DAG.getConstant(1, SDLoc(N), OpVT);
41387     return getOnesVector(OpVT, DAG, SDLoc(N));
41388   }
41389 
41390   if (InVec.getOpcode() == ISD::BUILD_VECTOR)
41391     return DAG.getBuildVector(
41392         OpVT, SDLoc(N),
41393         InVec.getNode()->ops().slice(IdxVal, OpVT.getVectorNumElements()));
41394 
41395   // If we're extracting the lowest subvector and we're the only user,
41396   // we may be able to perform this with a smaller vector width.
41397   if (IdxVal == 0 && InVec.hasOneUse()) {
41398     unsigned InOpcode = InVec.getOpcode();
41399     if (OpVT == MVT::v2f64 && InVec.getValueType() == MVT::v4f64) {
41400       // v2f64 CVTDQ2PD(v4i32).
41401       if (InOpcode == ISD::SINT_TO_FP &&
41402           InVec.getOperand(0).getValueType() == MVT::v4i32) {
41403         return DAG.getNode(X86ISD::CVTSI2P, SDLoc(N), OpVT, InVec.getOperand(0));
41404       }
41405       // v2f64 CVTPS2PD(v4f32).
41406       if (InOpcode == ISD::FP_EXTEND &&
41407           InVec.getOperand(0).getValueType() == MVT::v4f32) {
41408         return DAG.getNode(X86ISD::VFPEXT, SDLoc(N), OpVT, InVec.getOperand(0));
41409       }
41410     }
41411     if ((InOpcode == ISD::ZERO_EXTEND || InOpcode == ISD::SIGN_EXTEND) &&
41412         OpVT.is128BitVector() &&
41413         InVec.getOperand(0).getSimpleValueType().is128BitVector()) {
41414       unsigned ExtOp =
41415         InOpcode == ISD::ZERO_EXTEND ? ISD::ZERO_EXTEND_VECTOR_INREG
41416                                      : ISD::SIGN_EXTEND_VECTOR_INREG;
41417       return DAG.getNode(ExtOp, SDLoc(N), OpVT, InVec.getOperand(0));
41418     }
41419     if ((InOpcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
41420          InOpcode == ISD::SIGN_EXTEND_VECTOR_INREG) &&
41421         OpVT.is128BitVector() &&
41422         InVec.getOperand(0).getSimpleValueType().is128BitVector()) {
41423       return DAG.getNode(InOpcode, SDLoc(N), OpVT, InVec.getOperand(0));
41424     }
41425     if (InOpcode == ISD::BITCAST) {
41426       // TODO - do this for target shuffles in general.
41427       SDValue InVecBC = peekThroughOneUseBitcasts(InVec);
41428       if (InVecBC.getOpcode() == X86ISD::PSHUFB && OpVT.is128BitVector()) {
41429         SDLoc DL(N);
41430         SDValue SubPSHUFB =
41431             DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
41432                         extract128BitVector(InVecBC.getOperand(0), 0, DAG, DL),
41433                         extract128BitVector(InVecBC.getOperand(1), 0, DAG, DL));
41434         return DAG.getBitcast(OpVT, SubPSHUFB);
41435       }
41436     }
41437   }
41438 
41439   return SDValue();
41440 }
41441 
combineScalarToVector(SDNode * N,SelectionDAG & DAG)41442 static SDValue combineScalarToVector(SDNode *N, SelectionDAG &DAG) {
41443   EVT VT = N->getValueType(0);
41444   SDValue Src = N->getOperand(0);
41445 
41446   // If this is a scalar to vector to v1i1 from an AND with 1, bypass the and.
41447   // This occurs frequently in our masked scalar intrinsic code and our
41448   // floating point select lowering with AVX512.
41449   // TODO: SimplifyDemandedBits instead?
41450   if (VT == MVT::v1i1 && Src.getOpcode() == ISD::AND && Src.hasOneUse())
41451     if (auto *C = dyn_cast<ConstantSDNode>(Src.getOperand(1)))
41452       if (C->getAPIntValue().isOneValue())
41453         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), MVT::v1i1,
41454                            Src.getOperand(0));
41455 
41456   // Combine scalar_to_vector of an extract_vector_elt into an extract_subvec.
41457   if (VT == MVT::v1i1 && Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
41458       Src.hasOneUse() && Src.getOperand(0).getValueType().isVector() &&
41459       Src.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
41460     if (auto *C = dyn_cast<ConstantSDNode>(Src.getOperand(1)))
41461       if (C->isNullValue())
41462         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), VT,
41463                            Src.getOperand(0), Src.getOperand(1));
41464 
41465   return SDValue();
41466 }
41467 
41468 // Simplify PMULDQ and PMULUDQ operations.
combinePMULDQ(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)41469 static SDValue combinePMULDQ(SDNode *N, SelectionDAG &DAG,
41470                              TargetLowering::DAGCombinerInfo &DCI) {
41471   SDValue LHS = N->getOperand(0);
41472   SDValue RHS = N->getOperand(1);
41473 
41474   // Canonicalize constant to RHS.
41475   if (DAG.isConstantIntBuildVectorOrConstantInt(LHS) &&
41476       !DAG.isConstantIntBuildVectorOrConstantInt(RHS))
41477     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), RHS, LHS);
41478 
41479   // Multiply by zero.
41480   if (ISD::isBuildVectorAllZeros(RHS.getNode()))
41481     return RHS;
41482 
41483   // Aggressively peek through ops to get at the demanded low bits.
41484   APInt DemandedMask = APInt::getLowBitsSet(64, 32);
41485   SDValue DemandedLHS = DAG.GetDemandedBits(LHS, DemandedMask);
41486   SDValue DemandedRHS = DAG.GetDemandedBits(RHS, DemandedMask);
41487   if (DemandedLHS || DemandedRHS)
41488     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
41489                        DemandedLHS ? DemandedLHS : LHS,
41490                        DemandedRHS ? DemandedRHS : RHS);
41491 
41492   // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
41493   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41494   if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnesValue(64), DCI))
41495     return SDValue(N, 0);
41496 
41497   return SDValue();
41498 }
41499 
PerformDAGCombine(SDNode * N,DAGCombinerInfo & DCI) const41500 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
41501                                              DAGCombinerInfo &DCI) const {
41502   SelectionDAG &DAG = DCI.DAG;
41503   switch (N->getOpcode()) {
41504   default: break;
41505   case ISD::SCALAR_TO_VECTOR:
41506     return combineScalarToVector(N, DAG);
41507   case ISD::EXTRACT_VECTOR_ELT:
41508   case X86ISD::PEXTRW:
41509   case X86ISD::PEXTRB:
41510     return combineExtractVectorElt(N, DAG, DCI, Subtarget);
41511   case ISD::INSERT_SUBVECTOR:
41512     return combineInsertSubvector(N, DAG, DCI, Subtarget);
41513   case ISD::EXTRACT_SUBVECTOR:
41514     return combineExtractSubvector(N, DAG, DCI, Subtarget);
41515   case ISD::VSELECT:
41516   case ISD::SELECT:
41517   case X86ISD::BLENDV:      return combineSelect(N, DAG, DCI, Subtarget);
41518   case ISD::BITCAST:        return combineBitcast(N, DAG, DCI, Subtarget);
41519   case X86ISD::CMOV:        return combineCMov(N, DAG, DCI, Subtarget);
41520   case X86ISD::CMP:         return combineCMP(N, DAG);
41521   case ISD::ADD:            return combineAdd(N, DAG, Subtarget);
41522   case ISD::SUB:            return combineSub(N, DAG, Subtarget);
41523   case X86ISD::SBB:         return combineSBB(N, DAG);
41524   case X86ISD::ADC:         return combineADC(N, DAG, DCI);
41525   case ISD::MUL:            return combineMul(N, DAG, DCI, Subtarget);
41526   case ISD::SHL:
41527   case ISD::SRA:
41528   case ISD::SRL:            return combineShift(N, DAG, DCI, Subtarget);
41529   case ISD::AND:            return combineAnd(N, DAG, DCI, Subtarget);
41530   case ISD::OR:             return combineOr(N, DAG, DCI, Subtarget);
41531   case ISD::XOR:            return combineXor(N, DAG, DCI, Subtarget);
41532   case X86ISD::BEXTR:       return combineBEXTR(N, DAG, DCI, Subtarget);
41533   case ISD::LOAD:           return combineLoad(N, DAG, DCI, Subtarget);
41534   case ISD::MLOAD:          return combineMaskedLoad(N, DAG, DCI, Subtarget);
41535   case ISD::STORE:          return combineStore(N, DAG, Subtarget);
41536   case ISD::MSTORE:         return combineMaskedStore(N, DAG, DCI, Subtarget);
41537   case ISD::SINT_TO_FP:     return combineSIntToFP(N, DAG, Subtarget);
41538   case ISD::UINT_TO_FP:     return combineUIntToFP(N, DAG, Subtarget);
41539   case ISD::FADD:
41540   case ISD::FSUB:           return combineFaddFsub(N, DAG, Subtarget);
41541   case ISD::FNEG:           return combineFneg(N, DAG, Subtarget);
41542   case ISD::TRUNCATE:       return combineTruncate(N, DAG, Subtarget);
41543   case X86ISD::ANDNP:       return combineAndnp(N, DAG, DCI, Subtarget);
41544   case X86ISD::FAND:        return combineFAnd(N, DAG, Subtarget);
41545   case X86ISD::FANDN:       return combineFAndn(N, DAG, Subtarget);
41546   case X86ISD::FXOR:
41547   case X86ISD::FOR:         return combineFOr(N, DAG, Subtarget);
41548   case X86ISD::FMIN:
41549   case X86ISD::FMAX:        return combineFMinFMax(N, DAG);
41550   case ISD::FMINNUM:
41551   case ISD::FMAXNUM:        return combineFMinNumFMaxNum(N, DAG, Subtarget);
41552   case X86ISD::CVTSI2P:
41553   case X86ISD::CVTUI2P:     return combineX86INT_TO_FP(N, DAG, DCI);
41554   case X86ISD::BT:          return combineBT(N, DAG, DCI);
41555   case ISD::ANY_EXTEND:
41556   case ISD::ZERO_EXTEND:    return combineZext(N, DAG, DCI, Subtarget);
41557   case ISD::SIGN_EXTEND:    return combineSext(N, DAG, DCI, Subtarget);
41558   case ISD::SIGN_EXTEND_INREG: return combineSignExtendInReg(N, DAG, Subtarget);
41559   case ISD::SETCC:          return combineSetCC(N, DAG, Subtarget);
41560   case X86ISD::SETCC:       return combineX86SetCC(N, DAG, Subtarget);
41561   case X86ISD::BRCOND:      return combineBrCond(N, DAG, Subtarget);
41562   case X86ISD::PACKSS:
41563   case X86ISD::PACKUS:      return combineVectorPack(N, DAG, DCI, Subtarget);
41564   case X86ISD::VSHL:
41565   case X86ISD::VSRA:
41566   case X86ISD::VSRL:
41567     return combineVectorShiftVar(N, DAG, DCI, Subtarget);
41568   case X86ISD::VSHLI:
41569   case X86ISD::VSRAI:
41570   case X86ISD::VSRLI:
41571     return combineVectorShiftImm(N, DAG, DCI, Subtarget);
41572   case X86ISD::PINSRB:
41573   case X86ISD::PINSRW:      return combineVectorInsert(N, DAG, DCI, Subtarget);
41574   case X86ISD::SHUFP:       // Handle all target specific shuffles
41575   case X86ISD::INSERTPS:
41576   case X86ISD::EXTRQI:
41577   case X86ISD::INSERTQI:
41578   case X86ISD::PALIGNR:
41579   case X86ISD::VSHLDQ:
41580   case X86ISD::VSRLDQ:
41581   case X86ISD::BLENDI:
41582   case X86ISD::UNPCKH:
41583   case X86ISD::UNPCKL:
41584   case X86ISD::MOVHLPS:
41585   case X86ISD::MOVLHPS:
41586   case X86ISD::PSHUFB:
41587   case X86ISD::PSHUFD:
41588   case X86ISD::PSHUFHW:
41589   case X86ISD::PSHUFLW:
41590   case X86ISD::MOVSHDUP:
41591   case X86ISD::MOVSLDUP:
41592   case X86ISD::MOVDDUP:
41593   case X86ISD::MOVSS:
41594   case X86ISD::MOVSD:
41595   case X86ISD::VBROADCAST:
41596   case X86ISD::VPPERM:
41597   case X86ISD::VPERMI:
41598   case X86ISD::VPERMV:
41599   case X86ISD::VPERMV3:
41600   case X86ISD::VPERMIL2:
41601   case X86ISD::VPERMILPI:
41602   case X86ISD::VPERMILPV:
41603   case X86ISD::VPERM2X128:
41604   case X86ISD::SHUF128:
41605   case X86ISD::VZEXT_MOVL:
41606   case ISD::VECTOR_SHUFFLE: return combineShuffle(N, DAG, DCI,Subtarget);
41607   case X86ISD::FMADD_RND:
41608   case X86ISD::FMSUB:
41609   case X86ISD::FMSUB_RND:
41610   case X86ISD::FNMADD:
41611   case X86ISD::FNMADD_RND:
41612   case X86ISD::FNMSUB:
41613   case X86ISD::FNMSUB_RND:
41614   case ISD::FMA: return combineFMA(N, DAG, Subtarget);
41615   case X86ISD::FMADDSUB_RND:
41616   case X86ISD::FMSUBADD_RND:
41617   case X86ISD::FMADDSUB:
41618   case X86ISD::FMSUBADD:    return combineFMADDSUB(N, DAG, Subtarget);
41619   case X86ISD::MOVMSK:      return combineMOVMSK(N, DAG, DCI);
41620   case X86ISD::MGATHER:
41621   case X86ISD::MSCATTER:
41622   case ISD::MGATHER:
41623   case ISD::MSCATTER:       return combineGatherScatter(N, DAG, DCI, Subtarget);
41624   case X86ISD::PCMPEQ:
41625   case X86ISD::PCMPGT:      return combineVectorCompare(N, DAG, Subtarget);
41626   case X86ISD::PMULDQ:
41627   case X86ISD::PMULUDQ:     return combinePMULDQ(N, DAG, DCI);
41628   }
41629 
41630   return SDValue();
41631 }
41632 
isTypeDesirableForOp(unsigned Opc,EVT VT) const41633 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
41634   if (!isTypeLegal(VT))
41635     return false;
41636 
41637   // There are no vXi8 shifts.
41638   if (Opc == ISD::SHL && VT.isVector() && VT.getVectorElementType() == MVT::i8)
41639     return false;
41640 
41641   // 8-bit multiply is probably not much cheaper than 32-bit multiply, and
41642   // we have specializations to turn 32-bit multiply into LEA or other ops.
41643   // Also, see the comment in "IsDesirableToPromoteOp" - where we additionally
41644   // check for a constant operand to the multiply.
41645   if (Opc == ISD::MUL && VT == MVT::i8)
41646     return false;
41647 
41648   // i16 instruction encodings are longer and some i16 instructions are slow,
41649   // so those are not desirable.
41650   if (VT == MVT::i16) {
41651     switch (Opc) {
41652     default:
41653       break;
41654     case ISD::LOAD:
41655     case ISD::SIGN_EXTEND:
41656     case ISD::ZERO_EXTEND:
41657     case ISD::ANY_EXTEND:
41658     case ISD::SHL:
41659     case ISD::SRL:
41660     case ISD::SUB:
41661     case ISD::ADD:
41662     case ISD::MUL:
41663     case ISD::AND:
41664     case ISD::OR:
41665     case ISD::XOR:
41666       return false;
41667     }
41668   }
41669 
41670   // Any legal type not explicitly accounted for above here is desirable.
41671   return true;
41672 }
41673 
expandIndirectJTBranch(const SDLoc & dl,SDValue Value,SDValue Addr,SelectionDAG & DAG) const41674 SDValue X86TargetLowering::expandIndirectJTBranch(const SDLoc& dl,
41675                                                   SDValue Value, SDValue Addr,
41676                                                   SelectionDAG &DAG) const {
41677   const Module *M = DAG.getMachineFunction().getMMI().getModule();
41678   Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
41679   if (IsCFProtectionSupported) {
41680     // In case control-flow branch protection is enabled, we need to add
41681     // notrack prefix to the indirect branch.
41682     // In order to do that we create NT_BRIND SDNode.
41683     // Upon ISEL, the pattern will convert it to jmp with NoTrack prefix.
41684     return DAG.getNode(X86ISD::NT_BRIND, dl, MVT::Other, Value, Addr);
41685   }
41686 
41687   return TargetLowering::expandIndirectJTBranch(dl, Value, Addr, DAG);
41688 }
41689 
IsDesirableToPromoteOp(SDValue Op,EVT & PVT) const41690 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
41691   EVT VT = Op.getValueType();
41692   bool Is8BitMulByConstant = VT == MVT::i8 && Op.getOpcode() == ISD::MUL &&
41693                              isa<ConstantSDNode>(Op.getOperand(1));
41694 
41695   // i16 is legal, but undesirable since i16 instruction encodings are longer
41696   // and some i16 instructions are slow.
41697   // 8-bit multiply-by-constant can usually be expanded to something cheaper
41698   // using LEA and/or other ALU ops.
41699   if (VT != MVT::i16 && !Is8BitMulByConstant)
41700     return false;
41701 
41702   auto IsFoldableRMW = [](SDValue Load, SDValue Op) {
41703     if (!Op.hasOneUse())
41704       return false;
41705     SDNode *User = *Op->use_begin();
41706     if (!ISD::isNormalStore(User))
41707       return false;
41708     auto *Ld = cast<LoadSDNode>(Load);
41709     auto *St = cast<StoreSDNode>(User);
41710     return Ld->getBasePtr() == St->getBasePtr();
41711   };
41712 
41713   auto IsFoldableAtomicRMW = [](SDValue Load, SDValue Op) {
41714     if (!Load.hasOneUse() || Load.getOpcode() != ISD::ATOMIC_LOAD)
41715       return false;
41716     if (!Op.hasOneUse())
41717       return false;
41718     SDNode *User = *Op->use_begin();
41719     if (User->getOpcode() != ISD::ATOMIC_STORE)
41720       return false;
41721     auto *Ld = cast<AtomicSDNode>(Load);
41722     auto *St = cast<AtomicSDNode>(User);
41723     return Ld->getBasePtr() == St->getBasePtr();
41724   };
41725 
41726   bool Commute = false;
41727   switch (Op.getOpcode()) {
41728   default: return false;
41729   case ISD::SIGN_EXTEND:
41730   case ISD::ZERO_EXTEND:
41731   case ISD::ANY_EXTEND:
41732     break;
41733   case ISD::SHL:
41734   case ISD::SRL: {
41735     SDValue N0 = Op.getOperand(0);
41736     // Look out for (store (shl (load), x)).
41737     if (MayFoldLoad(N0) && IsFoldableRMW(N0, Op))
41738       return false;
41739     break;
41740   }
41741   case ISD::ADD:
41742   case ISD::MUL:
41743   case ISD::AND:
41744   case ISD::OR:
41745   case ISD::XOR:
41746     Commute = true;
41747     LLVM_FALLTHROUGH;
41748   case ISD::SUB: {
41749     SDValue N0 = Op.getOperand(0);
41750     SDValue N1 = Op.getOperand(1);
41751     // Avoid disabling potential load folding opportunities.
41752     if (MayFoldLoad(N1) &&
41753         (!Commute || !isa<ConstantSDNode>(N0) ||
41754          (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N1, Op))))
41755       return false;
41756     if (MayFoldLoad(N0) &&
41757         ((Commute && !isa<ConstantSDNode>(N1)) ||
41758          (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N0, Op))))
41759       return false;
41760     if (IsFoldableAtomicRMW(N0, Op) ||
41761         (Commute && IsFoldableAtomicRMW(N1, Op)))
41762       return false;
41763   }
41764   }
41765 
41766   PVT = MVT::i32;
41767   return true;
41768 }
41769 
41770 bool X86TargetLowering::
isDesirableToCombineBuildVectorToShuffleTruncate(ArrayRef<int> ShuffleMask,EVT SrcVT,EVT TruncVT) const41771     isDesirableToCombineBuildVectorToShuffleTruncate(
41772         ArrayRef<int> ShuffleMask, EVT SrcVT, EVT TruncVT) const {
41773 
41774   assert(SrcVT.getVectorNumElements() == ShuffleMask.size() &&
41775          "Element count mismatch");
41776   assert(
41777       Subtarget.getTargetLowering()->isShuffleMaskLegal(ShuffleMask, SrcVT) &&
41778       "Shuffle Mask expected to be legal");
41779 
41780   // For 32-bit elements VPERMD is better than shuffle+truncate.
41781   // TODO: After we improve lowerBuildVector, add execption for VPERMW.
41782   if (SrcVT.getScalarSizeInBits() == 32 || !Subtarget.hasAVX2())
41783     return false;
41784 
41785   if (is128BitLaneCrossingShuffleMask(SrcVT.getSimpleVT(), ShuffleMask))
41786     return false;
41787 
41788   return true;
41789 }
41790 
41791 //===----------------------------------------------------------------------===//
41792 //                           X86 Inline Assembly Support
41793 //===----------------------------------------------------------------------===//
41794 
41795 // Helper to match a string separated by whitespace.
matchAsm(StringRef S,ArrayRef<const char * > Pieces)41796 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
41797   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
41798 
41799   for (StringRef Piece : Pieces) {
41800     if (!S.startswith(Piece)) // Check if the piece matches.
41801       return false;
41802 
41803     S = S.substr(Piece.size());
41804     StringRef::size_type Pos = S.find_first_not_of(" \t");
41805     if (Pos == 0) // We matched a prefix.
41806       return false;
41807 
41808     S = S.substr(Pos);
41809   }
41810 
41811   return S.empty();
41812 }
41813 
clobbersFlagRegisters(const SmallVector<StringRef,4> & AsmPieces)41814 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
41815 
41816   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
41817     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
41818         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
41819         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
41820 
41821       if (AsmPieces.size() == 3)
41822         return true;
41823       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
41824         return true;
41825     }
41826   }
41827   return false;
41828 }
41829 
ExpandInlineAsm(CallInst * CI) const41830 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
41831   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
41832 
41833   const std::string &AsmStr = IA->getAsmString();
41834 
41835   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
41836   if (!Ty || Ty->getBitWidth() % 16 != 0)
41837     return false;
41838 
41839   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
41840   SmallVector<StringRef, 4> AsmPieces;
41841   SplitString(AsmStr, AsmPieces, ";\n");
41842 
41843   switch (AsmPieces.size()) {
41844   default: return false;
41845   case 1:
41846     // FIXME: this should verify that we are targeting a 486 or better.  If not,
41847     // we will turn this bswap into something that will be lowered to logical
41848     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
41849     // lower so don't worry about this.
41850     // bswap $0
41851     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
41852         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
41853         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
41854         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
41855         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
41856         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
41857       // No need to check constraints, nothing other than the equivalent of
41858       // "=r,0" would be valid here.
41859       return IntrinsicLowering::LowerToByteSwap(CI);
41860     }
41861 
41862     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
41863     if (CI->getType()->isIntegerTy(16) &&
41864         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
41865         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
41866          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
41867       AsmPieces.clear();
41868       StringRef ConstraintsStr = IA->getConstraintString();
41869       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
41870       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
41871       if (clobbersFlagRegisters(AsmPieces))
41872         return IntrinsicLowering::LowerToByteSwap(CI);
41873     }
41874     break;
41875   case 3:
41876     if (CI->getType()->isIntegerTy(32) &&
41877         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
41878         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
41879         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
41880         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
41881       AsmPieces.clear();
41882       StringRef ConstraintsStr = IA->getConstraintString();
41883       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
41884       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
41885       if (clobbersFlagRegisters(AsmPieces))
41886         return IntrinsicLowering::LowerToByteSwap(CI);
41887     }
41888 
41889     if (CI->getType()->isIntegerTy(64)) {
41890       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
41891       if (Constraints.size() >= 2 &&
41892           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
41893           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
41894         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
41895         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
41896             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
41897             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
41898           return IntrinsicLowering::LowerToByteSwap(CI);
41899       }
41900     }
41901     break;
41902   }
41903   return false;
41904 }
41905 
41906 /// Given a constraint letter, return the type of constraint for this target.
41907 X86TargetLowering::ConstraintType
getConstraintType(StringRef Constraint) const41908 X86TargetLowering::getConstraintType(StringRef Constraint) const {
41909   if (Constraint.size() == 1) {
41910     switch (Constraint[0]) {
41911     case 'R':
41912     case 'q':
41913     case 'Q':
41914     case 'f':
41915     case 't':
41916     case 'u':
41917     case 'y':
41918     case 'x':
41919     case 'v':
41920     case 'Y':
41921     case 'l':
41922     case 'k': // AVX512 masking registers.
41923       return C_RegisterClass;
41924     case 'a':
41925     case 'b':
41926     case 'c':
41927     case 'd':
41928     case 'S':
41929     case 'D':
41930     case 'A':
41931       return C_Register;
41932     case 'I':
41933     case 'J':
41934     case 'K':
41935     case 'L':
41936     case 'M':
41937     case 'N':
41938     case 'G':
41939     case 'C':
41940     case 'e':
41941     case 'Z':
41942       return C_Other;
41943     default:
41944       break;
41945     }
41946   }
41947   else if (Constraint.size() == 2) {
41948     switch (Constraint[0]) {
41949     default:
41950       break;
41951     case 'Y':
41952       switch (Constraint[1]) {
41953       default:
41954         break;
41955       case 'z':
41956       case '0':
41957         return C_Register;
41958       case 'i':
41959       case 'm':
41960       case 'k':
41961       case 't':
41962       case '2':
41963         return C_RegisterClass;
41964       }
41965     }
41966   }
41967   return TargetLowering::getConstraintType(Constraint);
41968 }
41969 
41970 /// Examine constraint type and operand type and determine a weight value.
41971 /// This object must already have been set up with the operand type
41972 /// and the current alternative constraint selected.
41973 TargetLowering::ConstraintWeight
getSingleConstraintMatchWeight(AsmOperandInfo & info,const char * constraint) const41974   X86TargetLowering::getSingleConstraintMatchWeight(
41975     AsmOperandInfo &info, const char *constraint) const {
41976   ConstraintWeight weight = CW_Invalid;
41977   Value *CallOperandVal = info.CallOperandVal;
41978     // If we don't have a value, we can't do a match,
41979     // but allow it at the lowest weight.
41980   if (!CallOperandVal)
41981     return CW_Default;
41982   Type *type = CallOperandVal->getType();
41983   // Look at the constraint type.
41984   switch (*constraint) {
41985   default:
41986     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
41987     LLVM_FALLTHROUGH;
41988   case 'R':
41989   case 'q':
41990   case 'Q':
41991   case 'a':
41992   case 'b':
41993   case 'c':
41994   case 'd':
41995   case 'S':
41996   case 'D':
41997   case 'A':
41998     if (CallOperandVal->getType()->isIntegerTy())
41999       weight = CW_SpecificReg;
42000     break;
42001   case 'f':
42002   case 't':
42003   case 'u':
42004     if (type->isFloatingPointTy())
42005       weight = CW_SpecificReg;
42006     break;
42007   case 'y':
42008     if (type->isX86_MMXTy() && Subtarget.hasMMX())
42009       weight = CW_SpecificReg;
42010     break;
42011   case 'Y': {
42012     unsigned Size = StringRef(constraint).size();
42013     // Pick 'i' as the next char as 'Yi' and 'Y' are synonymous, when matching 'Y'
42014     char NextChar = Size == 2 ? constraint[1] : 'i';
42015     if (Size > 2)
42016       break;
42017     switch (NextChar) {
42018       default:
42019         return CW_Invalid;
42020       // XMM0
42021       case 'z':
42022       case '0':
42023         if ((type->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1())
42024           return CW_SpecificReg;
42025         return CW_Invalid;
42026       // Conditional OpMask regs (AVX512)
42027       case 'k':
42028         if ((type->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
42029           return CW_Register;
42030         return CW_Invalid;
42031       // Any MMX reg
42032       case 'm':
42033         if (type->isX86_MMXTy() && Subtarget.hasMMX())
42034           return weight;
42035         return CW_Invalid;
42036       // Any SSE reg when ISA >= SSE2, same as 'Y'
42037       case 'i':
42038       case 't':
42039       case '2':
42040         if (!Subtarget.hasSSE2())
42041           return CW_Invalid;
42042         break;
42043     }
42044     // Fall through (handle "Y" constraint).
42045     LLVM_FALLTHROUGH;
42046   }
42047   case 'v':
42048     if ((type->getPrimitiveSizeInBits() == 512) && Subtarget.hasAVX512())
42049       weight = CW_Register;
42050     LLVM_FALLTHROUGH;
42051   case 'x':
42052     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1()) ||
42053         ((type->getPrimitiveSizeInBits() == 256) && Subtarget.hasAVX()))
42054       weight = CW_Register;
42055     break;
42056   case 'k':
42057     // Enable conditional vector operations using %k<#> registers.
42058     if ((type->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
42059       weight = CW_Register;
42060     break;
42061   case 'I':
42062     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
42063       if (C->getZExtValue() <= 31)
42064         weight = CW_Constant;
42065     }
42066     break;
42067   case 'J':
42068     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
42069       if (C->getZExtValue() <= 63)
42070         weight = CW_Constant;
42071     }
42072     break;
42073   case 'K':
42074     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
42075       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
42076         weight = CW_Constant;
42077     }
42078     break;
42079   case 'L':
42080     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
42081       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
42082         weight = CW_Constant;
42083     }
42084     break;
42085   case 'M':
42086     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
42087       if (C->getZExtValue() <= 3)
42088         weight = CW_Constant;
42089     }
42090     break;
42091   case 'N':
42092     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
42093       if (C->getZExtValue() <= 0xff)
42094         weight = CW_Constant;
42095     }
42096     break;
42097   case 'G':
42098   case 'C':
42099     if (isa<ConstantFP>(CallOperandVal)) {
42100       weight = CW_Constant;
42101     }
42102     break;
42103   case 'e':
42104     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
42105       if ((C->getSExtValue() >= -0x80000000LL) &&
42106           (C->getSExtValue() <= 0x7fffffffLL))
42107         weight = CW_Constant;
42108     }
42109     break;
42110   case 'Z':
42111     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
42112       if (C->getZExtValue() <= 0xffffffff)
42113         weight = CW_Constant;
42114     }
42115     break;
42116   }
42117   return weight;
42118 }
42119 
42120 /// Try to replace an X constraint, which matches anything, with another that
42121 /// has more specific requirements based on the type of the corresponding
42122 /// operand.
42123 const char *X86TargetLowering::
LowerXConstraint(EVT ConstraintVT) const42124 LowerXConstraint(EVT ConstraintVT) const {
42125   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
42126   // 'f' like normal targets.
42127   if (ConstraintVT.isFloatingPoint()) {
42128     if (Subtarget.hasSSE2())
42129       return "Y";
42130     if (Subtarget.hasSSE1())
42131       return "x";
42132   }
42133 
42134   return TargetLowering::LowerXConstraint(ConstraintVT);
42135 }
42136 
42137 /// Lower the specified operand into the Ops vector.
42138 /// If it is invalid, don't add anything to Ops.
LowerAsmOperandForConstraint(SDValue Op,std::string & Constraint,std::vector<SDValue> & Ops,SelectionDAG & DAG) const42139 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
42140                                                      std::string &Constraint,
42141                                                      std::vector<SDValue>&Ops,
42142                                                      SelectionDAG &DAG) const {
42143   SDValue Result;
42144 
42145   // Only support length 1 constraints for now.
42146   if (Constraint.length() > 1) return;
42147 
42148   char ConstraintLetter = Constraint[0];
42149   switch (ConstraintLetter) {
42150   default: break;
42151   case 'I':
42152     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
42153       if (C->getZExtValue() <= 31) {
42154         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
42155                                        Op.getValueType());
42156         break;
42157       }
42158     }
42159     return;
42160   case 'J':
42161     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
42162       if (C->getZExtValue() <= 63) {
42163         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
42164                                        Op.getValueType());
42165         break;
42166       }
42167     }
42168     return;
42169   case 'K':
42170     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
42171       if (isInt<8>(C->getSExtValue())) {
42172         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
42173                                        Op.getValueType());
42174         break;
42175       }
42176     }
42177     return;
42178   case 'L':
42179     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
42180       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
42181           (Subtarget.is64Bit() && C->getZExtValue() == 0xffffffff)) {
42182         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
42183                                        Op.getValueType());
42184         break;
42185       }
42186     }
42187     return;
42188   case 'M':
42189     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
42190       if (C->getZExtValue() <= 3) {
42191         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
42192                                        Op.getValueType());
42193         break;
42194       }
42195     }
42196     return;
42197   case 'N':
42198     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
42199       if (C->getZExtValue() <= 255) {
42200         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
42201                                        Op.getValueType());
42202         break;
42203       }
42204     }
42205     return;
42206   case 'O':
42207     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
42208       if (C->getZExtValue() <= 127) {
42209         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
42210                                        Op.getValueType());
42211         break;
42212       }
42213     }
42214     return;
42215   case 'e': {
42216     // 32-bit signed value
42217     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
42218       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
42219                                            C->getSExtValue())) {
42220         // Widen to 64 bits here to get it sign extended.
42221         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
42222         break;
42223       }
42224     // FIXME gcc accepts some relocatable values here too, but only in certain
42225     // memory models; it's complicated.
42226     }
42227     return;
42228   }
42229   case 'Z': {
42230     // 32-bit unsigned value
42231     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
42232       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
42233                                            C->getZExtValue())) {
42234         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
42235                                        Op.getValueType());
42236         break;
42237       }
42238     }
42239     // FIXME gcc accepts some relocatable values here too, but only in certain
42240     // memory models; it's complicated.
42241     return;
42242   }
42243   case 'i': {
42244     // Literal immediates are always ok.
42245     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
42246       // Widen to 64 bits here to get it sign extended.
42247       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
42248       break;
42249     }
42250 
42251     // In any sort of PIC mode addresses need to be computed at runtime by
42252     // adding in a register or some sort of table lookup.  These can't
42253     // be used as immediates.
42254     if (Subtarget.isPICStyleGOT() || Subtarget.isPICStyleStubPIC())
42255       return;
42256 
42257     // If we are in non-pic codegen mode, we allow the address of a global (with
42258     // an optional displacement) to be used with 'i'.
42259     GlobalAddressSDNode *GA = nullptr;
42260     int64_t Offset = 0;
42261 
42262     // Match either (GA), (GA+C), (GA+C1+C2), etc.
42263     while (1) {
42264       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
42265         Offset += GA->getOffset();
42266         break;
42267       } else if (Op.getOpcode() == ISD::ADD) {
42268         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
42269           Offset += C->getZExtValue();
42270           Op = Op.getOperand(0);
42271           continue;
42272         }
42273       } else if (Op.getOpcode() == ISD::SUB) {
42274         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
42275           Offset += -C->getZExtValue();
42276           Op = Op.getOperand(0);
42277           continue;
42278         }
42279       }
42280 
42281       // Otherwise, this isn't something we can handle, reject it.
42282       return;
42283     }
42284 
42285     const GlobalValue *GV = GA->getGlobal();
42286     // If we require an extra load to get this address, as in PIC mode, we
42287     // can't accept it.
42288     if (isGlobalStubReference(Subtarget.classifyGlobalReference(GV)))
42289       return;
42290 
42291     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
42292                                         GA->getValueType(0), Offset);
42293     break;
42294   }
42295   }
42296 
42297   if (Result.getNode()) {
42298     Ops.push_back(Result);
42299     return;
42300   }
42301   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
42302 }
42303 
42304 /// Check if \p RC is a general purpose register class.
42305 /// I.e., GR* or one of their variant.
isGRClass(const TargetRegisterClass & RC)42306 static bool isGRClass(const TargetRegisterClass &RC) {
42307   return RC.hasSuperClassEq(&X86::GR8RegClass) ||
42308          RC.hasSuperClassEq(&X86::GR16RegClass) ||
42309          RC.hasSuperClassEq(&X86::GR32RegClass) ||
42310          RC.hasSuperClassEq(&X86::GR64RegClass) ||
42311          RC.hasSuperClassEq(&X86::LOW32_ADDR_ACCESS_RBPRegClass);
42312 }
42313 
42314 /// Check if \p RC is a vector register class.
42315 /// I.e., FR* / VR* or one of their variant.
isFRClass(const TargetRegisterClass & RC)42316 static bool isFRClass(const TargetRegisterClass &RC) {
42317   return RC.hasSuperClassEq(&X86::FR32XRegClass) ||
42318          RC.hasSuperClassEq(&X86::FR64XRegClass) ||
42319          RC.hasSuperClassEq(&X86::VR128XRegClass) ||
42320          RC.hasSuperClassEq(&X86::VR256XRegClass) ||
42321          RC.hasSuperClassEq(&X86::VR512RegClass);
42322 }
42323 
42324 std::pair<unsigned, const TargetRegisterClass *>
getRegForInlineAsmConstraint(const TargetRegisterInfo * TRI,StringRef Constraint,MVT VT) const42325 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
42326                                                 StringRef Constraint,
42327                                                 MVT VT) const {
42328   // First, see if this is a constraint that directly corresponds to an LLVM
42329   // register class.
42330   if (Constraint.size() == 1) {
42331     // GCC Constraint Letters
42332     switch (Constraint[0]) {
42333     default: break;
42334       // TODO: Slight differences here in allocation order and leaving
42335       // RIP in the class. Do they matter any more here than they do
42336       // in the normal allocation?
42337     case 'k':
42338       if (Subtarget.hasAVX512()) {
42339         //  Only supported in AVX512 or later.
42340         switch (VT.SimpleTy) {
42341         default: break;
42342         case MVT::i32:
42343           return std::make_pair(0U, &X86::VK32RegClass);
42344         case MVT::i16:
42345           return std::make_pair(0U, &X86::VK16RegClass);
42346         case MVT::i8:
42347           return std::make_pair(0U, &X86::VK8RegClass);
42348         case MVT::i1:
42349           return std::make_pair(0U, &X86::VK1RegClass);
42350         case MVT::i64:
42351           return std::make_pair(0U, &X86::VK64RegClass);
42352         }
42353       }
42354       break;
42355     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
42356       if (Subtarget.is64Bit()) {
42357         if (VT == MVT::i32 || VT == MVT::f32)
42358           return std::make_pair(0U, &X86::GR32RegClass);
42359         if (VT == MVT::i16)
42360           return std::make_pair(0U, &X86::GR16RegClass);
42361         if (VT == MVT::i8 || VT == MVT::i1)
42362           return std::make_pair(0U, &X86::GR8RegClass);
42363         if (VT == MVT::i64 || VT == MVT::f64)
42364           return std::make_pair(0U, &X86::GR64RegClass);
42365         break;
42366       }
42367       LLVM_FALLTHROUGH;
42368       // 32-bit fallthrough
42369     case 'Q':   // Q_REGS
42370       if (VT == MVT::i32 || VT == MVT::f32)
42371         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
42372       if (VT == MVT::i16)
42373         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
42374       if (VT == MVT::i8 || VT == MVT::i1)
42375         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
42376       if (VT == MVT::i64)
42377         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
42378       break;
42379     case 'r':   // GENERAL_REGS
42380     case 'l':   // INDEX_REGS
42381       if (VT == MVT::i8 || VT == MVT::i1)
42382         return std::make_pair(0U, &X86::GR8RegClass);
42383       if (VT == MVT::i16)
42384         return std::make_pair(0U, &X86::GR16RegClass);
42385       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget.is64Bit())
42386         return std::make_pair(0U, &X86::GR32RegClass);
42387       return std::make_pair(0U, &X86::GR64RegClass);
42388     case 'R':   // LEGACY_REGS
42389       if (VT == MVT::i8 || VT == MVT::i1)
42390         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
42391       if (VT == MVT::i16)
42392         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
42393       if (VT == MVT::i32 || !Subtarget.is64Bit())
42394         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
42395       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
42396     case 'f':  // FP Stack registers.
42397       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
42398       // value to the correct fpstack register class.
42399       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
42400         return std::make_pair(0U, &X86::RFP32RegClass);
42401       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
42402         return std::make_pair(0U, &X86::RFP64RegClass);
42403       return std::make_pair(0U, &X86::RFP80RegClass);
42404     case 'y':   // MMX_REGS if MMX allowed.
42405       if (!Subtarget.hasMMX()) break;
42406       return std::make_pair(0U, &X86::VR64RegClass);
42407     case 'Y':   // SSE_REGS if SSE2 allowed
42408       if (!Subtarget.hasSSE2()) break;
42409       LLVM_FALLTHROUGH;
42410     case 'v':
42411     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
42412       if (!Subtarget.hasSSE1()) break;
42413       bool VConstraint = (Constraint[0] == 'v');
42414 
42415       switch (VT.SimpleTy) {
42416       default: break;
42417       // Scalar SSE types.
42418       case MVT::f32:
42419       case MVT::i32:
42420         if (VConstraint && Subtarget.hasAVX512() && Subtarget.hasVLX())
42421           return std::make_pair(0U, &X86::FR32XRegClass);
42422         return std::make_pair(0U, &X86::FR32RegClass);
42423       case MVT::f64:
42424       case MVT::i64:
42425         if (VConstraint && Subtarget.hasVLX())
42426           return std::make_pair(0U, &X86::FR64XRegClass);
42427         return std::make_pair(0U, &X86::FR64RegClass);
42428       // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
42429       // Vector types.
42430       case MVT::v16i8:
42431       case MVT::v8i16:
42432       case MVT::v4i32:
42433       case MVT::v2i64:
42434       case MVT::v4f32:
42435       case MVT::v2f64:
42436         if (VConstraint && Subtarget.hasVLX())
42437           return std::make_pair(0U, &X86::VR128XRegClass);
42438         return std::make_pair(0U, &X86::VR128RegClass);
42439       // AVX types.
42440       case MVT::v32i8:
42441       case MVT::v16i16:
42442       case MVT::v8i32:
42443       case MVT::v4i64:
42444       case MVT::v8f32:
42445       case MVT::v4f64:
42446         if (VConstraint && Subtarget.hasVLX())
42447           return std::make_pair(0U, &X86::VR256XRegClass);
42448         return std::make_pair(0U, &X86::VR256RegClass);
42449       case MVT::v8f64:
42450       case MVT::v16f32:
42451       case MVT::v16i32:
42452       case MVT::v8i64:
42453         return std::make_pair(0U, &X86::VR512RegClass);
42454       }
42455       break;
42456     }
42457   } else if (Constraint.size() == 2 && Constraint[0] == 'Y') {
42458     switch (Constraint[1]) {
42459     default:
42460       break;
42461     case 'i':
42462     case 't':
42463     case '2':
42464       return getRegForInlineAsmConstraint(TRI, "Y", VT);
42465     case 'm':
42466       if (!Subtarget.hasMMX()) break;
42467       return std::make_pair(0U, &X86::VR64RegClass);
42468     case 'z':
42469     case '0':
42470       if (!Subtarget.hasSSE1()) break;
42471       return std::make_pair(X86::XMM0, &X86::VR128RegClass);
42472     case 'k':
42473       // This register class doesn't allocate k0 for masked vector operation.
42474       if (Subtarget.hasAVX512()) { // Only supported in AVX512.
42475         switch (VT.SimpleTy) {
42476         default: break;
42477         case MVT::i32:
42478           return std::make_pair(0U, &X86::VK32WMRegClass);
42479         case MVT::i16:
42480           return std::make_pair(0U, &X86::VK16WMRegClass);
42481         case MVT::i8:
42482           return std::make_pair(0U, &X86::VK8WMRegClass);
42483         case MVT::i1:
42484           return std::make_pair(0U, &X86::VK1WMRegClass);
42485         case MVT::i64:
42486           return std::make_pair(0U, &X86::VK64WMRegClass);
42487         }
42488       }
42489       break;
42490     }
42491   }
42492 
42493   // Use the default implementation in TargetLowering to convert the register
42494   // constraint into a member of a register class.
42495   std::pair<unsigned, const TargetRegisterClass*> Res;
42496   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
42497 
42498   // Not found as a standard register?
42499   if (!Res.second) {
42500     // Map st(0) -> st(7) -> ST0
42501     if (Constraint.size() == 7 && Constraint[0] == '{' &&
42502         tolower(Constraint[1]) == 's' && tolower(Constraint[2]) == 't' &&
42503         Constraint[3] == '(' &&
42504         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
42505         Constraint[5] == ')' && Constraint[6] == '}') {
42506       // st(7) is not allocatable and thus not a member of RFP80. Return
42507       // singleton class in cases where we have a reference to it.
42508       if (Constraint[4] == '7')
42509         return std::make_pair(X86::FP7, &X86::RFP80_7RegClass);
42510       return std::make_pair(X86::FP0 + Constraint[4] - '0',
42511                             &X86::RFP80RegClass);
42512     }
42513 
42514     // GCC allows "st(0)" to be called just plain "st".
42515     if (StringRef("{st}").equals_lower(Constraint))
42516       return std::make_pair(X86::FP0, &X86::RFP80RegClass);
42517 
42518     // flags -> EFLAGS
42519     if (StringRef("{flags}").equals_lower(Constraint))
42520       return std::make_pair(X86::EFLAGS, &X86::CCRRegClass);
42521 
42522     // dirflag -> DF
42523     if (StringRef("{dirflag}").equals_lower(Constraint))
42524       return std::make_pair(X86::DF, &X86::DFCCRRegClass);
42525 
42526     // fpsr -> FPSW
42527     if (StringRef("{fpsr}").equals_lower(Constraint))
42528       return std::make_pair(X86::FPSW, &X86::FPCCRRegClass);
42529 
42530     // 'A' means [ER]AX + [ER]DX.
42531     if (Constraint == "A") {
42532       if (Subtarget.is64Bit())
42533         return std::make_pair(X86::RAX, &X86::GR64_ADRegClass);
42534       assert((Subtarget.is32Bit() || Subtarget.is16Bit()) &&
42535              "Expecting 64, 32 or 16 bit subtarget");
42536       return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
42537     }
42538     return Res;
42539   }
42540 
42541   // Make sure it isn't a register that requires 64-bit mode.
42542   if (!Subtarget.is64Bit() &&
42543       (isFRClass(*Res.second) || isGRClass(*Res.second)) &&
42544       TRI->getEncodingValue(Res.first) >= 8) {
42545     // Register requires REX prefix, but we're in 32-bit mode.
42546     return std::make_pair(0, nullptr);
42547   }
42548 
42549   // Make sure it isn't a register that requires AVX512.
42550   if (!Subtarget.hasAVX512() && isFRClass(*Res.second) &&
42551       TRI->getEncodingValue(Res.first) & 0x10) {
42552     // Register requires EVEX prefix.
42553     return std::make_pair(0, nullptr);
42554   }
42555 
42556   // Otherwise, check to see if this is a register class of the wrong value
42557   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
42558   // turn into {ax},{dx}.
42559   // MVT::Other is used to specify clobber names.
42560   if (TRI->isTypeLegalForClass(*Res.second, VT) || VT == MVT::Other)
42561     return Res;   // Correct type already, nothing to do.
42562 
42563   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
42564   // return "eax". This should even work for things like getting 64bit integer
42565   // registers when given an f64 type.
42566   const TargetRegisterClass *Class = Res.second;
42567   // The generic code will match the first register class that contains the
42568   // given register. Thus, based on the ordering of the tablegened file,
42569   // the "plain" GR classes might not come first.
42570   // Therefore, use a helper method.
42571   if (isGRClass(*Class)) {
42572     unsigned Size = VT.getSizeInBits();
42573     if (Size == 1) Size = 8;
42574     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
42575     if (DestReg > 0) {
42576       bool is64Bit = Subtarget.is64Bit();
42577       const TargetRegisterClass *RC =
42578           Size == 8 ? (is64Bit ? &X86::GR8RegClass : &X86::GR8_NOREXRegClass)
42579         : Size == 16 ? (is64Bit ? &X86::GR16RegClass : &X86::GR16_NOREXRegClass)
42580         : Size == 32 ? (is64Bit ? &X86::GR32RegClass : &X86::GR32_NOREXRegClass)
42581         : Size == 64 ? (is64Bit ? &X86::GR64RegClass : nullptr)
42582         : nullptr;
42583       if (Size == 64 && !is64Bit) {
42584         // Model GCC's behavior here and select a fixed pair of 32-bit
42585         // registers.
42586         switch (Res.first) {
42587         case X86::EAX:
42588           return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
42589         case X86::EDX:
42590           return std::make_pair(X86::EDX, &X86::GR32_DCRegClass);
42591         case X86::ECX:
42592           return std::make_pair(X86::ECX, &X86::GR32_CBRegClass);
42593         case X86::EBX:
42594           return std::make_pair(X86::EBX, &X86::GR32_BSIRegClass);
42595         case X86::ESI:
42596           return std::make_pair(X86::ESI, &X86::GR32_SIDIRegClass);
42597         case X86::EDI:
42598           return std::make_pair(X86::EDI, &X86::GR32_DIBPRegClass);
42599         case X86::EBP:
42600           return std::make_pair(X86::EBP, &X86::GR32_BPSPRegClass);
42601         default:
42602           return std::make_pair(0, nullptr);
42603         }
42604       }
42605       if (RC && RC->contains(DestReg))
42606         return std::make_pair(DestReg, RC);
42607       return Res;
42608     }
42609     // No register found/type mismatch.
42610     return std::make_pair(0, nullptr);
42611   } else if (isFRClass(*Class)) {
42612     // Handle references to XMM physical registers that got mapped into the
42613     // wrong class.  This can happen with constraints like {xmm0} where the
42614     // target independent register mapper will just pick the first match it can
42615     // find, ignoring the required type.
42616 
42617     // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
42618     if (VT == MVT::f32 || VT == MVT::i32)
42619       Res.second = &X86::FR32RegClass;
42620     else if (VT == MVT::f64 || VT == MVT::i64)
42621       Res.second = &X86::FR64RegClass;
42622     else if (TRI->isTypeLegalForClass(X86::VR128RegClass, VT))
42623       Res.second = &X86::VR128RegClass;
42624     else if (TRI->isTypeLegalForClass(X86::VR256RegClass, VT))
42625       Res.second = &X86::VR256RegClass;
42626     else if (TRI->isTypeLegalForClass(X86::VR512RegClass, VT))
42627       Res.second = &X86::VR512RegClass;
42628     else {
42629       // Type mismatch and not a clobber: Return an error;
42630       Res.first = 0;
42631       Res.second = nullptr;
42632     }
42633   }
42634 
42635   return Res;
42636 }
42637 
getScalingFactorCost(const DataLayout & DL,const AddrMode & AM,Type * Ty,unsigned AS) const42638 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
42639                                             const AddrMode &AM, Type *Ty,
42640                                             unsigned AS) const {
42641   // Scaling factors are not free at all.
42642   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
42643   // will take 2 allocations in the out of order engine instead of 1
42644   // for plain addressing mode, i.e. inst (reg1).
42645   // E.g.,
42646   // vaddps (%rsi,%rdx), %ymm0, %ymm1
42647   // Requires two allocations (one for the load, one for the computation)
42648   // whereas:
42649   // vaddps (%rsi), %ymm0, %ymm1
42650   // Requires just 1 allocation, i.e., freeing allocations for other operations
42651   // and having less micro operations to execute.
42652   //
42653   // For some X86 architectures, this is even worse because for instance for
42654   // stores, the complex addressing mode forces the instruction to use the
42655   // "load" ports instead of the dedicated "store" port.
42656   // E.g., on Haswell:
42657   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
42658   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
42659   if (isLegalAddressingMode(DL, AM, Ty, AS))
42660     // Scale represents reg2 * scale, thus account for 1
42661     // as soon as we use a second register.
42662     return AM.Scale != 0;
42663   return -1;
42664 }
42665 
isIntDivCheap(EVT VT,AttributeList Attr) const42666 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
42667   // Integer division on x86 is expensive. However, when aggressively optimizing
42668   // for code size, we prefer to use a div instruction, as it is usually smaller
42669   // than the alternative sequence.
42670   // The exception to this is vector division. Since x86 doesn't have vector
42671   // integer division, leaving the division as-is is a loss even in terms of
42672   // size, because it will have to be scalarized, while the alternative code
42673   // sequence can be performed in vector form.
42674   bool OptSize =
42675       Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
42676   return OptSize && !VT.isVector();
42677 }
42678 
initializeSplitCSR(MachineBasicBlock * Entry) const42679 void X86TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
42680   if (!Subtarget.is64Bit())
42681     return;
42682 
42683   // Update IsSplitCSR in X86MachineFunctionInfo.
42684   X86MachineFunctionInfo *AFI =
42685     Entry->getParent()->getInfo<X86MachineFunctionInfo>();
42686   AFI->setIsSplitCSR(true);
42687 }
42688 
insertCopiesSplitCSR(MachineBasicBlock * Entry,const SmallVectorImpl<MachineBasicBlock * > & Exits) const42689 void X86TargetLowering::insertCopiesSplitCSR(
42690     MachineBasicBlock *Entry,
42691     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
42692   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
42693   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
42694   if (!IStart)
42695     return;
42696 
42697   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
42698   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
42699   MachineBasicBlock::iterator MBBI = Entry->begin();
42700   for (const MCPhysReg *I = IStart; *I; ++I) {
42701     const TargetRegisterClass *RC = nullptr;
42702     if (X86::GR64RegClass.contains(*I))
42703       RC = &X86::GR64RegClass;
42704     else
42705       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
42706 
42707     unsigned NewVR = MRI->createVirtualRegister(RC);
42708     // Create copy from CSR to a virtual register.
42709     // FIXME: this currently does not emit CFI pseudo-instructions, it works
42710     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
42711     // nounwind. If we want to generalize this later, we may need to emit
42712     // CFI pseudo-instructions.
42713     assert(Entry->getParent()->getFunction().hasFnAttribute(
42714                Attribute::NoUnwind) &&
42715            "Function should be nounwind in insertCopiesSplitCSR!");
42716     Entry->addLiveIn(*I);
42717     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
42718         .addReg(*I);
42719 
42720     // Insert the copy-back instructions right before the terminator.
42721     for (auto *Exit : Exits)
42722       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
42723               TII->get(TargetOpcode::COPY), *I)
42724           .addReg(NewVR);
42725   }
42726 }
42727 
supportSwiftError() const42728 bool X86TargetLowering::supportSwiftError() const {
42729   return Subtarget.is64Bit();
42730 }
42731 
42732 /// Returns the name of the symbol used to emit stack probes or the empty
42733 /// string if not applicable.
getStackProbeSymbolName(MachineFunction & MF) const42734 StringRef X86TargetLowering::getStackProbeSymbolName(MachineFunction &MF) const {
42735   // If the function specifically requests stack probes, emit them.
42736   if (MF.getFunction().hasFnAttribute("probe-stack"))
42737     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString();
42738 
42739   // Generally, if we aren't on Windows, the platform ABI does not include
42740   // support for stack probes, so don't emit them.
42741   if (!Subtarget.isOSWindows() || Subtarget.isTargetMachO() ||
42742       MF.getFunction().hasFnAttribute("no-stack-arg-probe"))
42743     return "";
42744 
42745   // We need a stack probe to conform to the Windows ABI. Choose the right
42746   // symbol.
42747   if (Subtarget.is64Bit())
42748     return Subtarget.isTargetCygMing() ? "___chkstk_ms" : "__chkstk";
42749   return Subtarget.isTargetCygMing() ? "_alloca" : "_chkstk";
42750 }
42751